UNPKG

@verdocs/js-sdk

Version:

Isomorphic JS/TS SDK providing types and API wrappers for the Verdocs platform for Node and browser clients

3,803 lines • 165 kB
'use strict';

var axios = require('axios');

const FIELD_TYPES = [
    'textbox',
    'signature',
    'initial',
    'date',
    'dropdown',
    'timestamp',
    /** @deprecated. Use `textbox` with multiLine set to > 1 */
    'textarea',
    'checkbox',
    'radio',
    'attachment',
    'payment',
];
const DEFAULT_FIELD_WIDTHS = {
    signature: 71,
    initial: 71,
    date: 75,
    timestamp: 130,
    textbox: 150,
    textarea: 150,
    checkbox: 14,
    radio: 14,
    dropdown: 85,
    attachment: 24,
    payment: 24,
};
const DEFAULT_FIELD_HEIGHTS = {
    signature: 36,
    initial: 36,
    date: 15,
    timestamp: 15,
    textbox: 15,
    textarea: 41,
    checkbox: 14,
    radio: 14,
    dropdown: 20,
    attachment: 24,
    payment: 24,
};
const WEBHOOK_EVENTS = [
    'envelope_created',
    'envelope_completed',
    'envelope_canceled',
    'template_created',
    'template_updated',
    'template_deleted',
    'template_used',
];
const ALL_PERMISSIONS = [
    // TODO: Are these permissions still relevant?
    // 'member:view',
    // 'org:create',
    // 'org:view',
    // 'org:list',
    // 'org:transfer',
    'template:creator:create:public',
    'template:creator:create:org',
    'template:creator:create:personal',
    'template:creator:delete',
    'template:creator:visibility',
    'template:member:read',
    'template:member:write',
    'template:member:delete',
    'template:member:visibility',
    'owner:add',
    'owner:remove',
    'admin:add',
    'admin:remove',
    'member:view',
    'member:add',
    'member:remove',
    'org:create',
    'org:view',
    'org:update',
    'org:delete',
    'org:transfer',
    'org:list',
    'envelope:create',
    'envelope:cancel',
    'envelope:view',
];

/**
 * Given a `rgba(r,g,b,a)` string value, returns the hex equivalent, dropping the alpha channel.
 */
function getRGB(rgba) {
    const rgbNumbers = rgba.replace('rgba(', '').replace(')', '').split(',');
    const rgbObject = {
        red: +rgbNumbers[0],
        green: +rgbNumbers[1],
        blue: +rgbNumbers[2],
        alpha: +rgbNumbers[3],
    };
    const alpha = 1 - rgbObject.alpha;
    const red = Math.round((rgbObject.alpha * (rgbObject.red / 255) + alpha) * 255);
    const green = Math.round((rgbObject.alpha * (rgbObject.green / 255) + alpha) * 255);
    const blue = Math.round((rgbObject.alpha * (rgbObject.blue / 255) + alpha) * 255);
    return '#' + rgbToHex(red) + rgbToHex(green) + rgbToHex(blue);
}
/**
 * Given an RGB string value, returns the hex equivalent.
 */
function rgbToHex(rgb) {
    const hex = rgb.toString(16);
    if (hex.length < 2) {
        return '0' + hex;
    }
    return hex;
}
/**
 * Given a signer role index, return the color code for that signer.
 */
function getRGBA(roleIndex) {
    switch (roleIndex % 10) {
        case 0:
            return roleIndex === 0 ? 'rgba(255, 193, 7, 0.4)' : 'rgba(134, 134, 134, 0.3)'; // #FFE69C
        case 1:
            return 'rgba(156, 39, 176, .4)'; // '#E3C3E9'
        case 2:
            return 'rgba(33, 150, 243, .4)'; // '#C1E1FB'
        case 3:
            return 'rgba(220, 231, 117, 0.3)';
        case 4:
            return 'rgba(121, 134, 203, 0.3)';
        case 5:
            return 'rgba(77, 182, 172, 0.3)';
        case 6:
            return 'rgba(255, 202, 165, 0.3)';
        case 7:
            return 'rgba(2, 247, 190, 0.3)';
        case 8:
            return 'rgba(255, 138, 101, 0.3)';
        case 9:
            return 'rgba(82, 255, 79, 0.3)';
        default:
            return 'rgba(229, 115, 155, 0.3)';
    }
}
/**
 * Given a role name, return a color code for it. This works by computing a hash code so the specific color returned
 * is not specified explicitly, but will be the same for every call with the same input value.
 */
function nameToRGBA(str) {
    if (!!str) {
        const validNum = parseInt(str.slice(-1), 10);
        if (!isNaN(validNum)) {
            str += (validNum * 99).toString();
        }
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            // tslint:disable-next-line:no-bitwise
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        hash = Math.round(hash / 1.3);
        // tslint:disable-next-line:no-bitwise
        const c = (hash & 0x00ffff08).toString(16).toUpperCase();
        const hex = '#' + '00000'.substring(0, 6 - c.length) + c;
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        const color = {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16),
        };
        return `rgba(${color.r}, ${color.g}, ${color.b}, 0.2)`;
    }
}
/**
 * Helper function to obtain a color code given a role name given various possible inputs.
 */
function getRoleColor(name, roles, index) {
    if (index) {
        return getRGBA(index);
    }
    else if (roles && roles.length > 0) {
        const roleIndex = roles.findIndex((role) => role === name);
        if (roleIndex > -1) {
            return getRGBA(roleIndex);
        }
        else {
            return nameToRGBA(name);
        }
    }
    else {
        return nameToRGBA(name);
    }
}

const YEAR = 365 * 24 * 60 * 60;
// const MONTH = 30 * 24 * 60 * 60;
const WEEK = 7 * 24 * 60 * 60;
const DAY = 24 * 60 * 60;
const HOUR = 60 * 60;
const MINUTE = 60;
const formatShortTimeAgo = (val) => {
    if (val === undefined || val === null) {
        return '';
    }
    let dateInput;
    if (typeof val === 'string' || typeof val === 'number') {
        dateInput = new Date(val);
    }
    else if (typeof val === 'object') {
        dateInput = val;
    }
    else {
        return '';
    }
    const timeDiff = Math.floor((new Date().getTime() - dateInput.getTime()) / 1000);
    if (timeDiff >= YEAR) {
        return Math.floor(timeDiff / YEAR) + 'Y';
    }
    // if (timeDiff >= MONTH) {
    //   return Math.floor(timeDiff / MONTH) + 'M';
    // }
    if (timeDiff >= WEEK) {
        return Math.floor(timeDiff / WEEK) + 'W';
    }
    if (timeDiff >= DAY) {
        return Math.floor(timeDiff / DAY) + 'D';
    }
    if (timeDiff >= HOUR) {
        return Math.floor(timeDiff / HOUR) + 'H';
    }
    if (timeDiff >= MINUTE) {
        return Math.floor(timeDiff / MINUTE) + 'M';
    }
    return `${timeDiff}S`;
};

const collapseEntitlements = (entitlements) => {
    const now = new Date();
    const activeEntitlements = {};
    entitlements.forEach((entitlement) => {
        const start = new Date(entitlement.starts_at);
        const end = new Date(entitlement.ends_at);
        if (now >= start && now <= end && !activeEntitlements[entitlement.feature]) {
            activeEntitlements[entitlement.feature] = entitlement;
        }
    });
    return activeEntitlements;
};

function getRTop(y, fieldHeight, iTextHeight, yRatio) {
    return iTextHeight - (y + fieldHeight) * yRatio;
}
function getRLeft(x, ratio) {
    return x * ratio;
}
function getRValue(y, ratio) {
    return y * ratio;
}
function blobToBase64(image) {
    const fileReader = new FileReader();
    return new Promise((resolve, reject) => {
        fileReader.onerror = () => {
            reject(new DOMException('Problem reading blob.'));
        };
        fileReader.onload = () => {
            resolve(fileReader.result);
        };
        fileReader.readAsDataURL(image);
    });
}
function rescale(r, n) {
    return r * n;
}
/**
 * Utility function to sort fields by page, then by Y coordinate, then by X coordinate.
 * NOTE: This function mutates the input array.
 */
function sortFields(fields) {
    fields.sort((a, b) => {
        const aPage = a.page || 0;
        const bPage = b.page || 0;
        const aX = a.x || 0;
        const aY = (a.y || 0) + (a.height || 0);
        const bX = b.x || 0;
        const bY = (b.y || 0) + (b.height || 0);
        if (aPage !== bPage) {
            return aPage - bPage;
        }
        // NOTE: Logic looks a little strange X vs Y. It's because we go top down,
        // left to right. But Y coordinates are inverted in PDFs. The reason for
        // the division is because no human makes perfect templates and frequently
        // two fields on the "same line" will be slightly offset vertically.
        const divaY = Math.floor(aY / 5);
        const divbY = Math.floor(bY / 5);
        if (divaY !== divbY) {
            return divbY - divaY;
        }
        return aX - bX;
    });
    return fields;
}

/**
 * Given a File, extract the file's content as a base64 encoded data URL. The response will have a prefix that
 * includes the MIME type of the file, e.g. "data:image/jpeg;base64,iVBORw0K......"
 */
const fileToDataUrl = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve({
        lastModified: file.lastModified,
        size: file.size,
        type: file.type,
        name: file.name,
        data: reader.result,
    });
    reader.onerror = reject;
    if (file) {
        reader.readAsDataURL(file);
    }
    else {
        reject(new Error('Invalid file'));
    }
});
/**
 * Trigger a download dialog to save a blob as a file on disk.
 */
const downloadBlob = (blob, name = 'file.pdf') => {
    const blobUrl = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = name;
    document.body.appendChild(link);
    link.dispatchEvent(new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
    }));
    document.body.removeChild(link);
};

const Countries = [
    { code: '+7 840', name: 'Abkhazia', value: '+7' },
    { code: '+93', name: 'Afghanistan', value: '+93' },
    { code: '+355', name: 'Albania', value: '+355' },
    { code: '+213', name: 'Algeria', value: '+213' },
    { code: '+1', name: 'American Samoa', value: '+1' },
    { code: '+376', name: 'Andorra', value: '+376' },
    { code: '+244', name: 'Angola', value: '+244' },
    { code: '+1', name: 'Anguilla', value: '+1' },
    { code: '+1', name: 'Antigua and Barbuda', value: '+1' },
    { code: '+54', name: 'Argentina', value: '+54' },
    { code: '+374', name: 'Armenia', value: '+374' },
    { code: '+297', name: 'Aruba', value: '+297' },
    { code: '+247', name: 'Ascension', value: '+247' },
    { code: '+61', name: 'Australia', value: '+61' },
    { code: '+672', name: 'Australian External Territories', value: '+672' },
    { code: '+43', name: 'Austria', value: '+43' },
    { code: '+994', name: 'Azerbaijan', value: '+994' },
    { code: '+1', name: 'Bahamas', value: '+1' },
    { code: '+973', name: 'Bahrain', value: '+973' },
    { code: '+880', name: 'Bangladesh', value: '+880' },
    { code: '+1', name: 'Barbados', value: '+1' },
    { code: '+1', name: 'Barbuda', value: '+1' },
    { code: '+375', name: 'Belarus', value: '+375' },
    { code: '+32', name: 'Belgium', value: '+32' },
    { code: '+501', name: 'Belize', value: '+501' },
    { code: '+229', name: 'Benin', value: '+229' },
    { code: '+1', name: 'Bermuda', value: '+1' },
    { code: '+975', name: 'Bhutan', value: '+975' },
    { code: '+591', name: 'Bolivia', value: '+591' },
    { code: '+387', name: 'Bosnia and Herzegovina', value: '+387' },
    { code: '+267', name: 'Botswana', value: '+267' },
    { code: '+55', name: 'Brazil', value: '+55' },
    { code: '+246', name: 'British Indian Ocean Territory', value: '+246' },
    { code: '+1', name: 'British Virgin Islands', value: '+1' },
    { code: '+673', name: 'Brunei', value: '+673' },
    { code: '+359', name: 'Bulgaria', value: '+359' },
    { code: '+226', name: 'Burkina Faso', value: '+226' },
    { code: '+257', name: 'Burundi', value: '+257' },
    { code: '+855', name: 'Cambodia', value: '+855' },
    { code: '+237', name: 'Cameroon', value: '+237' },
    { code: '+1', name: 'Canada', value: '+1' },
    { code: '+238', name: 'Cape Verde', value: '+238' },
    { code: '+1', name: 'Cayman Islands', value: '+1' },
    { code: '+236', name: 'Central African Republic', value: '+236' },
    { code: '+235', name: 'Chad', value: '+235' },
    { code: '+56', name: 'Chile', value: '+56' },
    { code: '+86', name: 'China', value: '+86' },
    { code: '+61', name: 'Christmas Island', value: '+61' },
    { code: '+61', name: 'Cocos-Keeling Islands', value: '+61' },
    { code: '+57', name: 'Colombia', value: '+57' },
    { code: '+269', name: 'Comoros', value: '+269' },
    { code: '+242', name: 'Congo', value: '+242' },
    { code: '+243', name: 'Congo, Dem. Rep. of (Zaire)', value: '+243' },
    { code: '+682', name: 'Cook Islands', value: '+682' },
    { code: '+506', name: 'Costa Rica', value: '+506' },
    { code: '+385', name: 'Croatia', value: '+385' },
    { code: '+53', name: 'Cuba', value: '+53' },
    { code: '+599', name: 'Curacao', value: '+599' },
    { code: '+537', name: 'Cyprus', value: '+537' },
    { code: '+420', name: 'Czech Republic', value: '+420' },
    { code: '+45', name: 'Denmark', value: '+45' },
    { code: '+246', name: 'Diego Garcia', value: '+246' },
    { code: '+253', name: 'Djibouti', value: '+253' },
    { code: '+1', name: 'Dominica', value: '+1' },
    { code: '+1', name: 'Dominican Republic', value: '+1' },
    { code: '+670', name: 'East Timor', value: '+670' },
    { code: '+56', name: 'Easter Island', value: '+56' },
    { code: '+593', name: 'Ecuador', value: '+593' },
    { code: '+20', name: 'Egypt', value: '+20' },
    { code: '+503', name: 'El Salvador', value: '+503' },
    { code: '+240', name: 'Equatorial Guinea', value: '+240' },
    { code: '+291', name: 'Eritrea', value: '+291' },
    { code: '+372', name: 'Estonia', value: '+372' },
    { code: '+251', name: 'Ethiopia', value: '+251' },
    { code: '+500', name: 'Falkland Islands', value: '+500' },
    { code: '+298', name: 'Faroe Islands', value: '+298' },
    { code: '+679', name: 'Fiji', value: '+679' },
    { code: '+358', name: 'Finland', value: '+358' },
    { code: '+33', name: 'France', value: '+33' },
    { code: '+596', name: 'Martinique', value: '+596' },
    { code: '+594', name: 'French Guiana', value: '+594' },
    { code: '+689', name: 'French Polynesia', value: '+689' },
    { code: '+241', name: 'Gabon', value: '+241' },
    { code: '+220', name: 'Gambia', value: '+220' },
    { code: '+995', name: 'Georgia', value: '+995' },
    { code: '+49', name: 'Germany', value: '+49' },
    { code: '+233', name: 'Ghana', value: '+233' },
    { code: '+350', name: 'Gibraltar', value: '+350' },
    { code: '+30', name: 'Greece', value: '+30' },
    { code: '+299', name: 'Greenland', value: '+299' },
    { code: '+1', name: 'Grenada', value: '+1' },
    { code: '+590', name: 'Guadeloupe', value: '+590' },
    { code: '+1', name: 'Guam', value: '+1' },
    { code: '+502', name: 'Guatemala', value: '+502' },
    { code: '+224', name: 'Guinea', value: '+224' },
    { code: '+245', name: 'Guinea-Bissau', value: '+245' },
    { code: '+595', name: 'Guyana', value: '+595' },
    { code: '+509', name: 'Haiti', value: '+509' },
    { code: '+504', name: 'Honduras', value: '+504' },
    { code: '+852', name: 'Hong Kong SAR China', value: '+852' },
    { code: '+36', name: 'Hungary', value: '+36' },
    { code: '+354', name: 'Iceland', value: '+354' },
    { code: '+91', name: 'India', value: '+91' },
    { code: '+62', name: 'Indonesia', value: '+62' },
    { code: '+98', name: 'Iran', value: '+98' },
    { code: '+964', name: 'Iraq', value: '+964' },
    { code: '+353', name: 'Ireland', value: '+353' },
    { code: '+972', name: 'Israel', value: '+972' },
    { code: '+39', name: 'Italy', value: '+39' },
    { code: '+225', name: 'Ivory Coast', value: '+225' },
    { code: '+1', name: 'Jamaica', value: '+1' },
    { code: '+81', name: 'Japan', value: '+81' },
    { code: '+962', name: 'Jordan', value: '+962' },
    { code: '+77', name: 'Kazakhstan', value: '+7' },
    { code: '+254', name: 'Kenya', value: '+254' },
    { code: '+686', name: 'Kiribati', value: '+686' },
    { code: '+965', name: 'Kuwait', value: '+965' },
    { code: '+996', name: 'Kyrgyzstan', value: '+996' },
    { code: '+856', name: 'Laos', value: '+856' },
    { code: '+371', name: 'Latvia', value: '+371' },
    { code: '+961', name: 'Lebanon', value: '+961' },
    { code: '+266', name: 'Lesotho', value: '+266' },
    { code: '+231', name: 'Liberia', value: '+231' },
    { code: '+218', name: 'Libya', value: '+218' },
    { code: '+423', name: 'Liechtenstein', value: '+423' },
    { code: '+370', name: 'Lithuania', value: '+370' },
    { code: '+352', name: 'Luxembourg', value: '+352' },
    { code: '+853', name: 'Macau SAR China', value: '+853' },
    { code: '+389', name: 'Macedonia', value: '+389' },
    { code: '+261', name: 'Madagascar', value: '+261' },
    { code: '+265', name: 'Malawi', value: '+265' },
    { code: '+60', name: 'Malaysia', value: '+60' },
    { code: '+960', name: 'Maldives', value: '+960' },
    { code: '+223', name: 'Mali', value: '+223' },
    { code: '+356', name: 'Malta', value: '+356' },
    { code: '+692', name: 'Marshall Islands', value: '+692' },
    { code: '+596', name: 'Martinique', value: '+596' },
    { code: '+222', name: 'Mauritania', value: '+222' },
    { code: '+230', name: 'Mauritius', value: '+230' },
    { code: '+262', name: 'Mayotte or Réunion', value: '+262' },
    { code: '+52', name: 'Mexico', value: '+52' },
    { code: '+691', name: 'Micronesia', value: '+691' },
    { code: '+1', name: 'Midway Island', value: '+1' },
    { code: '+373', name: 'Moldova', value: '+373' },
    { code: '+377', name: 'Monaco', value: '+377' },
    { code: '+976', name: 'Mongolia', value: '+976' },
    { code: '+382', name: 'Montenegro', value: '+382' },
    { code: '+1', name: 'Montserrat', value: '+1' },
    { code: '+212', name: 'Morocco', value: '+212' },
    { code: '+95', name: 'Myanmar', value: '+95' },
    { code: '+264', name: 'Namibia', value: '+264' },
    { code: '+674', name: 'Nauru', value: '+674' },
    { code: '+977', name: 'Nepal', value: '+977' },
    { code: '+31', name: 'Netherlands', value: '+31' },
    { code: '+599', name: 'Netherlands Antilles', value: '+599' },
    { code: '+1', name: 'Nevis', value: '+1' },
    { code: '+687', name: 'New Caledonia', value: '+687' },
    { code: '+64', name: 'New Zealand', value: '+64' },
    { code: '+505', name: 'Nicaragua', value: '+505' },
    { code: '+227', name: 'Niger', value: '+227' },
    { code: '+234', name: 'Nigeria', value: '+234' },
    { code: '+683', name: 'Niue', value: '+683' },
    { code: '+672', name: 'Norfolk Island', value: '+672' },
    { code: '+850', name: 'North Korea', value: '+850' },
    { code: '+1', name: 'Northern Mariana Islands', value: '+1' },
    { code: '+47', name: 'Norway', value: '+47' },
    { code: '+968', name: 'Oman', value: '+968' },
    { code: '+92', name: 'Pakistan', value: '+92' },
    { code: '+680', name: 'Palau', value: '+680' },
    { code: '+970', name: 'Palestinian Territory', value: '+970' },
    { code: '+507', name: 'Panama', value: '+507' },
    { code: '+675', name: 'Papua New Guinea', value: '+675' },
    { code: '+595', name: 'Paraguay', value: '+595' },
    { code: '+51', name: 'Peru', value: '+51' },
    { code: '+63', name: 'Philippines', value: '+63' },
    { code: '+48', name: 'Poland', value: '+48' },
    { code: '+351', name: 'Portugal', value: '+351' },
    { code: '+1', name: 'Puerto Rico', value: '+1' },
    { code: '+974', name: 'Qatar', value: '+974' },
    { code: '+40', name: 'Romania', value: '+40' },
    { code: '+7', name: 'Russia', value: '+7' },
    { code: '+250', name: 'Rwanda', value: '+250' },
    { code: '508', name: 'Saint Pierre and Miquelon', value: '508' },
    { code: '+685', name: 'Samoa', value: '+685' },
    { code: '+378', name: 'San Marino', value: '+378' },
    { code: '+966', name: 'Saudi Arabia', value: '+966' },
    { code: '+221', name: 'Senegal', value: '+221' },
    { code: '+381', name: 'Serbia', value: '+381' },
    { code: '+248', name: 'Seychelles', value: '+248' },
    { code: '+232', name: 'Sierra Leone', value: '+232' },
    { code: '+65', name: 'Singapore', value: '+65' },
    { code: '+421', name: 'Slovakia', value: '+421' },
    { code: '+386', name: 'Slovenia', value: '+386' },
    { code: '+677', name: 'Solomon Islands', value: '+677' },
    { code: '+27', name: 'South Africa', value: '+27' },
    { code: '+500', name: 'South Georgia and the South Sandwich Islands', value: '+500' },
    { code: '+82', name: 'South Korea', value: '+82' },
    { code: '+34', name: 'Spain', value: '+34' },
    { code: '+94', name: 'Sri Lanka', value: '+94' },
    { code: '+249', name: 'Sudan', value: '+249' },
    { code: '+597', name: 'Suriname', value: '+597' },
    { code: '+268', name: 'Swaziland', value: '+268' },
    { code: '+46', name: 'Sweden', value: '+46' },
    { code: '+41', name: 'Switzerland', value: '+41' },
    { code: '+963', name: 'Syria', value: '+963' },
    { code: '+886', name: 'Taiwan', value: '+886' },
    { code: '+992', name: 'Tajikistan', value: '+992' },
    { code: '+255', name: 'Tanzania', value: '+255' },
    { code: '+66', name: 'Thailand', value: '+66' },
    { code: '+670', name: 'Timor Leste', value: '+670' },
    { code: '+228', name: 'Togo', value: '+228' },
    { code: '+690', name: 'Tokelau', value: '+690' },
    { code: '+676', name: 'Tonga', value: '+676' },
    { code: '+1', name: 'Trinidad and Tobago', value: '+1' },
    { code: '+216', name: 'Tunisia', value: '+216' },
    { code: '+90', name: 'Turkey', value: '+90' },
    { code: '+993', name: 'Turkmenistan', value: '+993' },
    { code: '+1', name: 'Turks and Caicos Islands', value: '+1' },
    { code: '+688', name: 'Tuvalu', value: '+688' },
    { code: '+1', name: 'U.S. Virgin Islands', value: '+1' },
    { code: '+256', name: 'Uganda', value: '+256' },
    { code: '+380', name: 'Ukraine', value: '+380' },
    { code: '+971', name: 'United Arab Emirates', value: '+971' },
    { code: '+44', name: 'United Kingdom', value: '+44' },
    { code: '+1', name: 'United States', value: '+1' },
    { code: '+598', name: 'Uruguay', value: '+598' },
    { code: '+998', name: 'Uzbekistan', value: '+998' },
    { code: '+678', name: 'Vanuatu', value: '+678' },
    { code: '+58', name: 'Venezuela', value: '+58' },
    { code: '+84', name: 'Vietnam', value: '+84' },
    { code: '+1', name: 'Wake Island', value: '+1' },
    { code: '+681', name: 'Wallis and Futuna', value: '+681' },
    { code: '+967', name: 'Yemen', value: '+967' },
    { code: '+260', name: 'Zambia', value: '+260' },
    { code: '+255', name: 'Zanzibar', value: '+255' },
    { code: '+263', name: 'Zimbabwe', value: '+263' },
];
function getCountryByCode(code) {
    const found = Countries.find((country) => country.code === code);
    if (found)
        return found;
    if (isFrenchGuiana(code)) {
        return { code: '+594', name: 'French Guiana', value: '+594' };
    }
    else if (isGuadeloupe(code)) {
        return { code: '+590', name: 'Guadeloupe', value: '+590' };
    }
    else if (isMartinique(code)) {
        return { code: '+596', name: 'Martinique', value: '+596' };
    }
    else if (isMayotte(code)) {
        return { code: '+262', name: 'Mayotte or Réunion', value: '+262' };
    }
    return null;
}
function isFrenchGuiana(code) {
    return '+594' === code.substring(0, 4);
}
function isGuadeloupe(code) {
    return '+590' === code.substring(0, 4);
}
function isMartinique(code) {
    return '+596' === code.substring(0, 4);
}
function isMayotte(code) {
    return '+262' === code.substring(0, 4);
}
function getPlusOneCountry(code) {
    let info = null;
    switch (code.substring(0, 5)) {
        case '+1684':
            info = { code: '+1', name: 'American Samoa', value: '+1' };
            break;
        case '+1264':
            info = { code: '+1', name: 'Anguilla', value: '+1' };
            break;
        case '+1268':
            info = { code: '+1', name: 'Antigua and Barbuda', value: '+1' };
            break;
        case '+1242':
            info = { code: '+1', name: 'Bahamas', value: '+1' };
            break;
        case '+1246':
            info = { code: '+1', name: 'Barbados', value: '+1' };
            break;
        case '+1441':
            info = { code: '+1', name: 'Bermuda', value: '+1' };
            break;
        case '+1284':
            info = { code: '+1', name: 'British Virgin Islands', value: '+1' };
            break;
        case '+1':
            info = { code: '+1', name: '', value: '+1' };
            break;
    }
    return info;
}
function isCanada(code) {
    const canadianAreaCodes = [
        '403',
        '587',
        '780',
        '825',
        '604',
        '250',
        '778',
        '236',
        '204',
        '431',
        '506',
        '709',
        '867',
        '782',
        '902',
        '867',
        '548',
        '705',
        '365',
        '613',
        '807',
        '226',
        '289',
        '437',
        '519',
        '647',
        '905',
        '249',
        '343',
        '416',
        '902',
        '782',
        '450',
        '418',
        '579',
        '873',
        '367',
        '514',
        '581',
        '819',
        '438',
        '639',
        '306',
        '867',
    ];
    const areaCode = code.substring(0, 5);
    return canadianAreaCodes.findIndex((x) => '+1' + x === areaCode) > -1;
}
function isAmericanSamoa(code) {
    return code.substring(0, 5) === '+1684';
}
function isDominicanRepublic(code) {
    return '+1809' === code.substring(0, 5) || '+1829' === code.substring(0, 5) || '+1849' === code.substring(0, 5);
}
function isPuertoRico(code) {
    return code.substring(0, 5) === '+' || code.substring(0, 5) === '+';
}
// need to finish
function getMatchingCountry(code, substrings) {
    const toMatch = code.substring(0, substrings);
    return Countries.filter((c) => c.code === toMatch).length;
}
// const e164Regex = new RegExp(/\+[1-9]\d{6,14}/g);
// export function simpleE164Validator(code: string) {
//   return (code !== null && code.length < 16 && code.length > 6 && e164Regex.test(code)) || code === '' || code === null;
// }

/**
 * Capitalize the first letter of a string.
 */
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
/**
 * Convert a phone-number-like string to E164 format.
 * @see https://46elks.com/kb/e164
 */
const convertToE164 = (input) => {
    // "(212) 555-1212" => +12125551212
    // "+46766861004" => "+46766861004"
    // "212-555-1212" => +12125551212
    // "212.555.1212" => +12125551212
    // "212 555 1212" => +12125551212
    let temp = (input || '').trim();
    // If we are already prefixed, assume the user did it deliberately and attempt to use what they entered. We also short-circuit blanks.
    if (!temp || temp.startsWith('+')) {
        return temp;
    }
    // Remove any spaces, parenthesis or other punctuation.
    temp = temp.replace(/[^0-9]/g, '');
    // If the number begins with a zero, remove the leading zero. Do not combine this with the previous step because it needs to be removed
    // whether it's the actual first character e.g. `0(5)` or just the first digit e.g. `(05`.
    temp = temp.replace(/^0/g, '');
    // Prepend the country code and +. We're assuming US in this case given the target demographic. Users in other countries would/should be
    // already entering a prefix so they'd shortcut out of this routine via the + prefix check.
    return `+1${temp}`;
};
// Generate a random string of a given length. This is NOT cryptographically strong. It is meant for light-duty
// uses such as assigning IDs to DOM elements.
const randomString = (length) => Math.random()
    .toString(36)
    .substring(2, 2 + length + 1);

/**
 * Create an array containing a sequence of integers, e.g. [START, START+1, START+2, ...] This is frequently useful
 * in rendering operations when there is no source array to .map() across.
 */
const integerSequence = (start, count) => Array(count)
    .fill(1)
    .map((_, index) => index + start);
/**
 * Format a profile's full name
 */
const formatFullName = (source) => `${capitalize(source?.first_name || '')} ${capitalize(source?.last_name || '')}`.trim();
/**
 * Format a profile's initials
 */
const formatInitials = (profile) => profile ? `${capitalize(profile.first_name).charAt(0)} ${capitalize(profile.last_name).charAt(0)}` : '--';
/**
 * Generate suggested initials for a full name, e.g. "John Doe" will yield "JD".
 */
const fullNameToInitials = (name) => name
    .split(' ')
    .map((word) => word[0])
    .join('');

/* tslint:disable:no-bitwise */
const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
// Regular expression to check formal correctness of base64 encoded strings
const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
/**
 * Simplified, Node/Browser-safe alternative to atob() for base64 decoding.
 * Modified from https://github.com/MaxArt2501/base64-js/blob/master/base64.js
 */
const AtoB = (str) => {
    // atob can work with strings with whitespaces, even inside the encoded part,
    // but only \t, \n, \f, \r and ' ', which can be stripped.
    str = String(str).replace(/[\t\n\f\r ]+/g, '');
    if (!b64re.test(str))
        throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
    // Adding the padding if missing, for semplicity
    str += '=='.slice(2 - (str.length & 3));
    let bitmap;
    let result = '';
    let r1;
    let r2;
    let i = 0;
    for (; i < str.length;) {
        bitmap =
            (b64.indexOf(str.charAt(i++)) << 18) |
                (b64.indexOf(str.charAt(i++)) << 12) |
                ((r1 = b64.indexOf(str.charAt(i++))) << 6) |
                (r2 = b64.indexOf(str.charAt(i++)));
        result +=
            r1 === 64
                ? String.fromCharCode((bitmap >> 16) & 255)
                : r2 === 64
                    ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255)
                    : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255);
    }
    return result;
};
/**
 * Decode the body of a JWT. This helper may allow front-end applications to avoid a dependency on `jsonwebtoken` in
 * many cases. Note that this should only be used for true JWTs. Opaque tokens will cause this to throw.
 */
const decodeJWTBody = (token) => JSON.parse(AtoB((token || '').split('.')[1] || ''));
/**
 * Decode the body of an Verdocs access token. Note that raw tokens contain namespaced fields, e.g.
 * `https://verdocs.com/profile_id`. To make these tokens easier to use in front-end code, this name-spacing
 * will be removed. Note that user and signing sessions have different access token formats. The calling
 * application should distinguish between the two based on the context of the authenticated session, or by
 * the presence of the `document_id` field, which will only be present for signing sessions.
 */
const decodeAccessTokenBody = (token) => {
    let decoded;
    try {
        decoded = decodeJWTBody(token);
        if (decoded === null) {
            return null;
        }
    }
    catch (e) {
        return null;
    }
    return decoded;
};

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

// This file provides a polyfill for managing globals in both NodeJS and browser environments. This is
// an anti-pattern we'd hoped to avoid, but we have several projects dependending on one common library
// (this js-sdk) and we want that library to provide a common endpoint to all callers (so authentication
// tokens only need to be tracked in one place). The trouble is, one of those libraries is based on
// StencilJS and is compiling its modules into Web Components. Because of how module resolution works,
// when those Components load js-sdk they get a separate instance. Without messy options like having to
// pass raw data from the caller to each Component, or pass around references to a common Endpoint, they
// have no way to access authenticated sessions unless we make the Endpoint a true global.
//
// @credit https://github.com/medikoo/es5-ext/blob/master/global.js
// @credit https://mathiasbynens.be/notes/globalthis
var naiveFallback = function () {
    if (typeof self === 'object' && self)
        return self;
    if (typeof window === 'object' && window)
        return window;
    throw new Error('Unable to resolve global `this`');
};
var globalThis_1 = (function () {
    if (this)
        return this;
    // Unexpected strict mode (may happen if e.g. bundled into ESM module)
    // Fallback to standard globalThis if available
    if (typeof globalThis === 'object' && globalThis)
        return globalThis;
    // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
    // In all ES5+ engines global object inherits from Object.prototype
    // (if you approached one that doesn't please report)
    try {
        Object.defineProperty(Object.prototype, '__global__', {
            get: function () {
                return this;
            },
            configurable: true,
        });
    }
    catch (error) {
        // Unfortunate case of updates to Object.prototype being restricted
        // via preventExtensions, seal or freeze
        return naiveFallback();
    }
    try {
        // Safari case (window.__global__ works, but __global__ does not)
        if (!__global__)
            return naiveFallback();
        return __global__;
    }
    finally {
        delete Object.prototype.__global__;
    }
})();

var globalThis$1 = /*@__PURE__*/getDefaultExportFromCjs(globalThis_1);

/**
 * Authenticate to Verdocs.
 *
 * ```typescript
 * import {authenticate, VerdocsEndpoint} from '@verdocs/js-sdk';
 *
 * // Client-side call, suitable for Web and mobile apps:
 * const {access_token} = await Auth.authenticate({ username: 'test@test.com', password: 'PASSWORD', grant_type:'password' });
 * VerdocsEndpoint.getDefault().setAuthToken(access_token);
 *
 * // Server-side call, suitable for server apps. NEVER EXPOSE client_secret IN FRONT-END CODE:
 * const {access_token} = await Auth.authenticate({ client_id: '...', client_secret: '...', grant_type:'client_credentials' });
 * VerdocsEndpoint.getDefault().setAuthToken(access_token);
 * ```
 *
 * @group Authentication
 * @api POST /v2/oauth2/token Authenticate
 * @apiBody string(enum: 'client_credentials'|'refresh_token'|'password') grant_type The type of grant to request. API callers should nearly always use 'client_credentials'.
 * @apiBody string(format: 'uuid') client_id? If grant_type is client_credentials or refresh_token, the client ID of the API key to use.
 * @apiBody string(format: 'uuid') client_secret? If grant_type is client_credentials, the secret key of the API key to use.
 * @apiBody string username? If grant_type is password, the username to authenticate with.
 * @apiBody string password? If grant_type is password, the password to authenticate with.
 * @apiBody string password? If grant_type is password, the password to authenticate with.
 * @apiBody string scope? Optional scope to limit the auth token to. Do not specify this unless you are instructed to by a Verdocs Support rep.
 * @apiSuccess IAuthenticateResponse . The detailed metadata for the envelope requested
 */
const authenticate = (endpoint, params) => endpoint.api //
    .post('/v2/oauth2/token', params)
    .then((r) => r.data);
/**
 * If called before the session expires, this will refresh the caller's session and tokens.
 *
 * ```typescript
 * import {Auth, VerdocsEndpoint} from '@verdocs/js-sdk';
 *
 * const {accessToken} = await Auth.refreshTokens();
 * VerdocsEndpoint.setAuthToken(accessToken);
 * ```
 */
const refreshToken = (endpoint, refreshToken) => authenticate(endpoint, { grant_type: 'refresh_token', refresh_token: refreshToken });
/**
 * Update the caller's password when the old password is known (typically for logged-in users).
 *
 * ```typescript
 * import {changePassword} from '@verdocs/js-sdk';
 *
 * const {status, message} = await changePassword({ old_password, new_password });
 * if (status !== 'OK') {
 *   window.alert(`Password reset error: ${message}`);
 * }
 * ```
 *
 * @group Authentication
 * @api POST /v2/users/change-password Change the caller's password
 * @apiBody string old_password Current password for the caller
 * @apiBody string new_password New password to set for the caller. Must meet strength requirements.
 * @apiSuccess string . Success
 */
const changePassword = (endpoint, params) => endpoint.api //
    .post('/v2/users/change-password', params)
    .then((r) => r.data);
/**
 * Request a password reset, when the old password is not known (typically in login forms).
 *
 * ```typescript
 * import {resetPassword} from '@verdocs/js-sdk';
 *
 * const {success} = await resetPassword({ email });
 * if (status !== 'OK') {
 *   window.alert(`Please check your email for instructions on how to reset your password.`);
 * }
 *
 * // Collect code and new password from the user, then call:
 *
 * const {success} = await resetPassword({ email, code, new_password });
 * if (status !== 'OK') {
 *   window.alert(`Please check your verification code and try again.`);
 * }
 * ```
 *
 * @group Authentication
 * @api POST /v2/users/reset-password Reset a password for a user
 * @apiBody string email Email address for the user account
 * @apiBody string code? To initiate a reset request, omit this field. To complete it, provide the emailed code received by the user.
 * @apiBody string new_password? To initiate a reset request, omit this field. To complete it, provide the new password the user wishes to use.
 * @apiSuccess string . Success
 */
const resetPassword = (endpoint, params) => endpoint.api //
    .post('/v2/users/reset-password', params)
    .then((r) => r.data);
/**
 * Resend the email verification request if the email or token are unknown. Instead, an accessToken
 * may be supplied through which the user will be identified. This is intended to be used in post-signup
 * cases where the user is "partially" authenticated (has a session, but is not yet verified).
 *
 * ```typescript
 * import {resendVerification} from '@verdocs/js-sdk';
 *
 * const result = await resendVerification();
 * ```
 *
 * @group Authentication
 * @api POST /v2/users/verify Resend an email verification request for a "partially" authenticated user (authenticated, but not yet verified)
 * @apiSuccess string . Success
 */
const resendVerification = (endpoint, accessToken) => endpoint.api //
    .post('/v2/users/resend-verification', {}, accessToken ? { headers: { Authorization: `Bearer ${accessToken}` } } : {})
    .then((r) => r.data);
/**
 * Resend the email verification request if the user is unauthenticated, but the email and token are known.
 * Used if the token is valid but has expired.
 *
 * ```typescript
 * import {resendVerification} from '@verdocs/js-sdk';
 *
 * const result = await resendVerification();
 * ```
 *
 * @group Authentication
 * @api POST /v2/users/verify Resend the email verification request if both the email and token are known. Used if the token is valid but has expired.
 * @apiSuccess IAuthenticateResponse . Updated authentication details
 */
const verifyEmail = (endpoint, params) => endpoint.api //
    .post('/v2/users/verify', params)
    .then((r) => r.data);
/**
 * Get the caller's current user record.
 *
 * @group Authentication
 * @api GET /v2/users/me Get the caller's user record.
 * @apiSuccess IUser . User record
 */
const getMyUser = (endpoint) => endpoint.api //
    .get('/v2/users/me')
    .then((r) => r.data);

const getNotifications = async (endpoint) => endpoint.api //
    .get('/v2/notifications')
    .then((r) => r.data);

/**
 * Get the caller's available profiles. The current profile will be marked with `current: true`.
 *
 * ```typescript
 * import {getProfiles} from '@verdocs/js-sdk';
 *
 * const profiles = await getProfiles();
 * ```
 *
 * @group Profiles
 * @api GET /v2/profiles Get the caller's profiles
 * @apiDescription A user may have multiple profiles, one for each organization of which they are a member. Only one profile may be "current" at a time.
 * @apiSuccess array(items: IProfile) . The caller's profiles
 */
const getProfiles = (endpoint) => endpoint.api //
    .get('/v2/profiles')
    .then((r) => r.data);
/**
 * Get the caller's current profile. This is just a convenience accessor that calls `getProfiles()`
 * and returns the first `current: true` entry.
 *
 * ```typescript
 * import {getCurrentProfile} from '@verdocs/js-sdk';
 *
 * const profiles = await getCurrentProfile(VerdocsEndpoint.getDefault());
 * ```
 */
const getCurrentProfile = (endpoint) => endpoint.api //
    .get('/v2/profiles')
    .then((r) => (r.data || []).find((profile) => profile.current));
/**
 * Switch the caller's "current" profile. The current profile is used for permissions checking
 * and profile_id field settings for most operations in Verdocs. It is important to select the
 * appropropriate profile before calling other API functions.
 *
 * ```typescript
 * import {switchProfile} from '@verdocs/js-sdk';
 *
 * const newProfile = await switchProfile(VerdocsEndpoint.getDefault(), 'PROFILEID');
 * ```
 *
 * @group Profiles
 * @api POST /v2/profiles/:profile_id/switch Change the "current" profile for the caller
 * @apiSuccess IAuthenticateResponse . New authentication credentials
 */
const switchProfile = (endpoint, profileId) => endpoint.api //
    .post(`/v2/profiles/${profileId}/switch`)
    .then((r) => r.data);
/**
 * Update a profile. For future expansion, the profile ID to update is required, but currently
 * this must also be the "current" profile for the caller.
 *
 * ```typescript
 * import {updateProfile} from '@verdocs/js-sdk/Users';
 *
 * const newProfile = await updateProfile(VerdocsEndpoint.getDefault(), 'PROFILEID');
 * ```
 *
 * @group Profiles
 * @api PATCH /v2/profiles/:profile_id Update a profile
 * @apiBody string first_name? First name
 * @apiBody string last_name? Last name
 * @apiBody string phone? Phone number
 * @apiBody array(items:TPermission) permissions? New permissions to directly apply to the profile
 * @apiBody array(items:TRole) roles? New roles to assign to the profile
 * @apiSuccess IProfile . The updated profile
 */
const updateProfile = (endpoint, profileId, params) => endpoint.api //
    .patch(`/v2/profiles/${profileId}`, params)
    .then((r) => r.data);
/**
 * Delete a profile. If the requested profile is the caller's curent profile, the next
 * available profile will be selected.
 *
 * ```typescript
 * import {deleteProfile} from '@verdocs/js-sdk';
 *
 * await deleteProfile(VerdocsEndpoint.getDefault(), 'PROFILEID');
 * ```
 *
 * @group Profiles
 * @api DELETE /v2/profiles/:profile_id Delete a profile
 * @apiSuccess IAuthenticateResponse . New session tokens for the next available profile for the caller, or null if none.
 */
const deleteProfile = (endpoint, profileId) => endpoint.api //
    .delete(`/v2/profiles/${profileId}`)
    .then((r) => r.data);
/**
 * Create a new profile. Note that there are two registration paths for creation:
 *   - Get invited to an organization, by an admin or owner of that org.
 *   - Created a new organization. The caller will become the first owner of the new org.
 *
 * This endpoint is for the second path, so an organization name is required. It is NOT
 * required to be unique because it is very common for businesses to have the same names,
 * without conflicting (e.g. "Delta" could be Delta Faucet or Delta Airlines).
 *
 * The new profile will automatically be set as the user's "current" profile, and new
 * session tokens will be returned to the caller. However, the caller's email may not yet
 * be verified. In that case, the caller will not yet be able to call other endpoints in
 * the Verdocs API. The caller will need to check their email for a verification code,
 * which should be submitted via the `verifyEmail` endpoint.
 *
 * ```typescript
 * import {createProfile} from '@verdocs/js-sdk';
 *
 * const newSession = await createProfile(VerdocsEndpoint.getDefault(), {
 *   orgName: 'NEW ORG', email: 'a@b.com', password: '12345678', firstName: 'FIRST', lastName: 'LAST'
 * });
 * ```
 */
const createProfile = (endpoint, params) => endpoint.api //
    .post('/v2/profiles', params)
    .then((r) => r.data);
/**
 * Update the caller's profile photo. This can only be called for the user's "current" profile.
 *
 * ```typescript
 * import {uploadProfilePhoto} from '@verdocs/js-sdk';
 *
 * await uploadProfilePhoto((VerdocsEndpoint.getDefault(), profileId, file);
 * ```
 *
 * @group Profiles
 * @api PATCH /v2/templates/:template_id Change a profile's photo
 * @apiBody string(format:binary) file File to upload
 * @apiSuccess IProfile . The updated profile
 */
const updateProfilePhoto = (endpoint, profileId, file, onUploadProgress) => {
    const formData = new FormData();
    formData.append('picture', file, file.name);
    return endpoint.api //
        .patch(`/v2/profiles/${profileId}`, formData, {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    })
        .then((r) => r.data);
};

// @credit https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/
// Also see globalThis for comments about why we're doing this in the first place.
const ENDPOINT_KEY = Symbol.for('verdocs-default-endpoint');
const BETA_ORIGINS = ['https://beta.verdocs.com', 'https://stage.verdocs.com', 'http://localhost:6006', 'http://localhost:5173'];
const requestLogger = (r) => {
    // tslint:disable-next-line
    console.debug(`[JS-SDK] ${r.method.toUpperCase()} ${r.baseURL}${r.url}`, r.data ? JSON.stringify(r.data) : '');
    return r;
};
/**
 * VerdocsEndpoint is a class wrapper for a specific connection and authorization context for calling the Verdocs APIs.
 * Endpoints can be used for isolated session tasks.
 *
 * For instance, ephemeral signing sessions may be created independently of a caller's status as an authenticated user.
 * In that case, an Endpoint can be created and authenticated, used for calls related to signing operations, then
 * discarded once signing is complete.
 *
 * Note that endpoint configuration functions return the instance, so they can be chained, e.g.
 *
 * ```typescript
 * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
 *
 * const endpoint = new VerdocsEndpoint();
 * endpoint
 *     .setSessionType('signing')
 *     .logRequests(true)
 *     .setClientID('1234)
 *     .setTimeout(30000);
 * ```
 */
class VerdocsEndpoint {
    environment = 'verdocs';
    sessionType = 'user';
    persist = true;
    baseURL = BETA_ORIGINS.includes(window.location.origin) ? 'https://stage-api.verdocs.com' : 'https://api.verdocs.com';
    clientID = 'not-set';
    timeout = 60000;
    token = null;
    nextListenerId = 0;
    sessionListeners = new Map();
    requestLoggerId = null;
    endpointId = randomString(8);
    /**
     * The current user's userId (NOT profileId), or null if not authenticated.
     */
    sub = null;
    /**
     * The current user session, or null if not authenticated. May be either a User or Signing session. If set, the
     * presence of the `document_id` field can be used to differentiate the types. Only signing sessions are associated
     * with Envelopes.
     */
    session = null;
    /**
     * The current user's profile, if known. Note that while sessions are loaded and handled synchronously,
     * profiles are loaded asynchronously and may not be available immediately after a session is loaded.
     * To ensure both are available, developers should subscribe to the `onSessionChanged` event, which
     * will not be fired until the profile is loaded and verified.
     */
    profile = null;
    api;
    /**
     * Create a new VerdocsEndpoint to call Verdocs platform services.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     * const endpoint = new VerdocsEndpoint();
     * ```
     */
    constructor(options) {
        this.baseURL = options?.baseURL ?? this.baseURL;
        this.timeout = options?.timeout ?? this.timeout;
        this.environment = options?.environment ?? this.environment;
        this.sessionType = options?.sessionType ?? this.sessionType;
        this.clientID = options?.clientID ?? this.clientID;
        this.persist = options?.persist ?? this.persist;
        this.api = axios.create({ baseURL: this.baseURL, timeout: this.timeout });
    }
    setDefault() {
        globalThis$1[ENDPOINT_KEY] = this;
        window?.console?.debug('[JS_SDK] Set default endpoint', this.endpointId);
    }
    static getDefault() {
        if (!globalThis$1[ENDPOINT_KEY]) {
            globalThis$1[ENDPOINT_KEY] = new VerdocsEndpoint();
        }
        return globalThis$1[ENDPOINT_KEY];
    }
    /**
     * Get the current environment.
     */
    getEnvironment() {
        return this.environment;
    }
    /**
     * Get the current session type.
     */
    getSessionType() {
        return this.sessionType;
    }
    /**
     * Get the current base URL. This should rarely be anything other than 'https://api.verdocs.com'.
     */
    getBaseURL() {
        return this.baseURL;
    }
    /**
     * Get the current client ID, if set.
     */
    getClientID() {
        return this.clientID;
    }
    /**
     * Get the current timeout.
     */
    getTimeout() {
        return this.timeout;
    }
    /**
     * Get the current session, if any.
     */
    getSession() {
        return this.session;
    }
    /**
     * Set the operating environment. This should rarely be anything other than 'verdocs'.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setEnvironment('verdocs-stage');
     * ```
     */
    setEnvironment(environment) {
        this.environment = environment;
        return this;
    }
    /**
     * Set the session type. In general this should be done immediately when the endpoint is created. Changing the
     * session type may be done at any time, but may have unintended consequences if the endpoint is shared between
     * multiple widgets.
     *
     * Changing the session type will clear/reload the action session. This may trigger notifications to session state
     * observers. Apps that use observers to trigger UI updates such as logging the user out should be prepared to
     * handle this event.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setEnvironment('verdocs-stage');
     * ```
     */
    setSessionType(sessionType) {
        this.sessionType = sessionType;
        return this;
    }
    /**
     * Set the base URL for API calls. Should be called only upon direction from Verdocs Customer Solutions Engineering.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setBaseURL('https://api.verdocs.com');
     * ```
     */
    setBaseURL(url) {
        this.baseURL = url;
        this.api.defaults.baseURL = url;
        return this;
    }
    /**
     * Set the Client ID for Verdocs API calls.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setClientID('1234);
     * ```
     */
    setClientID(clientID) {
        this.clientID = clientID;
        this.api.defaults.headers.common['X-Client-ID'] = clientID;
        return this;
    }
    /**
     * Set the timeout for API calls in milliseconds. 5000-20000ms is recommended for most purposes. 15000ms is the default.
     * Note that some calls may involve rendering operations that require some time to complete, so very short timeouts
     * are not recommended.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setTimeout(3000);
     * ```
     */
    setTimeout(timeout) {
        this.timeout = timeout;
        this.api.defaults.timeout = timeout;
        return this;
    }
    /**
     * Enable or disable request logging. This may expose sensitive data in the console log, so it should only be used for debugging.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.logRequests(true);
     * ```
     */
    logRequests(enable) {
        if (enable && this.requestLoggerId === null) {
            this.requestLoggerId = this.api.interceptors.request.use(requestLogger);
        }
        else if (!enable && this.requestLoggerId !== null) {
            this.api.interceptors.request.eject(this.requestLoggerId);
        }
        return this;
    }
    /**
     * Set the authorization token that will be used for Verdocs API calls. This will also set the session metadata
     * and notify any listeners of the new data.
     *
     * If this Endpoint will be used for non-default purposes (e.g. signing, or in an alternate environment) those
     * settings should be made before calling this. Sessions are persisted to localStorage, and the environment and
     * type become part of the storage key.
     *
     * ```typescript
     * import {VerdocsEndpoint} from '@verdocs/js-sdk/HTTP';
     *
     * const endpoint = new VerdocsEndpoint();
     * endpoint.setToken(accessToken);
     * ```
     */
    setToken(token, sessionType = 'user') {
        if (!token) {
            window.console.log('[JS_SDK] Clearing token');
            return this.clearSession();
        }
        const session = decodeAccessTokenBody(token);
        if (session === null || (session.exp && session.exp * 1000 < new Date().getTime())) {
            window.console.warn('[JS_SDK] Ignoring attempt to use expired session token');
            return this.clearSession();
        }
        window.console.log('[JS_SDK] Setting token', sessionType);
        this.token = token;
        this.session = session;
        this.sub = session.sub;
        this.sessionType = sessionType;
        if (this.sessionType === 'user') {
            this.api.defaults.headers.common.Authorization = `Bearer ${token}`;
            if (this.persist) {
                localStorage.setItem(this.sessionStorageKey(), token);
            }
        }
        else {
            // Required for legacy calls to rForm
            this.api.defaults.headers.common.signer = `Bearer ${token}`;
            // TODO: Once we confirm rForm doesn't react badly to this, we can switch over
            // this.api.defaults.headers.common.Authorization = `Bearer ${token}`;
        }
        if (this.sessionType === 'user') {
            window?.console?.debug('[JS_SDK] Loading current profile...', this.endpointId, this.sub, session.sub);
            getCurrentProfile(this)
                .then((r) => {
                window?.console?.debug('[JS_SDK] Loaded profile', this.endpointId, r);
                this.profile = r || null;
                this.notifySessionListeners();
            })
                .catch((e) => {
                this.profile = null;
                this.sub = null;
                window?.console?.warn('Unable to load profile', e);
                // We can't clear the token verdocs-auth may be using temporarily during registration
                if (this.persist) {
                    this.clearSession();
                }
            });
        }
        else {
            this.notifySessionListeners();
        }
        return this;
    }
    /**
     * Retrieves the current session token, if any. Tokens should rarely be used for direct actions, but this is
     * required by the `<VerdocsView>` and other components to authorize requests to raw PDF files.
     */
    getToken() {
        return this.token;
    }
    sessionStorageKey() {
        return `verdocs-session-${this.getSessionType()}-${this.getEnvironment()}`;
    }
    /**
     * Clear the active session.
     */
    clearSession() {
        window?.console?.debug('[JS_SDK] Clearing session', this.endpointId);
        if (this.persist) {
            localStorage.removeItem(this.sessionStorageKey());
        }
        delete this.api.defaults.headers.common.Authorization;
        delete this.api.defaults.headers.common.signer;
        this.session = null;
        this.profile = null;
        this.token = null;
        this.sub = null;
        this.notifySessionListeners();
        return this;
    }
    /**
     * Clear the active signing session.
     */
    clearSignerSession() {
        window?.console?.debug('[JS_SDK] Clearing signer session', this.endpointId);
        if (this.persist) {
            localStorage.removeItem(this.sessionStorageKey());
        }
        delete this.api.defaults.headers.common.Authorization;
        this.session = null;
        this.profile = null;
        this.token = null;
        this.sub = null;
        this.notifySessionListeners();
        return this;
    }
    notifySessionListeners() {
        this.sessionListeners.forEach((listener) => {
            try {
                listener(this, this.session, this.profile);
            }
            catch (e) {
                // NOOP
            }
        });
    }
    /**
     * Subscribe to session state change events.
     */
    onSessionChanged(listener) {
        // There's no value in randomizing this, a simple counter is fine
        this.nextListenerId++;
        const listenerSymbol = Symbol.for('' + this.nextListenerId);
        this.sessionListeners.set(listenerSymbol, listener);
        // Perform an immediate notification if this listener subscribed after the session was already loaded.
        if (this.profile) {
            listener(this, this.session, this.profile);
        }
        return () => {
            this.sessionListeners.delete(listenerSymbol);
        };
    }
    /**
     * Load a persisted session from localStorage. Typically called once after the endpoint is configured
     * when the app or component starts. Ignored if the endpoint is configured to not persist sessions.
     */
    loadSession() {
        if (!this.persist) {
            return this;
        }
        const token = localStorage.getItem(this.sessionStorageKey());
        if (!token) {
            window?.console?.debug('[JS_SDK] No cached session found', this.endpointId);
            return this.clearSession();
        }
        // We sometimes get multiple loadSession calls from stacked components all needing to just ensure
        // we've done our best to load it. We only set it the first time to avoid dupe profile reloads
        // and upstream component notifications.
        return this.token ? this : this.setToken(token);
    }
}

/**
 * Create an envelope
 *
 * ```typescript
 * import {Envelopes, ICreateEnvelopeRole, ICreateEnvelopeRequest} from '@verdocs/js-sdk/Envelopes';
 *
 * const role1: ICreateEnvelopeRole = {
 *   type: 'signer',
 *   name: 'Seller',
 *   first_name: 'Paige',
 *   last_name: 'Turner',
 *   email: 'paige.turner@nomail.com',
 *   phone: '',
 *   sequence: 1,
 *   delegator: false,
 *   message: '',
 * };
 *
 * const role2: ICreateEnvelopeRole = {
 *   type: 'signer',
 *   name: 'Buyer',
 *   first_name: 'Power',
 *   last_name: 'Power',
 *   email: 'will.power@nomail.com',
 *   phone: '',
 *   sequence: 2,
 *   delegator: false,
 *   message: '',
 * };
 *
 * const request: ICreateEnvelopeRequest = {template_id: 'd2338742-f3a1-465b-8592-806587413cc1', name: 'Bill of Sale', roles: [role1, role2]};
 * const {id, recipients} = await Envelopes.createEnvelope(VerdocsEndpoint.getDefault(), request);
 * ```
 *
 * @group Envelopes
 * @api POST /v2/envelopes Create Envelope From Template
 * @apiBody string(format:uuid) template_id The ID of the template to copy
 * @apiBody array(items:ICreateEnvelopeRecipient) recipients A list of recipients to include in the workflow. Must specify one recipient to match each template Role.
 * @apiBody string name? Override the name of the envelope (defaults to the template name).
 * @apiBody string description? Override the description of the envelope (defaults to the template description).
 * @apiBody array(items:IEnvelopeField) fields? Provide default values for fields in the envelope. Note that only "name", "role_name", and "default" should be set in this array.
 * @apiBody boolean no_contact? If set to true, no email or SMS messages will be sent to any recipients.
 * @apiBody integer(min: 0) initial_reminder? Override the template initial-reminder setting.
 * @apiBody integer(min: 0) followup_reminders? Override the template initial-reminder setting.
 * @apiSuccess IEnvelope . The newly-created envelope.
 */
const createEnvelope = async (endpoint, request) => endpoint.api //
    .post('/v2/envelopes', request)
    .then((r) => r.data);
/**
 * Get all metadata for an envelope. Note that when called by non-creators (e.g. Recipients)
 * this will return only the **metadata** the caller is allowed to view.
 *
 * @group Envelopes
 * @api GET /v2/envelopes/:id Get envelope details
 * @apiParam string(format: 'uuid') id The ID of the envelope to retrieve.
 * @apiSuccess IEnvelope . The detailed metadata for the envelope requested
 */
const getEnvelope = async (endpoint, envelopeId) => endpoint.api //
    .get(`/v2/envelopes/${envelopeId}`)
    .then((r) => r.data);
/**
 * Get all metadata for an envelope document. Note that when called by non-creators (e.g. Recipients)
 * this will return only the **metadata** the caller is allowed to view.
 *
 * @group Envelope Documents
 * @api GET /envelopes/:id Get envelope document
 * @apiParam string(format: 'uuid') id The ID of the document to retrieve.
 * @apiSuccess IEnvelopeDocument . The detailed metadata for the document requested
 */
const getEnvelopeDocument = async (endpoint, envelopeId, documentId) => endpoint.api //
    .get(`/envelopes/${envelopeId}/envelope_documents/${documentId}`)
    .then((r) => r.data);
/**
 * Get a pre-signed download link for an Envelope Document. This link expires quickly, so it should
 * be accessed immediately and never shared. Content-Disposition will be set to "download".
 *
 * @group Envelope Documents
 * @api GET /envelopes/:envelope_id/envelope_documents/:document_id Preview, Download, or Link to a Document
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to retrieve.
 * @apiParam string(format: 'uuid') document_id The ID of the document to retrieve.
 * @apiQuery boolean download? Set to true to generate a download link (content-disposition: download).
 * @apiQuery boolean preview? Set to true to generate a preview link (content-disposition: inline).
 * @apiQuery boolean file? Set to true to return the raw binary BLOB data of the file rather than a link.
 * @apiSuccess string . The generated link.
 */
const getDocumentDownloadLink = async (endpoint, envelopeId, documentId) => endpoint.api //
    .get(`/envelopes/${envelopeId}/envelope_documents/${documentId}?download=true`)
    .then((r) => r.data);
/**
 * Get a pre-signed preview link for an Envelope Document. This link expires quickly, so it should
 * be accessed immediately and never shared. Content-Disposition will be set to "inline".
 */
const getDocumentPreviewLink = async (endpoint, envelopeId, documentId) => endpoint.api //
    .get(`/envelopes/${envelopeId}/envelope_documents/${documentId}?preview=true`)
    .then((r) => r.data);
/**
 * Cancel an Envelope.
 *
 * @group Envelopes
 * @api PUT /v2/envelopes/:id Cancel envelope
 * @apiParam string(format: 'uuid') id The ID of the envelope to cancel.
 * @apiBody string(enum: 'cancel') action The action to perform (currently only "cancel" is supported).
 * @apiSuccess IEnvelope . The updated envelope.
 */
const cancelEnvelope = async (endpoint, envelopeId) => endpoint.api //
    .put(`/v2/envelopes/${envelopeId}`, { action: 'cancel' })
    .then((r) => r.data);
/**
 * Get (binary download) a file attached to an Envelope. It is important to use this method
 * rather than a direct A HREF or similar link to set the authorization headers for the
 * request.
 */
const getEnvelopeFile = async (endpoint, envelopeId, documentId) => endpoint.api //
    .get(`/envelopes/${envelopeId}/envelope_documents/${documentId}?file=true`, { responseType: 'blob' })
    .then((r) => r.data);
/**
 * Update an envelope. Currently, only reminder settings may be changed.
 *
 * @group Envelopes
 * @api PATCH /v2/envelopes/:id Update Envelope
 * @apiParam string(format: 'uuid') id The ID of the envelope to update.
 * @apiBody IEnvelope . Set of fields to update. Omit (leave undefined) any fields that should not be changed.
 * @apiSuccess IEnvelope . A copy of the newly-updated envelope.
 */
const updateEnvelope = async (endpoint, envelopeId, params) => endpoint.api //
    .patch(`/v2/envelopes/${envelopeId}`, params)
    .then((r) => r.data);
/**
 * Update a Document field. Typically called during the signing process as a Recipient fills in fields.
 *
 * @group Envelopes
 * @api PUT /envelopes/:envelope_id/fields/:field_name Update Envelope Field
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to retrieve.
 * @apiParam string field_name The name of the field to update. Be sure to URL-encode the value.
 * @apiBody IEnvelopeFieldSettings . Set of properties to update. Leave undefined any properties that should not be changed.
 * @apiSuccess IEnvelope . A copy of the newly-updated field.
 */
const updateEnvelopeField = async (endpoint, envelopeId, fieldName, value) => endpoint.api //
    .put(`/envelopes/${envelopeId}/fields/${fieldName}`, value)
    .then((r) => r.data);
/**
 * Apply a signature to a signature field. Signature fields are ID-driven. Call `createSignature()`
 * first to create a signature for a Recipient, then call `updateEnvelopeFieldSignature()` to
 * attach it to a field.
 *
 * @group Envelopes
 * @api PUT /envelopes/:envelope_id/fields/:field_name/signature/:signature_id Update Envelope
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to update.
 * @apiParam string field_name The name of the field to update. Be sure to URL-encode the value.
 * @apiParam string(format: 'uuid') signature_id The ID of the signature to attach.
 * @apiSuccess IEnvelopeFieldSettings . A copy of the newly-updated field.
 */
const updateEnvelopeFieldSignature = async (endpoint, envelopeId, fieldName, signatureId) => endpoint.api //
    .put(`/envelopes/${envelopeId}/fields/${fieldName}/signature/${signatureId}`)
    .then((r) => r.data);
/**
 * Apply an initial to an initials field. Initial fields are ID-driven. Call `createInitial()`
 * first to create an initial block for a Recipient, then call `supdateEnvelopeFieldInitials()` to
 * attach it to a field.
 *
 * @group Envelopes
 * @api PUT /envelopes/:envelope_id/fields/:field_name/initial/:initial_id Update Envelope
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to update.
 * @apiParam string field_name The name of the field to update. Be sure to URL-encode the value.
 * @apiParam string(format: 'uuid') initial_id The ID of the initial block to attach.
 * @apiSuccess IEnvelopeFieldSettings . A copy of the newly-updated field.
 */
const updateEnvelopeFieldInitials = async (endpoint, envelopeId, fieldName, initialId) => endpoint.api //
    .put(`/envelopes/${envelopeId}/fields/${fieldName}/initial/${initialId}`)
    .then((r) => r.data);
/**
 * Upload an attachment to an attachment field
 *
 * @group Envelopes
 * @api PUT /envelopes/:envelope_id/fields/:field_name Upload or Delete Attachment
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to update.
 * @apiParam string field_name The name of the field to update. Be sure to URL-encode the value.
 * @apiBody string document The file to attach. Must contain standard File object fields. If omitted, the attachment will be deleted instead.
 * @apiSuccess IEnvelopeFieldSettings . A copy of the newly-updated field.
 */
const uploadEnvelopeFieldAttachment = async (endpoint, envelopeId, fieldName, file, onUploadProgress) => {
    const formData = new FormData();
    formData.append('document', file, file.name);
    return endpoint.api //
        .put(`/envelopes/${envelopeId}/fields/${fieldName}`, formData, {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    })
        .then((r) => r.data);
};
/**
 * Delete an attachment. Note that this is not a DELETE endpoint because the field itself is not
 * being deleted. Instead, it is a similar operation to uploading a new attachment, but the
 * omission of the attachment signals the server to delete the current entry.
 */
const deleteEnvelopeFieldAttachment = async (endpoint, envelopeId, fieldName) => {
    const formData = new FormData();
    // Omitting file is the trigger here
    return endpoint.api //
        .put(`/envelopes/${envelopeId}/fields/${fieldName}`, formData)
        .then((r) => r.data);
};
/**
 * Get the attached file for an attachment field (if any).
 *
 * @group Envelopes
 * @api GET /envelopes/:envelope_id/fields/:field_name/document Download attachment in binary format
 * @apiParam string(format: 'uuid') envelope_id The ID of the envelope to retrieve.
 * @apiParam string field_name The name of the field from which to download the attachment.
 * @apiSuccess string . The file binary data.
 */
const getFieldAttachment = async (endpoint, envelopeId, fieldName) => endpoint.api //
    .get(`/envelopes/${envelopeId}/fields/${fieldName}/document`, { responseType: 'blob' })
    .then((r) => r.data);
/**
 * Get a display URI for a given page in a file attached to an envelope document. These pages are rendered server-side
 * into PNG resources suitable for display in IMG tags although they may be used elsewhere. Note that these are intended
 * for DISPLAY ONLY, are not legally binding documents, and do not contain any encoded metadata from participants.
 *
 * @group Envelopes
 * @api GET /v2/envelope-documnets/page-image/:document_id/:variant/:page Get envelope document page display URI
 * @apiParam string(format: 'uuid') document_id The ID of the document to retrieve.
 * @apiParam string(enum: 'original'|'filled') variant The variant of the document to retrieve.
 * @apiParam integer page The page number to retrieve
 * @apiSuccess string . The page display URI. Note that this is a signed URL with a short expiration. It should be used immediately and never databased or cached.
 */
const getEnvelopeDocumentPageDisplayUri = async (endpoint, documentId, page, variant = 'original') => endpoint.api.get(`/v2/envelope-documents/page-image/${documentId}/${variant}/${page}`, { timeout: 20000 }).then((r) => r.data);
/**
 * Lists all envelopes accessible by the caller, with optional filters.
 *
 * ```typescript
 * import {getEnvelopes} from '@verdocs/js-sdk/Envelopes';
 *
 * const {count, envelopes} = await getEnvelopes((VerdocsEndpoint.getDefault(), { q: 'test' });
 * ```
 *
 * @group Envelopes
 * @api GET /v2/envelopes List envelopes
 * @apiQuery string q? Match envelopes whose name contains this string
 * @apiQuery string(enum: 'inbox' | 'sent' | 'action' | 'waiting' | 'completed') view? Request pre-defined view. `inbox` returns envelopes where action is required by the caller. `sent` returns envelopes created by the caller. `action` returns envelopes where action is required by the caller. `waiting` returns envelopes where action is required by anyone. `completed` returns envelopes where all actions are complete.
 * @apiQuery array(items: 'complete' | 'pending' | 'in progress' | 'declined' | 'canceled') status? Match envelopes in one of the specified states.
 * @apiQuery boolean(default: false) include_org? If true, include organizations-shared envelopes
 * @apiQuery string(format: uuid) template_id? Match envelopes created from the specified template ID
 * @apiQuery string(format: date-time) created_before? Match envelopes created before this date
 * @apiQuery string(format: date-time) created_after? Match envelopes created after this date
 * @apiQuery string(enum: 'name' | 'created_at' | 'updated_at' | 'canceled_at' | 'status') sort_by? Return results sorted by this criteria
 * @apiQuery boolean ascending? Set true/false to override the sort direction. Note that the default depends on `sort_by`. Date-based sorts default to descending, while name and status default to ascending.
 * @apiQuery integer(default: 20) rows? Limit the number of rows returned
 * @apiQuery integer(default: 0) page? Specify which page of results to return
 * @apiSuccess integer(format: int32) count The total number of records matching the query, helpful for pagination
 * @apiSuccess integer(format: int32) rows The number of rows returned in this response page
 * @apiSuccess integer(format: int32) page The page number of this response
 * @apiSuccess array(items: IEnvelope) envelopes List of envelopes found
 */
const getEnvelopes = (endpoint, params) => endpoint.api //
    .get('/v2/envelopes', { params })
    .then((r) => r.data);

/**
 * Create an initials block. In a typical signing workflow, the user is asked at the beginning of the process to "adopt"
 * an initials block to be used for all initials fields in the document. Thus, this is typically called one time to
 * create and store an initials block. Thereafter, the ID of the initials block may be re-used for each initials field
 * to be "stamped" by the user.
 *
 * @group Signatures and Initials
 * @api POST /initials Create Initial Block
 * @apiBody string initial Blob containing initials image to store.
 * @apiSuccess IInitial . The newly-created initial block.
 */
const createInitials = (endpoint, name, initials) => {
    const data = new FormData();
    data.append('initial', initials, name);
    return endpoint.api //
        .post(`/initials`, data)
        .then((r) => r.data);
};

/**
 * Get the current KBA status. Note that this may only be called by the recipient and requires a
 * valid signing session to proceed. Although the Recipient object itself contains indications of
 * whether KBA is required, it will not contain the current status of the process. If
 * `recipient.auth_methods` is set (not empty), and `recipient.kba_completed` is false, this endpoint
 * should be called to determine the next KBA step required.
 */
const getKbaStep = (endpoint, envelope_id, role_name) => endpoint.api //
    .get(`/v2/kba/${envelope_id}/${encodeURIComponent(role_name)}`)
    .then((r) => r.data);
/**
 * Submit a response to a KBA PIN challenge.
 */
const submitKbaPin = (endpoint, envelope_id, role_name, pin) => endpoint.api //
    .post(`/v2/kba/pin`, { envelope_id, role_name, pin })
    .then((r) => r.data);
/**
 * Submit an identity response to a KBA challenge.
 */
const submitKbaIdentity = (endpoint, envelope_id, role_name, identity) => endpoint.api //
    .post(`/v2/kba/identity`, { envelope_id, role_name, identity })
    .then((r) => r.data);
/**
 * Submit an identity response to a KBA challenge. Answers should be submitted in the same order as
 * the challenges were listed in `IRecipientKbaStepChallenge.questions`.
 */
const submitKbaChallengeResponse = (endpoint, envelope_id, role_name, responses) => endpoint.api //
    .post(`/v2/kba/response`, { envelope_id, role_name, responses })
    .then((r) => r.data);

/**
 * Update a recipient's status.
 *
 * @group Recipients
 * @api PUT /envelopes/:envelope_id/recipients/:role_name Update Recipient Status
 * @apiParam string(format:uuid) envelope_id The envelope to operate on.
 * @apiParam string role_name The role to adjust.
 * @apiBody string(enum:'submit'|'decline'|'owner_update'|'update'|'prepare') action The action to take. Adjusts the status, and may also perform other operations.
 * @apiBody string first_name? Ignored unless action is 'owner_update' or 'update'. The new owner's or recipient's first name.
 * @apiBody string last_name? Ignored unless action is 'owner_update' or 'update'. The new owner's or recipient's last name.
 * @apiBody string email? Ignored unless action is 'owner_update'. The new owner's email address.
 * @apiBody boolean agreed? Ignored unless action is 'update'. Set to true to accept the e-signing disclosures.
 * @apiBody array(items:IRecipient) recipients? Ignored unless action is 'prepare'. A list of recipients and their fields to set defaults for.
 * @apiSuccess IRecipient . The updated Recipient.
 */
const updateRecipient = async (endpoint, envelope_id, role_name, params) => endpoint.api //
    .put(`/envelopes/${envelope_id}/recipients/${role_name}`, params)
    .then((r) => r.data);
/**
 * Submit an envelope (signing is finished). Note that all fields must be valid/completed for this to succeed.
 */
const envelopeRecipientSubmit = (endpoint, envelopeId, roleName) => updateRecipient(endpoint, envelopeId, roleName, { action: 'submit' });
/**
 * Decline to complete an envelope (signing will not terminated).
 */
const envelopeRecipientDecline = (endpoint, envelopeId, roleName) => updateRecipient(endpoint, envelopeId, roleName, { action: 'decline' });
/**
 * Claim / change ownership of an envelope. This is a special-case operation only available in certain workflows.
 */
const envelopeRecipientChangeOwner = (endpoint, envelope_id, role_name, email, first_name, last_name) => updateRecipient(endpoint, envelope_id, role_name, { action: 'owner_update', email, first_name, last_name });
/**
 * Agree to electronic signing.
 */
const envelopeRecipientAgree = (endpoint, envelopeId, roleName, agreed) => updateRecipient(endpoint, envelopeId, roleName, { action: 'update', agreed });
/**
 * Change a recipient's name.
 */
const envelopeRecipientUpdateName = (endpoint, envelopeId, roleName, first_name, last_name) => updateRecipient(endpoint, envelopeId, roleName, { action: 'update', first_name, last_name });
/**
 * Change a recipient's name.
 */
const envelopeRecipientPrepare = (endpoint, envelopeId, roleName, recipients) => updateRecipient(endpoint, envelopeId, roleName, { action: 'prepare', recipients });
/**
 * Begin a signing session for an Envelope. This path requires an invite code, and should generally
 * be called with a NON-default Endpoint to avoid conflicting with any active user session the user
 * may have. To initiate in-person signing by an authenticated user (e.g. self-signing), call
 * getInPersonLink() instead. The response from that call includes both a link for direct signing
 * via a Web browser as well as an in-person access_key. That access_key.key may be used here as well.
 *
 * @group Recipients
 * @api POST /v2/sign/unauth/:envelope_id/:role_name/:key Start Signing Session
 * @apiParam string(format:uuid) envelope_id The envelope to operate on.
 * @apiParam string role_name The role to request.
 * @apiParam string key Access key generated by the envelope creator or email/SMS invite.
 * @apiSuccess ISignerTokenResponse . Signing session token and envelope/recipient metadata.
 */
const startSigningSession = async (endpoint, envelope_id, role_name, key) => {
    return endpoint.api //
        .post(`/v2/sign/unauth/${envelope_id}/${encodeURIComponent(role_name)}/${key}`)
        .then((r) => {
        endpoint.setToken(r.data.access_token, 'signing');
        return r.data;
    });
};
/**
 * Get an in-person signing link. Must be called by the owner/creator of the envelope. The response
 * also includes the raw access key that may be used to directly initiate a signing session (see
 * `startSigningSession`) as well as an access token representing a valid signing session for
 * immediate use in embeds or other applications. Note that in-person signing is considered a
 * lower-security operation than authenticated signing, and the final envelope certificate will
 * reflect this.
 *
 * @group Recipients
 * @api POST /v2/sign/in-person/:envelope_id/:role_name Get In-Person Signing Link
 * @apiParam string(format:uuid) envelope_id The envelope to operate on.
 * @apiParam string role_name The role to request.
 * @apiSuccess IInPersonLinkResponse . Signing session token and envelope/recipient metadata.
 */
const getInPersonLink = (endpoint, envelope_id, role_name) => endpoint.api //
    .post(`/v2/sign/in-person/${envelope_id}/${encodeURIComponent(role_name)}`)
    .then((r) => r.data);
/**
 * Verify a recipient within a signing session. All signing sessions use an invite code at a minimum,
 * but many scenarios require more robust verification of recipients, so one or more verification
 * methods may be attached to each recipient. If an authentication method is enabled, the
 * signer must first accept the e-signature disclosures, then complete each verification step
 * before attempting to view/display documents, complete any fields, or submit the envelope.
 * This endpoint should be called to complete each step. If the call fails an error will be
 * thrown.
 *
 * @group Recipients
 * @api POST /v2/sign/verify Verify recipient/signer
 * @apiParam string(enum:'passcode'|'email'|'sms'|'kba'|'id') auth_method The authentication method being completed
 * @apiParam string code? The passcode or OTP entered. Required for passcode, email, and SMS methods.
 * @apiParam boolean resend? For SMS or email methods, set to send a new code.
 * @apiParam boolean first_name? For KBA, the recipient's first name
 * @apiParam boolean last_name? For KBA, the recipient's last name
 * @apiParam boolean address? For KBA, the recipient's address
 * @apiParam boolean city? For KBA, the recipient's city
 * @apiParam boolean state? For KBA, the recipient's state
 * @apiParam boolean zip? For KBA, the recipient's zip code
 * @apiParam boolean ssn_last_4? For KBA, the last 4 digits of the recipient's SSN
 * @apiParam boolean dob? For KBA, the recipient's date of birth
 * @apiParam array(items:IKBAResponse) responses? For KBA, responses to any challenge questions presented
 * @apiSuccess ISignerTokenResponse . Updated signing session.
 */
const verifySigner = (endpoint, params) => endpoint.api //
    .post(`/v2/sign/verify`, params)
    .then((r) => r.data);
/**
 * Send a delegation request.
 */
const sendDelegate = (endpoint, envelopeId, roleName) => endpoint.api //
    .post(`/envelopes/${envelopeId}/recipients/${encodeURIComponent(roleName)}`)
    .then((r) => r.data);
/**
 * Resend a recipient's invitation. NOTE: User interfaces should rate-limit this operation to
 * avoid spamming recipients. Excessive use of this endpoint may result in Verdocs rate-limiting
 * the calling application to prevent abuse. This endpoint will return a 200 OK even if the
 * no_contact flag is set on the envelope (in which case the call will be ignored).
 *
 * @group Recipients
 * @api PUT /v2/envelopes/:envelope_id/recipients/:role_name Resend Invitation
 * @apiParam string(format:uuid) envelope_id The envelope to operate on.
 * @apiParam string role_name The role to operate on.
 * @apiBody string(enum:'resend') action The operation to perform.
 * @apiSuccess string . Success message.
 */
const resendInvitation = (endpoint, envelopeId, roleName) => endpoint.api //
    .put(`/v2/envelopes/${envelopeId}/recipients/${encodeURIComponent(roleName)}`, { action: 'resend' })
    .then((r) => r.data);

/**
 * Various helpers to identify available operations for an envelope by a user.
 *
 * @module
 */
/**
 * Check to see if the user owns the envelope.
 */
const userIsEnvelopeOwner = (profile, envelope) => envelope.profile_id === profile?.id;
/**
 * Check to see if the user owns the envelope.
 */
const userIsEnvelopeRecipient = (profile, envelope) => envelope.profile_id === profile?.id;
/**
 * Check to see if the envelope has pending actions.
 */
const envelopeIsActive = (envelope) => envelope.status !== 'complete' && envelope.status !== 'declined' && envelope.status !== 'canceled';
/**
 * Check to see if the envelope has been completed.
 */
const envelopeIsComplete = (envelope) => envelope.status !== 'complete';
/**
 * Check to see if the user owns the envelope.
 */
const userCanCancelEnvelope = (profile, envelope) => userIsEnvelopeOwner(profile, envelope) &&
    envelope.status !== 'complete' &&
    envelope.status !== 'declined' &&
    envelope.status !== 'canceled';
/**
 * Check to see if the user owns the envelope.
 */
const userCanFinishEnvelope = (profile, envelope) => userIsEnvelopeOwner(profile, envelope) &&
    envelope.status !== 'complete' &&
    envelope.status !== 'declined' &&
    envelope.status !== 'canceled';
/**
 * Returns true if the recipient has a pending action. Note that this does not necessarily mean the recipient can act (yet).
 */
const recipientHasAction = (recipient) => !['submitted', 'canceled', 'declined'].includes(recipient.status);
/**
 * Returns the recipients who still have a pending action. Note that not all of these recipients may be able to act (yet).
 */
const getRecipientsWithActions = (envelope) => (envelope?.recipients || []).filter(recipientHasAction);
/**
 * Returns true if the recipient can act.
 */
const recipientCanAct = (recipient, recipientsWithActions) => recipient.sequence === recipientsWithActions?.[0]?.sequence;
/**
 * Returns true if the user can act.
 */
const userCanAct = (email, recipientsWithActions) => {
    const recipient = recipientsWithActions.find((r) => r.email === email);
    return recipient && recipient.sequence === recipientsWithActions?.[0]?.sequence;
};
/**
 * Returns true if the user can act.
 */
const userCanSignNow = (profile, envelope) => {
    if (!profile) {
        return false;
    }
    const recipientsWithActions = getRecipientsWithActions(envelope);
    const myRecipient = recipientsWithActions.find((r) => r.profile_id === profile?.id || r.email === profile?.email);
    return (myRecipient &&
        envelopeIsActive(envelope) &&
        userIsEnvelopeRecipient(profile, envelope) &&
        recipientCanAct(myRecipient, recipientsWithActions));
};
const getNextRecipient = (envelope) => {
    const recipientsWithActions = getRecipientsWithActions(envelope);
    return recipientsWithActions?.[0];
};

/**
 * Create a signature block. In a typical signing workflow, the user is asked at the beginning of the process to "adopt"
 * a signature block to be used for all signature fields in the document. Thus, this is typically called one time to
 * create and store a signature block. Thereafter, the ID of the signature block may be re-used for each signature field
 * to be "stamped" by the user.
 *
 * @group Signatures and Initials
 * @api POST /signatures Create Signature Block
 *
 * @apiBody string signature Blob containing signature image to store.
 * @apiSuccess ISignature . The newly-created signature block.
 */
const createSignature = (endpoint, name, signature) => {
    const data = new FormData();
    data.append('signature', signature, name);
    return endpoint.api //
        .post(`/signatures`, data)
        .then((r) => r.data);
};
/**
 * Get the available signatures for a user.
 *
 * @group Signatures and Initials
 * @api GET /signatures Create Signature Block
 *
 * @apiSuccess array(items:ISignature) . A list of signatures previously stored for the user.
 */
const getSignatures = (endpoint) => endpoint.api //
    .get('/signatures')
    .then((r) => r.data);
/**
 * Get a user's signature by ID.
 *
 * @group Signatures and Initials
 * @api GET /signatures/:id Delete Signature Block
 * @apiParam string(format: 'uuid') id The ID of the signature to delete.
 * @apiSuccess ISignature . The signature metadata requested.
 */
const getSignature = (endpoint, signatureId) => endpoint.api //
    .get(`/signatures/${signatureId}`)
    .then((r) => r.data);
/**
 * Delete a user's signature.
 *
 * @group Signatures and Initials
 * @api DELETE /signatures/:id Delete Signature Block
 * @apiParam string(format: 'uuid') id The ID of the signature to delete.
 * @apiSuccess string . OK
 */
const deleteSignature = (endpoint, signatureId) => endpoint.api //
    .delete(`/signatures/${signatureId}`)
    .then((r) => r.data);

/**
 * API keys are used to authenticate server-to-server calls. (API keys should **never** be used for client-to-server operations!)
 * To generate a key, either use the Verdocs admin interface and make note of the client_id and client_secret generated, or call
 * createKey as shown below. Then call {@link Users.Auth.authenticateApp} to obtain an access token using the provided ID and
 * secret. Note that server-to-server authentication requests return shorter-lived tokens, so it is important to check the `exp`
 * field and re-authenticate as needed for subsequent calls.
 *
 * API keys may be updated or rotated at any time. Regular rotation is recommended. Rotation will not expire or invalidate
 * existing server-to-server sessions, so it may be done at any time without disrupting your application.
 *
 * @module
 */
/**
 * Get a list of keys for a given organization. The caller must have admin access to the organization.
 *
 * ```typescript
 * import {getApiKeys} from '@verdocs/js-sdk';
 *
 * const keys = await getApiKeys(ORGID);
 * ```
 *
 * @group API Keys
 * @api GET /v2/api-keys Get API keys
 * @apiSuccess array(items: IApiKey) . A list of the API keys for the caller's organization. Secrets will not be included.
 */
const getApiKeys = (endpoint) => endpoint.api //
    .get(`/v2/api-keys`)
    .then((r) => r.data);
/**
 * Create an API key.
 *
 * ```typescript
 * import {createApiKey} from '@verdocs/js-sdk';
 *
 * await createApiKey(ORGID, {name: NEWNAME});
 * ```
 *
 * @group API Keys
 * @api POST /v2/api-keys Create API key
 * @apiBody string name A name used to identify the key in the Verdocs Web App
 * @apiBody string(format:uuid) profile_id The profile ID that calls made using the key will act as
 * @apiBody array(items:string) permission An array of permissions to assign to the new key. Extends (but does not override) the API key's profile permissions.
 * @apiSuccess IApiKey . The newly-created API key, including its secret.
 */
const createApiKey = (endpoint, params) => endpoint.api //
    .post('/v2/api-keys', params)
    .then((r) => r.data);
/**
 * Rotate the secret for an API key. The caller must have admin access to the organization.
 *
 * ```typescript
 * import {rotateApiKey} from '@verdocs/js-sdk';
 *
 * const {client_secret: newSecret} = await rotateApiKey(ORGID, CLIENTID);
 * ```
 *
 * @group API Keys
 * @api POST /v2/api-keys/:client_id/rotate Rotate API key
 * @apiParam string(format:uuid) client_id The client ID of the key to rotate
 * @apiSuccess IApiKey . The updated API key with its new secret.
 */
const rotateApiKey = (endpoint, clientId) => endpoint.api //
    .post(`/v2/api-keys/${clientId}/rotate`)
    .then((r) => r.data);
/**
 * Update an API key to change its assigned Profile ID or Name.
 *
 * ```typescript
 * import {updateApiKey} from '@verdocs/js-sdk';
 *
 * await updateApiKey(ORGID, CLIENTID, {name: NEWNAME});
 * ```
 *
 * @group API Keys
 * @api PATCH /v2/api-keys/:client_id Update API key
 * @apiBody string name? New name for the API key
 * @apiBody array(items:string) permission New array of permissions to assign to the new key. Extends (but does not override) the API key's profile permissions.
 * @apiSuccess IApiKey . The updated API key. The secret will not be included.
 */
const updateApiKey = (endpoint, clientId, params) => endpoint.api //
    .patch(`/v2/api-keys/${clientId}`, params)
    .then((r) => r.data);
/**
 * Delete an API key.
 *
 * ```typescript
 * import {deleteApiKey} from '@verdocs/js-sdk';
 *
 * await deleteApiKey(ORGID, CLIENTID);
 * ```
 *
 * @group API Keys
 * @api DELETE /v2/api-keys/:client_id Delete API key
 * @apiSuccess string . Success.
 */
const deleteApiKey = (endpoint, clientId) => endpoint.api //
    .delete(`/v2/api-keys/${clientId}`)
    .then((r) => r.data);

/**
 * An Organization Contact (aka Profile) is an individual user with no access to an organization. These entries
 * appear only in contact lists, usually to populate quick-search dropdowns when sending envelopes.
 *
 * @module
 */
/**
 * Get a list of the contacts in the caller's organization.
 *
 * ```typescript
 * import {getOrganizationContacts} from '@verdocs/js-sdk';
 *
 * const members = await getOrganizationContacts(VerdocsEndpoint.getDefault()});
 * ```
 *
 * @group Organization Contacts
 * @api GET /v2/organization-contacts Get a list of organization contacts
 * @apiBody string email Email address for the invitee
 * @apiBody string token Invite token for the invitee
 * @apiSuccess string . Success. The invitation will be marked declined and the token will be invalidated.
 */
const getOrganizationContacts = (endpoint) => endpoint.api //
    .get(`/v2/organization-contacts`)
    .then((r) => r.data);
/**
 * Delete a contact from the caller's organization. Note that the caller must be an admin or owner.
 *
 * ```typescript
 * import {deleteOrganizationContact} from '@verdocs/js-sdk';
 *
 * await deleteOrganizationContact(VerdocsEndpoint.getDefault(), 'PROFILEID'});
 * ```
 *
 * @group Organization Contacts
 * @api POST /v2/organization-invitations/decline GET a list of pending invitations
 * @apiBody string email Email address for the invitee
 * @apiBody string token Invite token for the invitee
 * @apiSuccess string . Success. The invitation will be marked declined and the token will be invalidated.
 */
const deleteOrganizationContact = (endpoint, profileId) => endpoint.api //
    .delete(`/v2/organization-contacts/${profileId}`)
    .then((r) => r.data);
/**
 * Update a member.
 *
 * ```typescript
 * import {createOrganizationContact} from '@verdocs/js-sdk';
 *
 * const result = await createOrganizationContact(VerdocsEndpoint.getDefault(), 'PROFILEID', {first_name:'First', last_name:'Last', email:'a@b.com'});
 * ```
 */
const createOrganizationContact = (endpoint, params) => endpoint.api //
    .post(`/v2/organization-contacts`, params)
    .then((r) => r.data);
/**
 * Update a member.
 *
 * ```typescript
 * import {updateOrganizationContact} from '@verdocs/js-sdk';
 *
 * const result = await updateOrganizationContact(VerdocsEndpoint.getDefault(), 'PROFILEID', {first_name:'NewFirst'});
 * ```
 */
const updateOrganizationContact = (endpoint, profileId, params) => endpoint.api //
    .patch(`/v2/organization-contacts/${profileId}`, params)
    .then((r) => r.data);

/**
 * Organizations may contain "Groups" of user profiles, called Members. Groups may have permissions assigned that
 * apply to all Members, making it easy to configure role-based access control (RBAC) within an Organization. Note
 * that permissions are **additive**. A user may be a member of more than one group, and may also have permissions
 * assigned directly. In that case, the user will have the combined set of all permissions inherited from all
 * sources.
 *
 * @module
 */
/**
 * Get a list of groups for the caller's organization. NOTE: Any organization member may request
 * the list of groups, but only Owners and Admins may update them.
 *
 * ```typescript
 * import {getGroups} from '@verdocs/js-sdk';
 *
 * const groups = await getGroups();
 * ```
 */
const getGroups = (endpoint) => endpoint.api //
    .get(`/v2/organization-groups`)
    .then((r) => r.data);
/**
 * Get the details for a group, including its member profiles and list of permissions.
 *
 * ```typescript
 * import {getGroup} from '@verdocs/js-sdk/v2/organization-groups';
 *
 * const group = await getGroup(GROUPID);
 * ```
 */
const getGroup = (endpoint, groupId) => endpoint.api //
    .get(`/v2/organization-groups/${groupId}`)
    .then((r) => r.data);
/**
 * Create a group. Note that "everyone" is a reserved name and may not be created.
 *
 * ```typescript
 * import {createGroup} from '@verdocs/js-sdk';
 *
 * const group = await createGroup(VerdocsEndpoint.getDefault(), {name:'newgroup'});
 * ```
 */
const createGroup = (endpoint, params) => endpoint.api //
    .post('/v2/organization-groups', params)
    .then((r) => r.data);
/**
 * Update a group. Note that "everyone" is a reserved name and may not be changed.
 *
 * ```typescript
 * import {updateGroup} from '@verdocs/js-sdk';
 *
 * const updated = await updateGroup(VerdocsEndpoint.getDefault(), {name:'newname'});
 * ```
 */
const updateGroup = (endpoint, groupId, params) => endpoint.api //
    .patch(`/v2/organization-groups/${groupId}`, params)
    .then((r) => r.data);
/**
 * Get an organization by ID. Note that the "everyone" group cannot be deleted.
 *
 * ```typescript
 * import {deleteGroup} from '@verdocs/js-sdk';
 *
 * await deleteGroup(VerdocsEndpoint.getDefault(), 'ORGID');
 * ```
 */
const deleteGroup = (endpoint, groupId) => endpoint.api //
    .delete(`/v2/organization-groups/${groupId}`)
    .then((r) => r.data);
/**
 * Add a member to a group.
 *
 * ```typescript
 * import {addGroupMember} from '@verdocs/js-sdk';
 *
 * await addGroupMember(VerdocsEndpoint.getDefault(), 'GROUPID', 'PROFILEID');
 * ```
 */
const addGroupMember = (endpoint, groupId, profile_id) => endpoint.api //
    .post(`/v2/organization-groups/${groupId}/members`, { profile_id })
    .then((r) => r.data);
/**
 * Remove a member from a group.
 *
 * ```typescript
 * import {deleteGroupMember} from '@verdocs/js-sdk';
 *
 * await deleteGroupMember(VerdocsEndpoint.getDefault(), 'GROUPID', 'PROFILEID');
 * ```
 */
const deleteGroupMember = (endpoint, groupId, profile_id) => endpoint.api //
    .delete(`/v2/organization-groups/${groupId}/members/${profile_id}`)
    .then((r) => r.data);

/**
 * An invitation represents an opportunity for a Member to join an Organization.
 *
 * @module
 */
/**
 * Get a list of invitations pending for the caller's organization. The caller must be an admin or owner.
 *
 * @group Organization Invitations
 * @api GET /v2/organization-invitations Get a list of pending invitations
 * @apiBody array(items:TRole) roles URL to send Webhook events to. An empty or invalid URL will disable Webhook calls.
 * @apiBody string first_name First name. The user may override this after accepting the invitation.
 * @apiBody string last_name Last name. The user may override this after accepting the invitation.
 * @apiSuccess array(items:IProfile) . List of caller's current organization's members
 */
const getOrganizationInvitations = (endpoint) => endpoint.api //
    .get(`/v2/organization-invitations`)
    .then((r) => r.data);
/**
 * Invite a new user to join the organization.
 *
 * @group Organization Invitations
 * @api POST /v2/organization-invitations Invite a new user to join the organization
 * @apiBody string email Email address to send the invitation to
 * @apiBody string first_name First name. The user may override this after accepting the invitation.
 * @apiBody string last_name Last name. The user may override this after accepting the invitation.
 * @apiBody TRole role Initial role to assign to the user once they accept.
 * @apiSuccess IOrganizationInvitation . The newly-created invitation.
 */
const createOrganizationInvitation = (endpoint, params) => endpoint.api //
    .post(`/v2/organization-invitations`, params)
    .then((r) => r.data);
/**
 * Delete an invitation. Note that no cancellation message will be sent. Invitations are also one-time-use.
 * If the invitee attempts to join after the invitation is deleted, accepted, or decline, they will be
 * shown an error.
 *
 * @group Organization Invitations
 * @api DELETE /v2/organization-invitations/:email Delete a pending invitation
 * @apiSuccess string . Success
 */
const deleteOrganizationInvitation = (endpoint, email) => endpoint.api //
    .delete(`/v2/organization-invitations/${email}`)
    .then((r) => r.data);
/**
 * Update an invitation. Note that email may not be changed after the invite is sent. To change
 * an invitee's email, delete the incorrect entry and create one with the correct value.
 *
 * @group Organization Invitations
 * @api PATCH /v2/organization-invitations/:email Update a pending invitation
 * @apiBody string first_name First name. The user may override this after accepting the invitation.
 * @apiBody string last_name Last name. The user may override this after accepting the invitation.
 * @apiBody TRole role Initial role to assign to the user once they accept.
 * @apiSuccess IOrganizationInvitation . The updated invitation.
 */
const updateOrganizationInvitation = (endpoint, email, params) => endpoint.api //
    .patch(`/v2/organization-invitations/${email}`, params)
    .then((r) => r.data);
/**
 * Send a reminder to the invitee to join the organization.
 *
 * @group Organization Invitations
 * @api POST /v2/organization-invitations/resend Send a reminder to a pending invitee
 * @apiBody string email The recipient to send the reminder to
 * @apiSuccess IOrganizationInvitation . The updated invitation
 */
const resendOrganizationInvitation = (endpoint, email) => endpoint.api //
    .post('/v2/organization-invitations/resend', { email })
    .then((r) => r.data);
/**
 * Get an invitation's details. This is generally used as the first step of accepting the invite.
 * A successful response will indicate that the invite token is still valid, and include some
 * metadata for the organization to style the acceptance screen.
 *
 * @group Organization Invitations
 * @api GET /v2/organization-invitations/:email/:token Get a pending invitation (_Authenticated via invite token, not an active session._). Intended to be called by the invitee to get details about the invitation they are about to accept.
 * @apiSuccess IOrganizationInvitation . Requested invitation's details. Will always include summary details for the organization, to be used for branding the accept-invite view.
 */
const getOrganizationInvitation = (endpoint, email, token) => endpoint.api //
    .get(`/v2/organization-invitations/${email}/${token}`)
    .then((r) => r.data);
/**
 * Accept an invitation. This will automatically create a user record for the caller as well as a profile
 * with the appropriate role as specified in the invite. The profile will be set as "current" for the caller,
 * and session tokens will be returned to access the new profile. The profile's email_verified flag will
 * also be set to true.
 *
 * @group Organization Invitations
 * @api POST /v2/organization-invitations/accept Accept an invitation
 * @apiBody string email Email address for the invitee
 * @apiBody string token Invite token for the invitee
 * @apiBody string first_name First name
 * @apiBody string last_name Last name
 * @apiBody string password Password
 * @apiSuccess IAuthenticateResponse . Session credentials for the newly-created user's profile. If the user already had a profile for another organization, the new profile will be made "current" automatically.
 */
const acceptOrganizationInvitation = (endpoint, params) => endpoint.api //
    .post('/v2/organization-invitations/accept', params)
    .then((r) => r.data);
/**
 * Decline an invitation. This will mark the status "declined," providing a visual indication to the
 * organization's admins that the invite was declined, preventing further invites from being created
 * to the same email address, and also preventing the invitee from receiving reminders to join.
 *
 * @group Organization Invitations
 * @api POST /v2/organization-invitations/decline Decline an invitation
 * @apiDescription Mark the status "declined," providing a visual indication to the organization's admins that the invite was declined, preventing further invites from being created to the same email address, and also preventing the invitee from receiving reminders to join.
 * @apiBody string email Email address for the invitee
 * @apiBody string token Invite token for the invitee
 * @apiSuccess string . Success. The invitation will be marked declined and the token will be invalidated.
 */
const declineOrganizationInvitation = (endpoint, email, token) => endpoint.api //
    .post('/v2/organization-invitations/decline', { email, token })
    .then((r) => r.data);

/**
 * An Organization Member (aka Profile) is an individual user with access to an organization.
 *
 * @module
 */
/**
 * Get a list of the members in the caller's organization.
 *
 * ```typescript
 * import {getOrganizationMembers} from '@verdocs/js-sdk';
 *
 * const members = await getOrganizationMembers(VerdocsEndpoint.getDefault()});
 * ```
 *
 * @group Organization Members
 * @api GET /v2/organization-members List current organization's members
 * @apiSuccess array(items:IProfile) . List of caller's current organization's members
 */
const getOrganizationMembers = (endpoint) => endpoint.api //
    .get(`/v2/organization-members`)
    .then((r) => r.data);
/**
 * Delete a member from the caller's organization. Note that the caller must be an admin or owner,
 * may not delete him/herself.
 *
 * ```typescript
 * import {deleteOrganizationMember} from '@verdocs/js-sdk';
 *
 * await deleteOrganizationMember(VerdocsEndpoint.getDefault(), 'PROFILEID'});
 * ```
 *
 * @group Organization Members
 * @api DELETE /v2/organization-members/:profile_id Delete a member from the organization
 * @apiSuccess string . Success
 */
const deleteOrganizationMember = (endpoint, profileId) => endpoint.api //
    .delete(`/v2/organization-members/${profileId}`)
    .then((r) => r.data);
/**
 * Update a member.
 *
 * ```typescript
 * import {updateOrganizationMember} from '@verdocs/js-sdk';
 *
 * const result = await updateOrganizationMember(VerdocsEndpoint.getDefault(), 'PROFILEID', {roles:['member']});
 * ```
 *
 * @group Organization Members
 * @api PATCH /v2/organization-members/:profile_id Update an organization member.
 * @apiBody array(items:TRole) roles URL to send Webhook events to. An empty or invalid URL will disable Webhook calls.
 * @apiBody string first_name Set to true to enable Webhooks calls.
 * @apiBody string last_name Record<TWebhookEvent, boolean> map of events to enable/disable.
 * @apiSuccess array(items:IProfile) . List of caller's current organization's members
 */
const updateOrganizationMember = (endpoint, profileId, params) => endpoint.api //
    .patch(`/v2/organization-members/${profileId}`, params)
    .then((r) => r.data);

/**
 * An Organization is the top level object for ownership for Members, Documents, and Templates.
 *
 * NOTE: There is no call specifically to create an organization. Every organization must have
 * at least one "owner" type member. To create a new organization, call createProfile() with
 * the desired new orgName to create. The caller will become the first owner of the new org, and
 * can then invite new members to join as well.
 *
 * NOTE: There is no call to delete an organization. For safety, this is a manual process. Please
 * contact support@verdocs.com if you wish to completely delete an organization and all its records.
 *
 * @module
 */
/**
 * Get an organization by ID. Note that this endpoint will return only a subset of fields
 * if the caller is not a member of the organization (the public fields).
 *
 * ```typescript
 * import {getOrganization} from '@verdocs/js-sdk';
 *
 * const organizations = await getOrganization(VerdocsEndpoint.getDefault(), 'ORGID');
 * ```
 *
 * @group Organizations
 * @api GET /v2/organizations/:organization_id Get organization
 * @apiSuccess IOrganization . The requested organization. The caller must be a member.
 */
const getOrganization = (endpoint, organizationId) => endpoint.api //
    .get(`/v2/organizations/${organizationId}`)
    .then((r) => r.data);
/**
 * Create an organization. The caller will be assigned an "Owner" profile in the new organization,
 * and it will be set to "current" automatically. A new set of session tokens will be issued to
 * the caller, and the caller should update their endpoint to use the new tokens.
 *
 * ```typescript
 * import {createOrganization} from '@verdocs/js-sdk';
 *
 * const organization = await createOrganization(VerdocsEndpoint.getDefault(), {name: 'NewOrg'});
 * ```
 *
 * @group Organizations
 * @api POST /v2/organizations Create organization
 * @apiDescription The caller will be assigned an "Owner" profile in the new organization, and it will be set to "current" automatically. A new set of session tokens will be issued to  the caller, and the caller should update their endpoint to use the new tokens.
 * @apiBody string name The name of the new organization
 * @apiBody string contact_email? Contact email for the new organization
 * @apiBody string url? URL for the new organization
 * @apiBody string full_logo_url? URL of a large-format PNG logo
 * @apiBody string thumbnail_url? URL of a small-format (square is recommended) PNG logo
 * @apiBody string primary_color? URL of a small-format (square is recommended) PNG logo
 * @apiBody string secondary_color? URL of a small-format (square is recommended) PNG logo
 * @apiSuccess IAuthenticateResponse . Authentication credentials for user in the new organization. The user will be made an Owner automatically.
 */
const createOrganization = (endpoint, params) => endpoint.api //
    .post(`/v2/organizations`, params)
    .then((r) => r.data);
/**
 * Update an organization. This can only be called by an admin or owner.
 *
 * ```typescript
 * import {updateOrganization} from '@verdocs/js-sdk';
 *
 * const organizations = await updateOrganization(VerdocsEndpoint.getDefault(), organizationId, {name:'ORGNAME'});
 * ```
 *
 * @group Organizations
 * @api PATCH /v2/organizations/:organization_id Update organization
 * @apiBody string name The name of the new organization
 * @apiBody string contact_email? Contact email for the new organization
 * @apiBody string url? URL for the new organization
 * @apiBody string full_logo_url? URL of a large-format PNG logo
 * @apiBody string thumbnail_url? URL of a small-format (square is recommended) PNG logo
 * @apiBody string primary_color? URL of a small-format (square is recommended) PNG logo
 * @apiBody string secondary_color? URL of a small-format (square is recommended) PNG logo
 * @apiSuccess IOrganization . The details for the updated organization
 */
const updateOrganization = (endpoint, organizationId, params) => endpoint.api //
    .patch(`/v2/organizations/${organizationId}`, params)
    .then((r) => r.data);
/**
 * Delete an organization. This can only be called by an owner. Inclusion of the organization ID to delete
 * is just a safety check. The caller may only delete the organization they have currently selected.
 *
 * ```typescript
 * import {deleteOrganization} from '@verdocs/js-sdk';
 *
 * const newSession = await deleteOrganization(VerdocsEndpoint.getDefault(), organizationId);
 * ```
 *
 * @group Organizations
 * @api DELETE /v2/organizations/:organization_id Delete organization
 * @apiSuccess IAuthenticateResponse . If the caller is a member of another organization, authentication credentials for the next organization available. If not, this will be null and the caller will be logged out.
 */
const deleteOrganization = (endpoint, organizationId) => endpoint.api //
    .delete(`/v2/organizations/${organizationId}`)
    .then((r) => r.data);
/**
 * Update the organization's full or thumbnail logo. This can only be called by an admin or owner.
 *
 * ```typescript
 * import {updateOrganizationLogo} from '@verdocs/js-sdk';
 *
 * await updateOrganizationLogo((VerdocsEndpoint.getDefault(), organizationId, file);
 * ```
 *
 * @group Organizations
 * @api PATCH /v2/organizations/:organization_id Update organization full or thumbnail logo.
 * @apiBody image/png logo? Form-url-encoded file to upload
 * @apiBody image/png thumbnail? Form-url-encoded file to upload
 * @apiSuccess IOrganization . The updated organization.
 */
const updateOrganizationLogo = (endpoint, organizationId, file, onUploadProgress) => {
    const formData = new FormData();
    formData.append('logo', file, file.name);
    return endpoint.api //
        .patch(`/v2/organizations/${organizationId}`, formData, {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    })
        .then((r) => r.data);
};
/**
 * Update the organization's thumbnail. This can only be called by an admin or owner.
 *
 * ```typescript
 * import {updateOrganizationThumbnail} from '@verdocs/js-sdk';
 *
 * await updateOrganizationThumbnail((VerdocsEndpoint.getDefault(), organizationId, file);
 * ```
 */
const updateOrganizationThumbnail = (endpoint, organizationId, file, onUploadProgress) => {
    const formData = new FormData();
    formData.append('thumbnail', file, file.name);
    return endpoint.api //
        .patch(`/v2/organizations/${organizationId}`, formData, {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    })
        .then((r) => r.data);
};
const getEntitlements = async (endpoint) => endpoint.api.get(`/v2/organizations/entitlements`).then((r) => r.data);
/**
 * Largely intended to be used internally by Web SDK components but may be informative for other cases.
 * Entitlements are feature grants such as "ID-based KBA" that require paid contracts to enable, typically
 * because the underlying services that support them are fee-based. Entitlements may run concurrently,
 * and may have different start/end dates e.g. "ID-based KBA" may run 1/1/2026-12/31/2026 while
 * "SMS Authentication" may be added later and run 6/1/2026-5/31/2027. The entitlements list is a simple
 * array of enablements and may include entries that are not YET enabled or have now expired.
 *
 * In client code it is helpful to simply know "is XYZ feature currently enabled?" This function collapses
 * the entitlements list to a simplified dictionary of current/active entitlements. Note that it is async
 * because it calls the server to obtain the "most current" entitlements list. Existence of an entry in the
 * resulting dictionary implies the feature is active. Metadata inside each entry can be used to determine
 * limits, etc.
 *
 * ```typescript
 * import {getActiveEntitlements} from '@verdocs/js-sdk';
 *
 * const activeEntitlements = await getActiveEntitlements((VerdocsEndpoint.getDefault());
 * const isSMSEnabled = !!activeEntitlements.sms_auth;
 * const monthlyKBALimit = activeEntitlements.kba_auth?.monthly_max;
 * ```
 */
const getActiveEntitlements = async (endpoint) => {
    if (!endpoint.session) {
        throw new Error('No active session');
    }
    const entitlements = await getEntitlements(endpoint);
    return collapseEntitlements(entitlements);
};

/**
 * Webhooks are callback triggers from Verdocs to your servers that notify your applications
 * of various events, such as signing operations.
 *
 * @module
 */
/**
 * Get the registered Webhook configuration for the caller's organization.
 *
 * ```typescript
 * import {getWebhooks} from '@verdocs/js-sdk';
 *
 * await getWebhooks(ORGID, params);
 * ```
 *
 * @group Webhooks
 * @api GET /v2/webhooks Get organization Webhooks config
 * @apiSuccess IWebhook . The current Webhooks config for the caller's organization.
 */
const getWebhooks = (endpoint) => endpoint.api //
    .get(`/v2/webhooks`)
    .then((r) => r.data);
/**
 * Update the registered Webhook configuration for the caller's organization. Note that
 * Webhooks cannot currently be deleted, but may be easily disabled by setting `active`
 * to `false` and/or setting the `url` to an empty string.
 *
 * ```typescript
 * import {setWebhooks} from '@verdocs/js-sdk';
 *
 * await setWebhooks(ORGID, params);
 * ```
 *
 * @group Webhooks
 * @api PATCH /v2/webhooks Update organization Webhooks config
 * @apiDescription Note that Webhooks cannot currently be deleted, but may be easily disabled by setting `active` to `false` and/or setting the `url` to an empty string.
 * @apiBody string url URL to send Webhook events to. An empty or invalid URL will disable Webhook calls.
 * @apiBody boolean active Set to true to enable Webhooks calls.
 * @apiBody object events Record<TWebhookEvent, boolean> map of events to enable/disable.
 * @apiSuccess IWebhook . The updated Webhooks config for the caller's organization.
 */
const setWebhooks = (endpoint, params) => endpoint.api //
    .patch(`/v2/webhooks`, params)
    .then((r) => r.data);

/**
 * A map of the permissions each role confers.
 */
const RolePermissions = {
    owner: [
        'template:creator:create:public',
        'template:creator:create:org',
        'template:creator:create:personal',
        'template:creator:delete',
        'template:creator:visibility',
        'template:member:read',
        'template:member:write',
        'template:member:delete',
        'template:member:visibility',
        'owner:add',
        'owner:remove',
        'admin:add',
        'admin:remove',
        'member:view',
        'member:add',
        'member:remove',
        'org:create',
        'org:view',
        'org:update',
        'org:delete',
        'org:transfer',
        'org:list',
        'envelope:create',
        'envelope:cancel',
        'envelope:view',
    ],
    admin: [
        'template:creator:create:public',
        'template:creator:create:org',
        'template:creator:create:personal',
        'template:creator:delete',
        'template:creator:visibility',
        'template:member:read',
        'template:member:write',
        'template:member:delete',
        'template:member:visibility',
        'admin:add',
        'admin:remove',
        'member:view',
        'member:add',
        'member:remove',
        'org:create',
        'org:view',
        'org:update',
        'org:list',
        'envelope:create',
        'envelope:cancel',
        'envelope:view',
    ],
    member: [
        'template:creator:create:public',
        'template:creator:create:org',
        'template:creator:create:personal',
        'template:creator:delete',
        'template:creator:visibility',
        'template:member:read',
        'template:member:write',
        'template:member:delete',
        'member:view',
        'org:create',
        'org:view',
        'org:list',
        'envelope:create',
        'envelope:cancel',
        'envelope:view',
    ],
    basic_user: ['template:member:read', 'member:view', 'org:view', 'org:list'],
    contact: ['org:view', 'org:list', 'org:create'],
};
/**
 * Confirm whether the user has all of the specified permissions.
 */
const userHasPermissions = (profile, permissions) => {
    // No need to de-dupe here, we're just checking present-at-least-once set membership.
    const netPermissions = [...(profile?.permissions || [])];
    (profile?.roles || []).forEach((role) => {
        netPermissions.push(...(RolePermissions[role] || []));
    });
    (profile?.group_profiles || []).forEach((groupProfile) => {
        netPermissions.push(...(groupProfile.group?.permissions || []));
    });
    return permissions.every((perm) => netPermissions.includes(perm));
};

const canPerformTemplateAction = (profile, action, template) => {
    if (!template && !action.includes('create')) {
        return { canPerform: false, message: 'Missing required template object' };
    }
    // We use BOGUS here to force the option-chain in things like template?.profile_id to NOT match profile?.profile_id because if both
    // were undefined, they would actually match.
    const profile_id = profile?.id || 'BOGUS';
    const organization_id = profile?.organization_id || 'BOGUS';
    if (!profile_id) {
        return { canPerform: false, message: 'Active session required' };
    }
    const isCreator = template?.profile_id === profile_id;
    const isSameOrg = template?.organization_id === organization_id;
    const isPersonal = template?.is_personal ?? false;
    const isPublic = template?.is_public ?? false;
    const permissionsRequired = [];
    switch (action) {
        case 'create_personal':
            permissionsRequired.push('template:creator:create:personal');
            break;
        case 'create_org':
            permissionsRequired.push('template:creator:create:org');
            break;
        case 'create_public':
            permissionsRequired.push('template:creator:create:public');
            break;
        case 'read':
            if (!isCreator) {
                if ((!isPersonal && isSameOrg) || !isPublic) {
                    permissionsRequired.push('template:member:read');
                }
            }
            break;
        case 'write':
            if (!isCreator) {
                permissionsRequired.push('template:member:read');
                permissionsRequired.push('template:member:write');
            }
            break;
        case 'change_visibility_personal':
            if (isCreator) {
                permissionsRequired.push('template:creator:create:personal');
            }
            else {
                permissionsRequired.push('template:member:visibility');
            }
            break;
        case 'change_visibility_org':
            if (isCreator) {
                permissionsRequired.push('template:creator:create:org');
            }
            else {
                permissionsRequired.push('template:member:visibility');
            }
            break;
        case 'change_visibility_public':
            if (isCreator) {
                permissionsRequired.push('template:creator:create:public');
                permissionsRequired.push('template:creator:visibility');
            }
            else {
                permissionsRequired.push('template:member:visibility');
            }
            break;
        case 'delete':
            if (isCreator) {
                permissionsRequired.push('template:creator:delete');
            }
            else {
                permissionsRequired.push('template:member:delete');
            }
            break;
        default:
            return { canPerform: false, message: 'Action is not defined' };
    }
    if (hasRequiredPermissions(profile, permissionsRequired)) {
        return { canPerform: true, message: '' };
    }
    return { canPerform: false, message: `Insufficient access to perform '${action}'. Needed permissions: ${permissionsRequired.toString()}` };
};
const hasRequiredPermissions = (profile, permissions) => permissions.every((perm) => (profile?.permissions || []).includes(perm));

/**
 * Add a field to a template.
 *
 * ```typescript
 * import {createField} from '@verdocs/js-sdk/Templates';
 *
 * await createField((VerdocsEndpoint.getDefault(), template_id, { ... });
 * ```
 *
 * @group Fields
 * @api POST /v2/fields/:template_id Add a field to a template
 * @apiBody string name Name for the new field. Field names must be unique within a template. Although special characters are allowed, they must be URL-encoded in subsequent requests, so it is recommended to use only alphanumeric characters and hyphens if possible.
 * @apiBody string role_name Role to assign to the field. Role names must be valid, so it is recommended to create roles before fields.
 * @apiBody string document_id ID of the document upon which to place the field.
 * @apiBody string(enum: 'signature' | 'initial' | 'checkbox' | 'radio' | 'textbox' | 'timestamp' | 'date' | 'dropdown' | 'textarea' | 'attachment' | 'payment') type Type of field to create
 * @apiBody boolean(default: false) required Whether the field is required
 * @apiBody integer(min: 0) page 0-based page number upon which to place the field
 * @apiBody integer(min: 0) x X position for the field (left to right)
 * @apiBody integer(min: 0) y Y position for the field (_bottom to top!_)
 * @apiBody string label? Optional label to display above the field
 * @apiBody integer(min: 50) width? Width of the field. Note that all fields have built-in defaults, and it is recommended that this only be set on text fields.
 * @apiBody integer(min: 15) height? Height of the field. Note that all fields have built-in defaults, and it is recommended that this only be set on text fields.
 * @apiBody string placeholder? Optional placeholder to display in text fields
 * @apiBody string group? For fields that support grouping (radio buttons and check boxes) the value selected will be stored under this name
 * @apiBody array(items:IDropdownOption) options? For dropdown fields, the options to display
 * @apiBody string value? Optional default value to set on the field
 * @apiSuccess ITemplateField . Template field
 */
const createField = (endpoint, templateId, params) => endpoint.api //
    .post(`/v2/fields/${templateId}`, params)
    .then((r) => r.data);
/**
 * Update a template field.
 *
 * ```typescript
 * import {updateField} from '@verdocs/js-sdk/Templates';
 *
 * await updateField((VerdocsEndpoint.getDefault(), template_id, field_name, { ... });
 * ```
 *
 * @group Fields
 * @api PATCH /v2/fields/:template_id/:field_name Update a field. See createField for additional details on the supported parameters.
 * @apiBody string name? Rename the field. Note that template field names must be unique within a template.
 * @apiBody string role_name Role to assign to the field.
 * @apiBody string document_id ID of the document upon which to place the field.
 * @apiBody string(enum: 'signature' | 'initial' | 'checkbox' | 'radio' | 'textbox' | 'timestamp' | 'date' | 'dropdown' | 'textarea' | 'attachment' | 'payment') type? Change the field type. Note that while this is technically allowed, fields have different behaviors, validators, default sizes, etc. It is usually easier to add a new field and delete the old one.
 * @apiBody boolean(default: false) required? Whether the field is required
 * @apiBody integer(min: 0) page? 0-based page number upon which to place the field
 * @apiBody integer(min: 0) x? X position for the field (left to right)
 * @apiBody integer(min: 0) y? Y position for the field (_bottom to top!_)
 * @apiBody string label? Optional label to display above the field
 * @apiBody integer(min: 50) width? Width of the field. Note that all fields have built-in defaults, and it is recommended that this only be set on text fields.
 * @apiBody integer(min: 15) height? Height of the field. Note that all fields have built-in defaults, and it is recommended that this only be set on text fields.
 * @apiBody string placeholder? Optional placeholder to display in text fields
 * @apiBody string group? For fields that support grouping (radio buttons and check boxes) the value selected will be stored under this name
 * @apiBody array(items:IDropdownOption) options? For dropdown fields, the options to display
 * @apiBody string value? Optional default value to set on the field
 * @apiSuccess ITemplateField . Updated template field
 */
const updateField = (endpoint, templateId, name, params) => endpoint.api //
    .patch(`/v2/fields/${templateId}/${encodeURIComponent(name)}`, params)
    .then((r) => r.data);
/**
 * Remove a field from a template.
 *
 * ```typescript
 * import {deleteField} from '@verdocs/js-sdk/Templates';
 *
 * await deleteField((VerdocsEndpoint.getDefault(), template_id, field_name);
 * ```
 *
 * @group Fields
 * @api DELETE /v2/fields/:template_id/:field_name Delete a field
 * @apiSuccess string . Success
 */
const deleteField = (endpoint, templateId, name) => endpoint.api //
    .delete(`/v2/fields/${templateId}/${encodeURIComponent(name)}`)
    .then((r) => r.data);

/**
 * Various helpers to identify available operations for a template by a user.
 *
 * @module
 */
/**
 * Check to see if the user created the template.
 */
const userIsTemplateCreator = (profile, template) => profile && template && profile.id === template.profile_id;
/**
 * Check to see if a template is "shared" with the user.
 */
const userHasSharedTemplate = (profile, template) => profile && template && !template.is_personal && profile.organization_id === template.organization_id;
/**
 * Check to see if the user can create a personal/private template.
 */
const userCanCreatePersonalTemplate = (profile) => userHasPermissions(profile, ['template:creator:create:personal']);
/**
 * Check to see if the user can create an org-shared template.
 */
const userCanCreateOrgTemplate = (profile) => userHasPermissions(profile, ['template:creator:create:org']);
/**
 * Check to see if the user can create a public template.
 */
const userCanCreatePublicTemplate = (profile) => userHasPermissions(profile, ['template:creator:create:public']);
/**
 * Check to see if the user can read/view a template.
 */
const userCanReadTemplate = (profile, template) => template.is_public ||
    userIsTemplateCreator(profile, template) ||
    (userHasSharedTemplate(profile, template) && userHasPermissions(profile, ['template:member:read']));
/**
 * Check to see if the user can update a tempate.
 */
const userCanUpdateTemplate = (profile, template) => userIsTemplateCreator(profile, template) ||
    (userHasSharedTemplate(profile, template) && userHasPermissions(profile, ['template:member:read', 'template:member:write']));
/**
 * Check to see if the user can change whether a template is personal vs org-shared.
 */
const userCanMakeTemplatePrivate = (profile, template) => userIsTemplateCreator(profile, template)
    ? userHasPermissions(profile, ['template:creator:create:personal'])
    : userHasPermissions(profile, ['template:member:visibility']);
/**
 * Check to see if the user can change whether a template is personal vs org-shared.
 */
const userCanMakeTemplateShared = (profile, template) => userIsTemplateCreator(profile, template)
    ? userHasPermissions(profile, ['template:creator:create:org'])
    : userHasPermissions(profile, ['template:member:visibility']);
/**
 * Check to see if the user can change whether a template is personal vs org-shared.
 */
const userCanMakeTemplatePublic = (profile, template) => userIsTemplateCreator(profile, template)
    ? userHasPermissions(profile, ['template:creator:create:public'])
    : userHasPermissions(profile, ['template:member:visibility']);
/**
 * Check to see if the user can change whether a template is personal vs org-shared.
 */
const userCanChangeOrgVisibility = (profile, template) => userIsTemplateCreator(profile, template) && userHasPermissions(profile, ['template:creator:create:personal']);
/**
 * Check to see if the user can change whether a template is personal vs org-shared.
 */
const userCanDeleteTemplate = (profile, template) => userIsTemplateCreator(profile, template)
    ? userHasPermissions(profile, ['template:creator:delete'])
    : userHasPermissions(profile, ['template:member:delete']);
/**
 * Confirm whether the user can create an envelope using the specified template.
 */
const userCanSendTemplate = (profile, template) => {
    switch (template.visibility) {
        case 'private':
            return userIsTemplateCreator(profile, template);
        case 'shared':
            return userIsTemplateCreator(profile, template) || template.organization_id === profile?.organization_id;
        case 'public':
            return true;
    }
};
/**
 * Confirm whether the user can create a new template.
 */
const userCanCreateTemplate = (profile) => userCanCreatePersonalTemplate(profile) || userCanCreateOrgTemplate(profile) || userCanCreatePublicTemplate(profile);
/**
 * Check to see if the user can "build" the template (use the field builder). The user must have write access to the
 * template, and the template must have at least one signer role.
 */
const userCanBuildTemplate = (profile, template) => userCanUpdateTemplate(profile, template) && (template.roles || []).filter((role) => role.type === 'signer').length > 0;
const getFieldsForRole = (template, role_name) => (template.fields || []).filter((field) => field.role_name === role_name);
/**
 * Check to see if the user can preview the template. The user must have read access to the template, the template must
 * have at least one signer, and every signer must have at least one field.
 */
const userCanPreviewTemplate = (profile, template) => {
    const hasPermission = userCanReadTemplate(profile, template);
    const signers = (template.roles || []).filter((role) => role.type === 'signer');
    return hasPermission && signers.length > 0 && signers.every((signer) => getFieldsForRole(template, signer.name).length > 0);
};

/**
 * A "role" is an individual participant in a signing flow, such as a signer or CC contact.
 * A role is a placeholder that will eventually become a named recipient. For example, "Tenant 1"
 * might be replaced with "John Smith" when the document is sent out for signature.
 *
 * Role names must be unique within a template, e.g. 'Recipient 1'. They may contain any [a-zA-Z0-9_- ]
 * characters, although it is recommended to keep them simple and human-readable, and to avoid
 * spaces (although they are allowed). If spaces are used in role names, be sure to URL-encode them
 * when calling endpoints like `updateRole()` e.g. 'Recipient%201'.
 *
 * NOTE: Roles are always enumerated under Template objects, so there are no "list" or "get" endpoints
 * for them. To get a template's latest role list, simply call `getTemplate()`.
 *
 * @module
 */
/**
 * Create a role.
 *
 * ```typescript
 * import {createTemplateRole} from '@verdocs/js-sdk';
 *
 * const role = await createTemplateRole(VerdocsEndpoint.getDefault(), template_id, params...);
 * ```
 *
 * @group Roles
 * @api POST /v2/roles/:template_id Add a role to a template
 * @apiBody string name Name for the new role. Must be unique within the template. May include spaces, but later calls must URL-encode any references to this role, so it is recomended that special characters be avoided.
 * @apiBody string(enum:'signer' | 'cc' | 'approver') type Type of role to create. Signers act on documents by filling and signing fields. CC recipients receive a copy but do not act on the document. Approvers control the final submission of a document, but do not have fields of their own to fill out.
 * @apiBody string full_name? Default full name for the role. May be completed/overridden later, when envelopes are made from the template.
 * @apiBody string email? Default email address for the role. May be completed/overridden later, when envelopes are made from the template.
 * @apiBody string phone? Default (SMS-capable) phone number for the role. May be completed/overridden later, when envelopes are made from the template.
 * @apiBody string message? Optional message to include in email and SMS signing invitations.
 * @apiBody integer(min: 1, default: 1) sequence? Optional 1-based sequence number for the role. Roles that share the same sequence number act in parallel, and will receive invitations at the same time.
 * @apiBody integer(min: 1, default: 1) order? Optional 1-based order number for the role. Controls the left-to-right display order of roles at the same sequence number in the UI components e.g. `<verdocs-template-roles />`.
 * @apiBody boolean delegator? If true, the role may delegate their signing responsibility to another party.
 * @apiSuccess IRole . The newly-created role
 */
const createTemplateRole = (endpoint, template_id, params) => endpoint.api //
    .post(`/v2/roles/${template_id}`, params)
    .then((r) => r.data);
/**
 * Update a role.
 *
 * ```typescript
 * import {updateTemplateRole} from '@verdocs/js-sdk';
 *
 * const role = await updateTemplateRole(VerdocsEndpoint.getDefault(), template_id, name, params...);
 * ```
 *
 * @group Roles
 * @api PATCH /v2/roles/:template_id/:role_id Update a role. See createRole for additional details on the parameters available.
 * @apiBody string name? Rename the role. Note that role names must be unique within a template, so this may fail if the new name is already in use.
 * @apiBody string(enum:'signer' | 'cc' | 'approver') type? Type of role.
 * @apiBody string full_name? Default full name for the role.
 * @apiBody string email? Default email address for the role.
 * @apiBody string phone? Default (SMS-capable) phone number for the role.
 * @apiBody string message? Optional message to include in email and SMS signing invitations.
 * @apiBody integer(min: 1, default: 1) sequence? Optional 1-based sequence number for the role.
 * @apiBody integer(min: 1, default: 1) order? Optional 1-based order number for the role.
 * @apiBody boolean delegator? If true, the role may delegate their signing responsibility to another party.
 * @apiBody string(enum:'pin'|'identity'|'') kba_method? Active PIN- or Identity-based KBA for the role.
 * @apiSuccess IRole . The newly-created role
 */
const updateTemplateRole = (endpoint, template_id, name, params) => endpoint.api //
    .patch(`/v2/roles/${template_id}/${encodeURIComponent(name)}`, params)
    .then((r) => r.data);
/**
 * Delete a role.
 *
 * ```typescript
 * import {deleteTemplateRole} from '@verdocs/js-sdk';
 *
 * const profiles = await deleteTemplateRole(VerdocsEndpoint.getDefault(), template_id, name);
 * ```
 *
 * @group Roles
 * @api DELETE /v2/roles/:template_id/:role_id Delete a role.
 * @apiSuccess string . Success
 */
const deleteTemplateRole = (endpoint, template_id, name) => endpoint.api //
    .delete(`/v2/roles/${template_id}/${encodeURIComponent(name)}`)
    .then((r) => r.data);

/**
 * Get the template stars for a template.
 */
const getStars = (endpoint, templateId) => endpoint.api //
    .get(`/templates/${templateId}/stars`)
    .then((r) => r.data);
/**
 * Toggle the template star for a template.
 */
const toggleStar = (endpoint, templateId) => endpoint.api //
    .post(`/templates/${templateId}/stars/toggle`)
    .then((r) => r.data);

/**
 * A Tag is a user-specified label applied to a template. Tags help users organize and find Templates.
 * recipients. Every Organization has a set of tags "owned" by that Organization and only visible inside it.
 * Verdocs also provides a set of system-wide "featured" tags available to all Organizations.
 *
 * @module
 */
/**
 * Apply a tag to a template.
 */
const addTemplateTag = (endpoint, templateId, params) => endpoint.api //
    .post(`/templates/${templateId}/tags/`, params)
    .then((r) => r.data);
/**
 * Get all tags for a template.
 */
const getTemplateTags = (endpoint, templateId) => endpoint.api //
    .get(`/templates/${templateId}/tags/`)
    .then((r) => r.data);
/**
 * Remove a tag from a template.
 */
const deleteTemplateTag = (endpoint, templateId, tagName) => endpoint.api //
    .post(`/templates/${templateId}/tags/${tagName}`)
    .then((r) => r.data);
/**
 * Create an Organization-wide tag.
 */
const createTag = (endpoint, name) => endpoint.api //
    .post('/tags', { tag_name: name })
    .then((r) => r.data);
/**
 * Get an Organization-wide tag.
 */
const getTag = (endpoint, name) => endpoint.api //
    .get(`/tags/${name}`)
    .then((r) => r.data);
/**
 * Get all tags available for use by an Organization.
 */
const getAllTags = (endpoint) => endpoint.api //
    .get('/tags')
    .then((r) => r.data);

/**
 * A Template defines how a Verdocs signing flow will be performed, including attachments, signing fields, and
 * recipients.
 *
 * @module
 */
/**
 * Get all templates accessible by the caller, with optional filters.
 *
 * ```typescript
 * import {getTemplates} from '@verdocs/js-sdk/Templates';
 *
 * await getTemplates((VerdocsEndpoint.getDefault());
 * await getTemplates((VerdocsEndpoint.getDefault(), { is_starred: true });
 * await getTemplates((VerdocsEndpoint.getDefault(), { is_creator: true });
 * await getTemplates((VerdocsEndpoint.getDefault(), { is_organization: true });
 * ```
 *
 * @group Templates
 * @api GET /v2/templates Get Templates
 * @apiQuery string q? Find templates whose names/descriptions contain the specified query string
 * @apiQuery boolean is_starred? If true, returns only templates with at least one "star".
 * @apiQuery boolean is_creator? If true, returns only templates that the caller created.
 * @apiQuery string(enum: 'private_shared' | 'private' | 'shared' | 'public') visibility? Return only templates with the specified visibility.
 * @apiQuery string(enum: 'created_at' | 'updated_at' | 'name' | 'last_used_at' | 'counter' | 'star_counter') sort_by? Return results sorted by this criteria
 * @apiQuery boolean ascending? Set true/false to override the sort direction. Note that the default depends on `sort_by`. Date-based sorts default to descending, while name defaults to ascending.
 * @apiQuery integer(default: 20) rows? Limit the number of rows returned
 * @apiQuery integer(default: 0) page? Specify which page of results to return
 * @apiSuccess integer(format: int32) count The total number of records matching the query, helpful for pagination
 * @apiSuccess integer(format: int32) rows The number of rows returned in this response page
 * @apiSuccess integer(format: int32) page The page number of this response
 * @apiSuccess array(items: ITemplate) templates List of templates found
 */
const getTemplates = (endpoint, params) => endpoint.api //
    .get('/v2/templates', { params })
    .then((r) => r.data);
/**
 * Get one template by its ID.
 *
 * ```typescript
 * import {getTemplate} from '@verdocs/js-sdk/Templates';
 *
 * const template = await getTemplate((VerdocsEndpoint.getDefault(), '83da3d70-7857-4392-b876-c4592a304bc9');
 * ```
 *
 * @group Templates
 * @api GET /v2/templates/:template_id Get a template. Note that the caller must have at least View access to the template.
 * @apiSuccess ITemplate . The requested template
 */
const getTemplate = (endpoint, templateId) => {
    window?.console?.log('[JS_SDK] Loading template', templateId);
    return endpoint.api //
        .get(`/v2/templates/${templateId}`)
        .then((r) => {
        const template = r.data;
        window?.console?.log('[JS_SDK] Post-processing template', template);
        // Post-process the template to upgrade to new data fields
        if (!template.documents && template.template_documents) {
            template.documents = template.template_documents;
        }
        template.documents?.forEach((document) => {
            if (!document.order) {
                document.order = 0;
            }
            if (document.page_numbers) {
                document.pages = document.page_numbers;
            }
        });
        // Temporary upgrade from legacy app
        template.fields?.forEach((field) => {
            if (field.setting) {
                field.settings = field.setting;
            }
        });
        return template;
    });
};
const ALLOWED_CREATE_FIELDS = [
    'name',
    'is_personal',
    'is_public',
    'sender',
    'description',
    'roles',
    'fields',
];
/**
 * Create a template.
 *
 * ```typescript
 * import {createTemplate} from '@verdocs/js-sdk/Templates';
 *
 * const newTemplate = await createTemplate((VerdocsEndpoint.getDefault(), {...});
 * ```
 *
 * @group Templates
 * @api POST /v2/templates Create a template
 * @apiBody string name Template name
 * @apiBody string description? Optional description
 * @apiBody TTemplateVisibility visibility? Visibility setting
 * @apiBody boolean is_personal? Deprecated. If true, the template is personal and can only be seen by the caller. (Use "visibility" for new calls.)
 * @apiBody boolean is_public? Deprecated. If true, the template is public and can be seen by anybody. (Use "visibility" for new calls.)
 * @apiBody TTemplateSender sender? Who may send envelopes using this template
 * @apiBody number initial_reminder? Delay (in seconds) before the first reminder is sent (min: 4hrs). Set to 0 or null to disable.
 * @apiBody number followup_reminders? Delay (in seconds) before the subsequent reminders are sent (min: 12hrs). Set to 0 or null to disable.
 * @apiBody array(items:object) documents? Optional list of documents to attach to the template
 * @apiBody array(items:IRole) roles? Optional list of roles to create. Note that if roles are not included in the request, fields will be ignored.
 * @apiBody array(fields:ITemplateField) fields? Optional list of fields to create. Note that if fields that do not match a role will be ignored.
 * @apiSuccess ITemplate . The newly-created template
 */
const createTemplate = (endpoint, params, onUploadProgress) => {
    const options = {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    };
    if (params.documents && params.documents[0] instanceof File) {
        const formData = new FormData();
        ALLOWED_CREATE_FIELDS.forEach((allowedKey) => {
            if (params[allowedKey] !== undefined) {
                formData.append(allowedKey, params[allowedKey]);
            }
        });
        params.documents.forEach((file) => {
            formData.append('documents', file, file.name);
        });
        return endpoint.api.post('/v2/templates', formData, options).then((r) => r.data);
    }
    else {
        return endpoint.api.post('/v2/templates', params, options).then((r) => r.data);
    }
};
/**
 * Duplicate a template. Creates a complete clone, including all settings (e.g. reminders), fields,
 * roles, and documents.
 *
 * ```typescript
 * import {duplicateTemplate} from '@verdocs/js-sdk/Templates';
 *
 * const newTemplate = await duplicateTemplate((VerdocsEndpoint.getDefault(), originalTemplateId, 'My Template Copy');
 * ```
 *
 * @group Templates
 * @api PUT /v2/templates/:template_id Perform an operation on a template
 * @apiBody string(enum:'duplicate') action Action to perform
 * @apiBody string name? If duplicating the template, a name for the new copy
 * @apiSuccess ITemplate . The newly-copied template
 */
const duplicateTemplate = (endpoint, templateId, name) => endpoint.api //
    .put(`/v2/templates/${templateId}`, { action: 'duplicate', name })
    .then((r) => r.data);
/**
 * Create a template from a Sharepoint asset.
 *
 * ```typescript
 * import {createTemplateFromSharepoint} from '@verdocs/js-sdk/Templates';
 *
 * const newTemplate = await createTemplateFromSharepoint((VerdocsEndpoint.getDefault(), {...});
 * ```
 *
 * @group Templates
 * @api POST /v2/templates/from-sharepoint Create a template from an asset in Sharepoint
 * @apiBody string name Name for the new template
 * @apiBody string siteId Name for the new template
 * @apiBody string itemId Name for the new template
 * @apiBody string oboToken On-Behalf-Of token for calls to Sharepoint. Should be generated as a short-expiration token with at least Read privileges to the siteId/itemId. This token will be discarded after being used.
 * @apiSuccess ITemplate . The newly-created template
 */
const createTemplateFromSharepoint = (endpoint, params) => {
    const options = {
        timeout: 120000,
    };
    return endpoint.api.post('/v2/templates/from-sharepoint', params, options).then((r) => r.data);
};
/**
 * Update a template.
 *
 * ```typescript
 * import {updateTemplate} from '@verdocs/js-sdk/Templates';
 *
 * const updatedTemplate = await updateTemplate((VerdocsEndpoint.getDefault(), '83da3d70-7857-4392-b876-c4592a304bc9', { name: 'New Name' });
 * ```
 *
 * @group Templates
 * @api PATCH /v2/templates/:template_id Update a template
 * @apiBody string name? Template name
 * @apiBody string description? Optional description
 * @apiBody TTemplateVisibility visibility? Visibility setting
 * @apiBody boolean is_personal? Deprecated. If true, the template is personal and can only be seen by the caller. (Use "visibility" for new calls.)
 * @apiBody boolean is_public? Deprecated. If true, the template is public and can be seen by anybody. (Use "visibility" for new calls.)
 * @apiBody TTemplateSender sender? Who may send envelopes using this template
 * @apiBody number initial_reminder? Delay (in seconds) before the first reminder is sent (min: 4hrs). Set to 0 or null to disable.
 * @apiBody number followup_reminders? Delay (in seconds) before the subsequent reminders are sent (min: 12hrs). Set to 0 or null to disable.
 * @apiSuccess ITemplate . The updated template
 */
const updateTemplate = (endpoint, templateId, params) => endpoint.api //
    .patch(`/v2/templates/${templateId}`, params)
    .then((r) => r.data);
/**
 * Delete a template.
 *
 * ```typescript
 * import {deleteTemplate} from '@verdocs/js-sdk/Templates';
 *
 * await deleteTemplate((VerdocsEndpoint.getDefault(), '83da3d70-7857-4392-b876-c4592a304bc9');
 * ```
 *
 * @group Templates
 * @api DELETE /v2/templates/:template_id Delete a template
 * @apiSuccess string . Success
 */
const deleteTemplate = (endpoint, templateId) => endpoint.api //
    .delete(`/v2/templates/${templateId}`)
    .then((r) => r.data);

/**
 * A TemplateDocument represents a PDF or other attachment in a Template.
 *
 * @module
 */
/**
 * Get all the Template Documents associated to a particular Template.
 *
 * ```typescript
 * import {TemplateDocument} from '@verdocs/js-sdk/Templates';
 *
 * await TemplateDocument.geTemplateDocuments((VerdocsEndpoint.getDefault(), templateId);
 * ```
 *
 * @group Template Documents
 * @api GET /v2/templates/:template_id/documents List the documents assigned to a template
 * @apiSuccess array(items: ITemplateDocument) . Template documents
 */
const getTemplateDocuments = (endpoint, templateId) => endpoint.api //
    .get(`/templates/${templateId}/documents/`)
    .then((r) => r.data);
/**
 * Get a specific Document.
 *
 * ```typescript
 * import {TemplateDocument} from '@verdocs/js-sdk/Templates';
 *
 * await TemplateDocument.geTemplateDocument((VerdocsEndpoint.getDefault(), templateId,documentId);
 * ```
 *
 * @group Template Documents
 * @api GET /v2/templates/:template_id/documents/:document_id Get an individual template document
 * @apiSuccess ITemplateDocument . Template document
 */
const getTemplateDocument = (endpoint, templateId, documentId) => endpoint.api //
    .get(`/templates/${templateId}/documents/${documentId}`)
    .then((r) => r.data);
/**
 * Create a Document for a particular Template.
 *
 * ```typescript
 * import {TemplateDocument} from '@verdocs/js-sdk/Templates';
 *
 * await TemplateDocument.createDocument((VerdocsEndpoint.getDefault(), templateID, params);
 * ```
 *
 * @group Template Documents
 * @api POST /v2/templates/:template_id/documents Attach a document to a template
 * @apiBody string(format:binary) file Document file to attach. The file name will automatically be used as the document name.
 * @apiSuccess ITemplateDocument . Template document
 */
const createTemplateDocument = (endpoint, templateId, file, onUploadProgress) => {
    const formData = new FormData();
    formData.append('document', file, file.name);
    return endpoint.api //
        .post(`/templates/${templateId}/documents`, formData, {
        timeout: 120000,
        onUploadProgress: (event) => {
            const total = event.total || 1;
            const loaded = event.loaded || 0;
            onUploadProgress?.(Math.floor((loaded * 100) / (total)), loaded, total);
        },
    })
        .then((r) => r.data);
};
/**
 * Delete a specific Document.
 *
 * ```typescript
 * import {TemplateDocument} from '@verdocs/js-sdk/Templates';
 *
 * await TemplateDocument.deleteDocument((VerdocsEndpoint.getDefault(), templateID, documentID);
 * ```
 *
 * @group Template Documents
 * @api DELETE /v2/templates/:temlate_id/documents/:document_id Delete a template document
 * @apiSuccess string . Success
 */
const deleteTemplateDocument = (endpoint, templateId, documentId) => endpoint.api //
    .delete(`/templates/${templateId}/documents/${documentId}`)
    .then((r) => r.data);
/**
 * Get (binary download) a file attached to a Template. It is important to use this method
 * rather than a direct A HREF or similar link to set the authorization headers for the
 * request.
 */
const getTemplateDocumentFile = async (endpoint, templateId, documentId) => endpoint.api //
    .get(`/templates/${templateId}/documents/${documentId}?file=true`, { responseType: 'blob' })
    .then((r) => r.data);
/**
 * Get (binary download) a file attached to a Template. It is important to use this method
 * rather than a direct A HREF or similar link to set the authorization headers for the
 * request.
 */
const getTemplateDocumentThumbnail = async (endpoint, templateId, documentId) => endpoint.api //
    .get(`/templates/${templateId}/documents/${documentId}?thumbnail=true`, { responseType: 'blob' })
    .then((r) => r.data);
/**
 * Get a display URI for a given page in a file attached to a template document. These pages are rendered server-side
 * into PNG resources suitable for display in IMG tags although they may be used elsewhere. Note that these are intended
 * for DISPLAY ONLY, are not legally binding documents, and do not contain any encoded metadata from participants. The
 * original asset may be obtained by calling `getTemplateDocumentFile()` or similar.
 */
const getTemplateDocumentPageDisplayUri = async (endpoint, documentId, page, variant = 'original') => endpoint.api.get(`/v2/template-documents/page-image/${documentId}/${variant}/${page}`, { timeout: 20000 }).then((r) => r.data);

/**
 * Get all defined validators
 *
 * ```typescript
 * import {Documents} from '@verdocs/js-sdk/Templates';
 *
 * await Documents.getDocuments(templateID);
 * ```
 */
const getValidators = (endpoint) => endpoint.api //
    .get('/validators')
    .then((r) => r.data);
const getValidator = (endpoint, validatorName) => endpoint.api //
    .get(`/validators/${validatorName}`)
    .then((r) => r.data);
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const isValidEmail = (email) => !!email && EMAIL_REGEX.test(email);
// @see https://www.regextester.com/1978
const PHONE_REGEX = /((?:\+|00)[17](?: |\-)?|(?:\+|00)[1-9]\d{0,2}(?: |\-)?|(?:\+|00)1\-\d{3}(?: |\-)?)?(0\d|\([0-9]{3}\)|[1-9]{0,3})(?:((?: |\-)[0-9]{2}){4}|((?:[0-9]{2}){4})|((?: |\-)[0-9]{3}(?: |\-)[0-9]{4})|([0-9]{7}))/;
const isValidPhone = (phone) => !!phone && PHONE_REGEX.test(phone);
const isValidRoleName = (value, roles) => roles.findIndex((role) => role.name === value) !== -1;
const TagRegEx = /^[a-zA-Z0-9-]{0,32}$/;
const isValidTag = (value, tags) => TagRegEx.test(value) || tags.findIndex((tag) => tag === value) !== -1;

exports.ALL_PERMISSIONS = ALL_PERMISSIONS;
exports.AtoB = AtoB;
exports.Countries = Countries;
exports.DEFAULT_FIELD_HEIGHTS = DEFAULT_FIELD_HEIGHTS;
exports.DEFAULT_FIELD_WIDTHS = DEFAULT_FIELD_WIDTHS;
exports.FIELD_TYPES = FIELD_TYPES;
exports.RolePermissions = RolePermissions;
exports.VerdocsEndpoint = VerdocsEndpoint;
exports.WEBHOOK_EVENTS = WEBHOOK_EVENTS;
exports.acceptOrganizationInvitation = acceptOrganizationInvitation;
exports.addGroupMember = addGroupMember;
exports.addTemplateTag = addTemplateTag;
exports.authenticate = authenticate;
exports.blobToBase64 = blobToBase64;
exports.canPerformTemplateAction = canPerformTemplateAction;
exports.cancelEnvelope = cancelEnvelope;
exports.capitalize = capitalize;
exports.changePassword = changePassword;
exports.collapseEntitlements = collapseEntitlements;
exports.convertToE164 = convertToE164;
exports.createApiKey = createApiKey;
exports.createEnvelope = createEnvelope;
exports.createField = createField;
exports.createGroup = createGroup;
exports.createInitials = createInitials;
exports.createOrganization = createOrganization;
exports.createOrganizationContact = createOrganizationContact;
exports.createOrganizationInvitation = createOrganizationInvitation;
exports.createProfile = createProfile;
exports.createSignature = createSignature;
exports.createTag = createTag;
exports.createTemplate = createTemplate;
exports.createTemplateDocument = createTemplateDocument;
exports.createTemplateFromSharepoint = createTemplateFromSharepoint;
exports.createTemplateRole = createTemplateRole;
exports.declineOrganizationInvitation = declineOrganizationInvitation;
exports.decodeAccessTokenBody = decodeAccessTokenBody;
exports.decodeJWTBody = decodeJWTBody;
exports.deleteApiKey = deleteApiKey;
exports.deleteEnvelopeFieldAttachment = deleteEnvelopeFieldAttachment;
exports.deleteField = deleteField;
exports.deleteGroup = deleteGroup;
exports.deleteGroupMember = deleteGroupMember;
exports.deleteOrganization = deleteOrganization;
exports.deleteOrganizationContact = deleteOrganizationContact;
exports.deleteOrganizationInvitation = deleteOrganizationInvitation;
exports.deleteOrganizationMember = deleteOrganizationMember;
exports.deleteProfile = deleteProfile;
exports.deleteSignature = deleteSignature;
exports.deleteTemplate = deleteTemplate;
exports.deleteTemplateDocument = deleteTemplateDocument;
exports.deleteTemplateRole = deleteTemplateRole;
exports.deleteTemplateTag = deleteTemplateTag;
exports.downloadBlob = downloadBlob;
exports.duplicateTemplate = duplicateTemplate;
exports.envelopeIsActive = envelopeIsActive;
exports.envelopeIsComplete = envelopeIsComplete;
exports.envelopeRecipientAgree = envelopeRecipientAgree;
exports.envelopeRecipientChangeOwner = envelopeRecipientChangeOwner;
exports.envelopeRecipientDecline = envelopeRecipientDecline;
exports.envelopeRecipientPrepare = envelopeRecipientPrepare;
exports.envelopeRecipientSubmit = envelopeRecipientSubmit;
exports.envelopeRecipientUpdateName = envelopeRecipientUpdateName;
exports.fileToDataUrl = fileToDataUrl;
exports.formatFullName = formatFullName;
exports.formatInitials = formatInitials;
exports.formatShortTimeAgo = formatShortTimeAgo;
exports.fullNameToInitials = fullNameToInitials;
exports.getActiveEntitlements = getActiveEntitlements;
exports.getAllTags = getAllTags;
exports.getApiKeys = getApiKeys;
exports.getCountryByCode = getCountryByCode;
exports.getCurrentProfile = getCurrentProfile;
exports.getDocumentDownloadLink = getDocumentDownloadLink;
exports.getDocumentPreviewLink = getDocumentPreviewLink;
exports.getEntitlements = getEntitlements;
exports.getEnvelope = getEnvelope;
exports.getEnvelopeDocument = getEnvelopeDocument;
exports.getEnvelopeDocumentPageDisplayUri = getEnvelopeDocumentPageDisplayUri;
exports.getEnvelopeFile = getEnvelopeFile;
exports.getEnvelopes = getEnvelopes;
exports.getFieldAttachment = getFieldAttachment;
exports.getFieldsForRole = getFieldsForRole;
exports.getGroup = getGroup;
exports.getGroups = getGroups;
exports.getInPersonLink = getInPersonLink;
exports.getKbaStep = getKbaStep;
exports.getMatchingCountry = getMatchingCountry;
exports.getMyUser = getMyUser;
exports.getNextRecipient = getNextRecipient;
exports.getNotifications = getNotifications;
exports.getOrganization = getOrganization;
exports.getOrganizationContacts = getOrganizationContacts;
exports.getOrganizationInvitation = getOrganizationInvitation;
exports.getOrganizationInvitations = getOrganizationInvitations;
exports.getOrganizationMembers = getOrganizationMembers;
exports.getPlusOneCountry = getPlusOneCountry;
exports.getProfiles = getProfiles;
exports.getRGB = getRGB;
exports.getRGBA = getRGBA;
exports.getRLeft = getRLeft;
exports.getRTop = getRTop;
exports.getRValue = getRValue;
exports.getRecipientsWithActions = getRecipientsWithActions;
exports.getRoleColor = getRoleColor;
exports.getSignature = getSignature;
exports.getSignatures = getSignatures;
exports.getStars = getStars;
exports.getTag = getTag;
exports.getTemplate = getTemplate;
exports.getTemplateDocument = getTemplateDocument;
exports.getTemplateDocumentFile = getTemplateDocumentFile;
exports.getTemplateDocumentPageDisplayUri = getTemplateDocumentPageDisplayUri;
exports.getTemplateDocumentThumbnail = getTemplateDocumentThumbnail;
exports.getTemplateDocuments = getTemplateDocuments;
exports.getTemplateTags = getTemplateTags;
exports.getTemplates = getTemplates;
exports.getValidator = getValidator;
exports.getValidators = getValidators;
exports.getWebhooks = getWebhooks;
exports.hasRequiredPermissions = hasRequiredPermissions;
exports.integerSequence = integerSequence;
exports.isAmericanSamoa = isAmericanSamoa;
exports.isCanada = isCanada;
exports.isDominicanRepublic = isDominicanRepublic;
exports.isFrenchGuiana = isFrenchGuiana;
exports.isGuadeloupe = isGuadeloupe;
exports.isMartinique = isMartinique;
exports.isMayotte = isMayotte;
exports.isPuertoRico = isPuertoRico;
exports.isValidEmail = isValidEmail;
exports.isValidPhone = isValidPhone;
exports.isValidRoleName = isValidRoleName;
exports.isValidTag = isValidTag;
exports.nameToRGBA = nameToRGBA;
exports.randomString = randomString;
exports.recipientCanAct = recipientCanAct;
exports.recipientHasAction = recipientHasAction;
exports.refreshToken = refreshToken;
exports.rescale = rescale;
exports.resendInvitation = resendInvitation;
exports.resendOrganizationInvitation = resendOrganizationInvitation;
exports.resendVerification = resendVerification;
exports.resetPassword = resetPassword;
exports.rotateApiKey = rotateApiKey;
exports.sendDelegate = sendDelegate;
exports.setWebhooks = setWebhooks;
exports.sortFields = sortFields;
exports.startSigningSession = startSigningSession;
exports.submitKbaChallengeResponse = submitKbaChallengeResponse;
exports.submitKbaIdentity = submitKbaIdentity;
exports.submitKbaPin = submitKbaPin;
exports.switchProfile = switchProfile;
exports.toggleStar = toggleStar;
exports.updateApiKey = updateApiKey;
exports.updateEnvelope = updateEnvelope;
exports.updateEnvelopeField = updateEnvelopeField;
exports.updateEnvelopeFieldInitials = updateEnvelopeFieldInitials;
exports.updateEnvelopeFieldSignature = updateEnvelopeFieldSignature;
exports.updateField = updateField;
exports.updateGroup = updateGroup;
exports.updateOrganization = updateOrganization;
exports.updateOrganizationContact = updateOrganizationContact;
exports.updateOrganizationInvitation = updateOrganizationInvitation;
exports.updateOrganizationLogo = updateOrganizationLogo;
exports.updateOrganizationMember = updateOrganizationMember;
exports.updateOrganizationThumbnail = updateOrganizationThumbnail;
exports.updateProfile = updateProfile;
exports.updateProfilePhoto = updateProfilePhoto;
exports.updateRecipient = updateRecipient;
exports.updateTemplate = updateTemplate;
exports.updateTemplateRole = updateTemplateRole;
exports.uploadEnvelopeFieldAttachment = uploadEnvelopeFieldAttachment;
exports.userCanAct = userCanAct;
exports.userCanBuildTemplate = userCanBuildTemplate;
exports.userCanCancelEnvelope = userCanCancelEnvelope;
exports.userCanChangeOrgVisibility = userCanChangeOrgVisibility;
exports.userCanCreateOrgTemplate = userCanCreateOrgTemplate;
exports.userCanCreatePersonalTemplate = userCanCreatePersonalTemplate;
exports.userCanCreatePublicTemplate = userCanCreatePublicTemplate;
exports.userCanCreateTemplate = userCanCreateTemplate;
exports.userCanDeleteTemplate = userCanDeleteTemplate;
exports.userCanFinishEnvelope = userCanFinishEnvelope;
exports.userCanMakeTemplatePrivate = userCanMakeTemplatePrivate;
exports.userCanMakeTemplatePublic = userCanMakeTemplatePublic;
exports.userCanMakeTemplateShared = userCanMakeTemplateShared;
exports.userCanPreviewTemplate = userCanPreviewTemplate;
exports.userCanReadTemplate = userCanReadTemplate;
exports.userCanSendTemplate = userCanSendTemplate;
exports.userCanSignNow = userCanSignNow;
exports.userCanUpdateTemplate = userCanUpdateTemplate;
exports.userHasPermissions = userHasPermissions;
exports.userHasSharedTemplate = userHasSharedTemplate;
exports.userIsEnvelopeOwner = userIsEnvelopeOwner;
exports.userIsEnvelopeRecipient = userIsEnvelopeRecipient;
exports.userIsTemplateCreator = userIsTemplateCreator;
exports.verifyEmail = verifyEmail;
exports.verifySigner = verifySigner;
//# sourceMappingURL=index.js.map