UNPKG

keap-client

Version:

A client to work with Infusionsoft/Keap API.

1,542 lines (1,532 loc) 55.4 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/utils/api.ts var Api = class { constructor(apiKey) { this.apiKey = null; this.timeout = null; this.retries = null; this.baseUrl = "https://api.infusionsoft.com/crm/rest/"; this.apiKey = apiKey; } /** * Set the request timeout * @param ms - The number of milliseconds before the request times out */ setRequestTimeout(ms) { this.timeout = ms; } /** * Set the number of retries for the requests * @param retriesCount - The number of retries to make before giving up */ setRetries(retriesCount) { this.retries = retriesCount; } /** * Make a request to the Infusionsoft API * @param method - The request method * @param url - The URL path of the API endpoint * @param data - Data to be sent with the request * @returns The response data * @throws Error if no API key has been set */ makeApiCall(method, url, data) { return __async(this, null, function* () { if (!this.apiKey) { throw new Error("API key is not set"); } const fetchOptions = { method, headers: { "X-Keap-API-Key": this.apiKey, "Content-Type": "application/json" } }; if (method !== "GET" && data) { fetchOptions.body = JSON.stringify(data); } const fetchWithRetry = (url2, options, retries) => __async(this, null, function* () { try { const controller = new AbortController(); const timeoutId = setTimeout( () => controller.abort(), this.timeout || 5e3 ); const response = yield fetch(url2, __spreadProps(__spreadValues({}, options), { signal: controller.signal })); clearTimeout(timeoutId); if (!response.ok) { throw new Error(`HTTP error! status: ${response == null ? void 0 : response.status}`); } return response; } catch (error) { if (retries > 0) { return fetchWithRetry(url2, options, retries - 1); } else { throw error; } } }); try { const response = yield fetchWithRetry( `${this.baseUrl}${url}`, fetchOptions, this.retries || 1 ); return yield response.json(); } catch (error) { if (error instanceof Error) { throw new Error( `Error making ${method} request to ${url}: ${error.message}` ); } } }); } get(url) { return __async(this, null, function* () { return this.makeApiCall("GET", url); }); } post(url, data) { return __async(this, null, function* () { return this.makeApiCall("POST", url, data); }); } put(url, data) { return __async(this, null, function* () { return this.makeApiCall("PUT", url, data); }); } delete(url, data) { return __async(this, null, function* () { return this.makeApiCall("DELETE", url, data); }); } patch(url, data) { return __async(this, null, function* () { return this.makeApiCall("PATCH", url, data); }); } }; // src/utils/paginator.ts var Paginator = class { constructor(api, items, nextUrl, previousUrl, count) { this.nextUrl = null; this.previousUrl = null; this.api = api; this.items = items; this.nextUrl = (nextUrl == null ? void 0 : nextUrl.replace(this.api.baseUrl, "")) || null; this.previousUrl = (previousUrl == null ? void 0 : previousUrl.replace(this.api.baseUrl, "")) || null; this.count = count; } /** * Fetches the next page of results. * @returns A new Paginator instance with the next page of results. */ next() { return __async(this, null, function* () { if (this.nextUrl) { const response = yield this.api.get(this.nextUrl); return Paginator.wrap(this.api, response, this.getItemKey(response)); } return null; }); } /** * Fetches the previous page of results. * @returns A new Paginator instance with the previous page of results. */ previous() { return __async(this, null, function* () { if (this.previousUrl) { const response = yield this.api.get(this.previousUrl); return Paginator.wrap(this.api, response, this.getItemKey(response)); } return null; }); } /** * Creates a new Paginator instance from the API response. * @param api - The API instance. * @param response - The API response. * @param itemKey - The key of the items in the response. * @returns A new Paginator instance. * @example * function handleResponse(response: any): Paginator<ItemsType> { * return Paginator.wrap(api, response, 'items'); * } */ // eslint-disable-next-line @typescript-eslint/no-explicit-any static wrap(api, response, itemKey) { const { next, previous, count } = response; if (!next || !previous || !count || !itemKey) { throw new Error("Invalid API response"); } const items = response[itemKey]; if (!items || !Array.isArray(items)) { throw new Error("Invalid API response"); } return new Paginator(api, items, next, previous, count); } /** * Gets the key of the items in the response. * @param response - The API response. * @returns The key of the items in the response. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any getItemKey(response) { var _a; const keys = Object.keys(response); return ((_a = keys.find((key) => Array.isArray(response[key]))) != null ? _a : keys[0]) || ""; } /** * Gets the items of the current page. * @returns The items of the current page. */ getItems() { return this.items; } /** * Gets the total count of items. * @returns The total count of items. */ getCount() { return this.count; } }; // src/utils/queryParams.ts import { URLSearchParams } from "url"; function createParams(options, keysToValidate) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(options)) { if (value !== void 0 && (keysToValidate ? keysToValidate.includes(key) : true)) { params.append(key, value.toString()); } } return params; } // src/models/Contact.ts var Contacts = class { /** * Creates a new Contact model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } /** * Fetches a list of contacts. * @param parameters - Options for fetching contacts, like page size and page number. * email:string //Optional email address to query on * family_name:string //Optional last name or surname to query on * given_name:string //Optional first name or forename to query on * limit:number //Sets a total of items to return * offset:number //Sets a beginning range of items to return * optional_properties:string[] //Comma-delimited list of Contact properties to include in the response. (Some fields such as lead_source_id, custom_fields, and job_title aren't included, by default.) * order:string //Enum: "id" "date_created" "last_updated" "name" "firstName" "email" //Attribute to order items by * order_direction:string //Enum: "ASCENDING" "DESCENDING" //How to order the data i.e. ascending (A-Z) or descending (Z-A) * since:string //Date to start searching from on LastUpdated ex. 2017-01-01T22:17:59.039Z * until:string //Date to search to on LastUpdated ex. 2017-01-01T22:17:59.039Z * @example * const contacts = await contacts.getContacts({ limit: 5, offset: 10 }); * console.log(contacts); * @returns The list of contacts if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getContacts(parameters) { return __async(this, null, function* () { const params = parameters ? createParams(parameters, [ "email", "limit", "offset", "family_name", "given_name", "optional_properties", "order", "order_direction", "since", "until" ]) : ""; const r = yield this.api.get(`v1/contacts?${params}`); const rObj = r; if (!rObj || !Object.prototype.hasOwnProperty.call(rObj, "contacts")) { return void 0; } if (rObj.contacts === null) { throw new Error("No contacts found"); } const contacts = rObj.contacts.map((c) => { if (c === null) { throw new Error("Contact is null"); } return new Contact(this, c); }); const paginator = Paginator.wrap( this.api, __spreadProps(__spreadValues({}, r), { contacts }), "contacts" ); return paginator; }); } /** * Creates a new contact in Keap. NB: Contact must contain at least one item in email_addresses or phone_numbers and country_code is required if region is specified on the adresses. * @param contactData {IContact} - The data to create a contact with ContactData. * @returns The newly created contact if the API call was successful, undefined otherwise. * @example * const contact = await contacts.createContact(given_name: 'John', * family_name: 'Doe', * email_addresses: [ * { * email: "string@example.com", * field: "EMAIL1" * } * ],); * console.log(contact); * @throws Will throw an error if the API call fails. */ createContact(contactData) { return __async(this, null, function* () { var _a; if (!contactData.email_addresses && !contactData.phone_numbers) { throw new Error( "Contact must contain at least one item in email_addresses or phone_numbers." ); } const addressesWithRegionAndNoCountryCode = (_a = contactData.addresses) == null ? void 0 : _a.filter( (address) => address.region && !address.country_code ); if (addressesWithRegionAndNoCountryCode && addressesWithRegionAndNoCountryCode.length > 0) { throw new Error( "Contact must contain a country code if a region is provided." ); } const r = yield this.api.post("v1/contacts", contactData); if (!r) return void 0; return new Contact(this, r); }); } /** * Updates an existing contact. * @param contactId - The ID of the contact to update. * @param contactData {IContact} - The data to update the contact with. * @returns The updated contact if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const contact = await contacts * .updateContact(123, { * given_name: "Jane", * family_name: "Doe" * }); */ updateContact(contactId, contactData) { return __async(this, null, function* () { const r = yield this.api.patch(`v1/contacts/${contactId}`, contactData); if (!r) return void 0; return new Contact(this, r); }); } /** * Deletes a contact by ID. * @param contactId - The ID of the contact to delete. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const result = await contacts.deleteContact(123); * console.log(result); // true * if (result) { * console.log("Contact deleted successfully"); * }else{ * console.log("Failed to delete contact"); * } */ deleteContact(contactId) { return __async(this, null, function* () { const r = this.api.delete(`v1/contacts/${contactId}`); if (!r) return void 0; return true; }); } /** * Fetches a single contact by ID. * @param contactId - The ID of the contact to fetch. * @returns The contact if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const contact = await contacts.getContact(123); * console.log(contact.given_name); // "Jane" * console.log(contact.family_name); // "Doe" */ getContact(contactId) { return __async(this, null, function* () { const r = yield this.api.get(`v1/contacts/${contactId}`); if (!r) return void 0; return new Contact(this, r); }); } /** * Fetches the contact model. * @returns The contact model if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const contactModel = await contacts.getContactModel(); * console.log(contactModel); */ getContactModel() { return __async(this, null, function* () { const r = yield this.api.get("v1/contacts/model"); if (!r) return void 0; return r; }); } /** * Creates a new custom contact field. * @param customFieldData{CustomField} - The data to create a custom field with. * @returns The newly created custom field if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ createCustomField(customFieldData) { return __async(this, null, function* () { const r = yield this.api.post("v1/contacts/customFields", customFieldData); if (!r) return void 0; return r; }); } /** * Creates a new contact if the contact does not exist, or updates the contact if it does. * @param contactData {IContact} - The data to create or update a contact with. * @returns The newly created or updated contact if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const contact = await contacts.createOrUpdate({ * given_name: "Jane", * family_name: "Doe" * }) * * console.log(contact); // {given_name: "Jane", family_name: "Doe", id: 123} * * * const contact = await contacts.createOrUpdate({ * given_name: "John", * family_name: "Doe" * id: 123 * }) * * console.log(contact); // {given_name: "John", family_name: "Doe", id: 123} */ createOrUpdate(contactData) { return __async(this, null, function* () { const r = yield this.api.put("v1/contacts", contactData); if (!r) return void 0; return new Contact(this, r); }); } /** * Fetches the credit cards associated with a contact. * @param contactId - The ID of the contact to fetch credit cards for. * @returns The credit cards associated with the contact if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getCreditCards(contactId) { return this.api.get(`v1/contacts/${contactId}/creditCards`); } /** * Creates a new credit card for a contact. * @param contactId - The ID of the contact to add the credit card to. * @param creditCardData - The data to create the credit card with. * @returns {Promise<CreditCard>} - The newly created credit card if the API call was successful, undefined otherwise. */ createCreditCard(contactId, creditCardData) { return this.api.post( `v1/contacts/${contactId}/creditCards`, creditCardData ); } /** * Fetches the email addresses associated with a contact. * @param contactId - The ID of the contact to fetch email addresses for. * @returns The email addresses associated with the contact if the API call was successful, undefined otherwise. */ listEmails(contactId, options) { return __async(this, null, function* () { const params = options ? createParams(options, ["email", "limit", "offset"]) : ""; const r = yield this.api.get( `v1/contacts/${contactId}/emails?${params == null ? void 0 : params.toString()}` ); if (!r) return void 0; return Paginator.wrap(this.api, r, "emails"); }); } /** * Creates a new email address for a contact. * @param contactId - The ID of the contact to add the email address to. * @param emailData {EmailRecord} - The data to create the email address with. * @returns The newly created email address if the API call was successful, undefined otherwise. */ createEmail(contactId, emailData) { return this.api.post( `v1/contacts/${contactId}/emails`, emailData ); } /** * Fetches the tags applied to a contact. * @param contactId - The ID of the contact to fetch tags for. * @param options - The options to use when fetching tags. * @returns The tags applied to the contact if the API call was successful, undefined otherwise. */ listAppliedTags(contactId, options) { return __async(this, null, function* () { const params = options ? createParams(options, ["limit", "offset"]) : ""; const r = yield this.api.get( `v1/contacts/${contactId}/tags?${params == null ? void 0 : params.toString()}` ); if (!r) return void 0; return Paginator.wrap(this.api, r, "tags"); }); } /** * Applies a tag to a contact. * @param contactId {number} - The ID of the contact to apply the tag to. * @param tagIds {number[]} - The ID of the tag to apply. * @returns The result of the API call if it was successful, undefined otherwise. */ applyTags(contactId, tagIds) { return this.api.post(`v1/contacts/${contactId}/tags`, { tagIds }); } /** * Removes a tag from a contact. * @param contactId - The ID of the contact to remove the tag from. * @param tagId - The ID of the tag to remove. * @returns The result of the API call if it was successful, undefined otherwise. */ removeTag(contactId, tagId) { return this.api.delete(`v1/contacts/${contactId}/tags/${tagId}`); } /** * Removes multiple tags from a contact. * @param contactId - The ID of the contact to remove the tags from. * @param tagIds - The IDs of the tags to remove. * @param data - Data to be sent with the request. * @returns The result of the API call if it was successful, undefined otherwise. */ removeTags(contactId, tagIds, data) { return this.api.delete( `v1/contacts/${contactId}/tags?tagIds=${tagIds.join(",")}`, data ); } /** * Adds UTM tracking data to a contact. * @param contactId - The ID of the contact to add the UTM data to. * @param utmData - The UTM data to add. * @returns The result of the API call if it was successful, undefined otherwise. */ addUTM(contactId, utmData) { return this.api.post( `v1/contacts/${contactId}/utms`, utmData ); } }; var Contact = class { /** * Creates a new Contact instance from the given data and API client. * @param api - The API client to use for making requests. * @param data - The data to use to populate the Contact instance. */ constructor(contacts, data) { this.ScoreValue = null; this.addresses = null; this.anniversary = null; this.birthday = null; this.company = null; this.company_name = null; this.contact_type = null; this.custom_fields = null; this.date_created = null; this.email_addresses = null; this.email_opted_in = null; this.email_status = null; this.family_name = null; this.fax_numbers = null; this.given_name = null; this.job_title = null; this.last_updated = null; this.lead_source_id = null; this.middle_name = null; this.opt_in_reason = null; this.origin = null; this.owner_id = null; this.phone_numbers = null; this.preferred_locale = null; this.preferred_name = null; this.prefix = null; this.relationships = null; this.social_accounts = null; this.source_type = null; this.spouse_name = null; this.suffix = null; this.tag_ids = null; this.time_zone = null; this.website = null; this.contacts = contacts; Object.assign(this, data); if (!data.id) throw new Error("Contact ID is required"); this.id = data.id; } /** * Updates the contact with the given data. * @param data - The data to update the contact with. * @returns The updated contact if the API call was successful, undefined otherwise. */ update(data) { return __async(this, null, function* () { const r = yield this.contacts.updateContact(this.id, data); if (!r) return void 0; return new Contact(this.contacts, r); }); } /** * Deletes the contact. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ delete() { return __async(this, null, function* () { return this.contacts.deleteContact(this.id); }); } /** * Refreshes the contact data from the API. * @returns The updated contact if the API call was successful, undefined otherwise. */ refresh() { return __async(this, null, function* () { const contact = yield this.contacts.getContact(this.id); Object.assign(this, contact); return contact; }); } /** * Fetches the credit cards associated with this contact. * @returns The credit cards associated with this contact if the API call was successful, undefined otherwise. */ getCreditCards() { return this.contacts.getCreditCards(this.id); } /** * Creates a new credit card for this contact. * @param data - The data to create the credit card with. * @returns The newly created credit card if the API call was successful, undefined otherwise. */ addCreditCard(data) { return this.contacts.createCreditCard(this.id, data); } /** * Fetches the email addresses associated with this contact. * @param options - The options to use when fetching email addresses. * @returns The email addresses associated with this contact if the API call was successful, undefined otherwise. */ getEmails(options) { return this.contacts.listEmails(this.id, options); } /** * Adds a new email address to this contact. * @param data - The data to create the email address with. * @returns The newly created email address if the API call was successful, undefined otherwise. */ addEmail(data) { return this.contacts.createEmail(this.id, data); } /** * Fetches the tags applied to this contact. * @param options - The options to use when fetching tags. * @returns The tags applied to this contact if the API call was successful, undefined otherwise. */ getAppliedTags(options) { return this.contacts.listAppliedTags(this.id, options); } /** * Applies the given tags to this contact. * @param tagIds - The IDs of the tags to apply. * @returns The result of the API call if it was successful, undefined otherwise. */ applyTags(tagIds) { return this.contacts.applyTags(this.id, tagIds); } /** * Removes the given tag from this contact. * @param tagId - The ID of the tag to remove. * @returns The result of the API call if it was successful, undefined otherwise. */ removeTag(tagId) { return this.contacts.removeTag(this.id, tagId); } /** * Removes multiple tags from this contact. * @param tagIds - The IDs of the tags to remove. * @param data - Data to be sent with the request. * @returns The result of the API call if it was successful, undefined otherwise. */ removeTags(tagIds, data) { return this.contacts.removeTags(this.id, tagIds, data); } /** * Adds UTM tracking data to this contact. * @param utmData - The UTM data to add. * @returns The result of the API call if it was successful, undefined otherwise. */ addUTM(utmData) { return this.contacts.addUTM(this.id, utmData); } }; // src/models/AccountInfo.ts var AccountInfo = class { /** * Creates a new AccountInfo model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } /** * Fetches the current account information. * @returns The account information if the API call was successful, undefined otherwise. */ getAccountInfo() { return __async(this, null, function* () { const r = yield this.api.get("v1/account/profile"); if (!r) return void 0; return r; }); } /** * Updates the current account information. * @returns The account information if the API call was successful, undefined otherwise. */ updateAccountInfo(data) { return __async(this, null, function* () { const r = yield this.api.put("v1/account/profile", data); if (!r) return void 0; return r; }); } }; // src/models/Opportunities.ts var Opportunities = class { /** * Creates a model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } /** * Fetches a list of opportunities. * @param parameters - Options for fetching opportunities, like page size and page number. * @example * const opportunities = await opportunities.getopportunities({ limit: 5, offset: 10 }); * // parameters * //limit:number //Sets a total of items to return * //offset:number //Sets a beginning range of items to return * //order:"next_action" | "opportunity_name" | "contact_name" | "date_created", //Attribute to order items by * //search_term:string //Returns opportunities that match any of the contact's given_name, family_name, company_name, and email_addresses (searches EMAIL1 only) fields as well as opportunity_title * //stage_id:number <int64> //Returns opportunities for the provided stage id * //user_id:number <int64> //Returns opportunities for the provided user id * console.log(opportunities); * @returns The list of opportunities if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getOpportunities(parameters) { return __async(this, null, function* () { let queryParams; if (parameters) { queryParams = createParams(parameters, [ "user_id", "stage_id", "limit", "offset", "order", "search_term" ]); } const r = yield this.api.get(`v1/opportinities?${queryParams}`); const rObj = r; if (!rObj || !Object.prototype.hasOwnProperty.call(rObj, "opportunities")) { return void 0; } if (rObj.opportunities === null) { throw new Error("No opportunities found"); } const opportunities = rObj.opportunities.map((opp) => { if (opp === null) { throw new Error("Opportunities is null"); } return new Opportunity(this, opp); }); return Paginator.wrap( this.api, __spreadProps(__spreadValues({}, r), { opportunities }), "opportunities" ); }); } /** * Creates a new opportunity. * @param data - The data to create the opportunity with. * @returns The newly created opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. * @example * const opportunity = await opportunities.createOpportunity({ * contact_id: 1, * opportunity_title: "New Opportunity", * stage_id: 1 * }); * console.log(opportunity); */ createOpportunity(data) { return __async(this, null, function* () { const r = yield this.api.post("v1/opportunities", data); if (!r) return void 0; return new Opportunity(this, r); }); } /** * Replaces an existing opportunity. * @param data - The data to replace the opportunity with. * @returns The replaced opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ replaceOpportunity(data) { return __async(this, null, function* () { const r = yield this.api.put(`v1/opportunities/${data.id}`, data); if (!r) return void 0; return new Opportunity(this, r); }); } /** * Retrieves an opportunity by ID. * @param id - The ID of the opportunity to fetch. * @returns The opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getOpportunity(id) { return __async(this, null, function* () { const r = yield this.api.get(`v1/opportunities/${id}`); if (!r) return void 0; return new Opportunity(this, r); }); } /** * Deletes an opportunity by ID. * @param id - The ID of the opportunity to delete. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteOpportunity(id) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/opportunities/${id}`); if (!r) return void 0; return true; }); } /** * Updates an existing opportunity. * @param data - The data to update the opportunity with. * @returns The updated opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ updateOpportunity(data) { return __async(this, null, function* () { const r = yield this.api.patch(`v1/opportunities/${data.id}`, data); if (!r) return void 0; return new Opportunity(this, r); }); } }; var Opportunity = class { /** * Creates a new Opportunity instance from the given data and Opportunities model. * @param opps - The Opportunities model to use for making requests. * @param data - The data to use to populate the Opportunity instance. * @throws Will throw an error if any of the required fields are missing. */ constructor(opps, data) { if (!data.contact || !data.stage || !data.opportunity_title) { throw new Error("Invalid data"); } this.opportunities = opps; this.contact = data.contact; this.opportunity_title = data.opportunity_title; this.stage = data.stage; Object.assign(this, data); } /** * Deletes this opportunity. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails or if this opportunity does not have an ID. */ delete() { return __async(this, null, function* () { if (!this.id) throw new Error("Invalid ID"); const r = yield this.opportunities.deleteOpportunity(this.id); if (!r) return void 0; return true; }); } /** * Updates this opportunity. * @param data - The data to update this opportunity with. * @returns The updated opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails or if this opportunity does not have an ID. */ update(data) { return __async(this, null, function* () { if (!this.id) throw new Error("Invalid ID"); const r = yield this.opportunities.updateOpportunity(data); if (!r) return void 0; return new Opportunity(this.opportunities, r); }); } /** * Refreshes the opportunity data from the API. * @returns The updated opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails or if this opportunity does not have an ID. */ refresh() { return __async(this, null, function* () { if (!this.id) throw new Error("Invalid ID"); const r = yield this.opportunities.getOpportunity(this.id); if (!r) return void 0; return new Opportunity(this.opportunities, r); }); } /** * Replaces this opportunity. * @param data - The data to replace this opportunity with. * @returns The replaced opportunity if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails or if this opportunity does not have an ID. */ replace(data) { return __async(this, null, function* () { if (!this.id) throw new Error("Invalid ID"); const r = yield this.opportunities.replaceOpportunity(data); if (!r) return void 0; return new Opportunity(this.opportunities, r); }); } }; // src/models/Products.ts var Products = class { /** * Creates a model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } /** * Fetches a list of products. * @param options - Options for fetching products, like page size and page number. * @returns The list of products if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getProducts(options) { return __async(this, null, function* () { let queryParams; if (options) { queryParams = createParams(options, ["active", "limit", "offset"]); } const r = yield this.api.get(`v1/products?${queryParams}`); const rObj = r; if (!rObj || !Object.prototype.hasOwnProperty.call(rObj, "products")) { return void 0; } if (!rObj.products) { return void 0; } const products = rObj.products.map((product) => { if (product === null) { throw new Error("Product is null"); } return new Product(this, product); }); return Paginator.wrap( this.api, __spreadProps(__spreadValues({}, r), { products }), "products" ); }); } /** * Creates a new product. * @param data - The data to create a product with. * @returns The newly created product if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ createProduct(data) { return __async(this, null, function* () { const r = yield this.api.post("v1/products", data); if (!r) { return void 0; } return new Product(this, r); }); } /** * Fetches a single product by ID. * @param productId - The ID of the product to fetch. * @returns The product if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getProduct(productId) { return __async(this, null, function* () { const r = yield this.api.get(`v1/products/${productId}`); if (!r) { return void 0; } return new Product(this, r); }); } /** * Updates a product. * @param data - The data to update the product with. * @returns The updated product if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ updateProduct(data) { return __async(this, null, function* () { const r = yield this.api.patch(`v1/products/${data.id}`, data); if (!r) { return void 0; } return new Product(this, r); }); } /** * Deletes a product. * @param productId - The ID of the product to delete. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteProduct(productId) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/products/${productId}`); if (!r) { return void 0; } return true; }); } /** * Uploads a product image. * @param productId - The ID of the product to upload the image to. * @param fileData - The base64 encoded image data. * @param fileName - The name of the image. * @param checksum - The checksum of the image. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ uploadProductImage(productId, fileData, fileName, checksum) { return __async(this, null, function* () { const r = yield this.api.post(`v1/products/${productId}/image`, { checksum, file_data: fileData, file_name: fileName }); if (!r) { return void 0; } return true; }); } /** * Deletes the product image associated with the given product id. * @param productId - The ID of the product to delete the image from. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteProductImage(productId) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/products/${productId}/image`); if (!r) { return void 0; } return true; }); } /** * Creates a new subscription plan associated with the given product id. * @param productId - The ID of the product to create the subscription plan for. * @param data - The data to create the subscription plan with. * @returns The newly created subscription plan if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ createASubscriptionPlan(productId, data) { return __async(this, null, function* () { const r = yield this.api.post( `v1/products/${productId}/subscriptions`, data ); if (!r) { return void 0; } return r; }); } /** * Fetches a single subscription plan associated with the given product id. * @param productId - The ID of the product to fetch the subscription plan from. * @param subscriptionId - The ID of the subscription plan to fetch. * @returns The subscription plan if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getASubscriptionPlan(productId, subscriptionId) { return __async(this, null, function* () { const r = yield this.api.get( `v1/products/${productId}/subscriptions/${subscriptionId}` ); if (!r) { return void 0; } return r; }); } /** * Deletes a subscription plan associated with the given product id. * @param productId - The ID of the product to delete the subscription plan from. * @param subscriptionId - The ID of the subscription plan to delete. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteASubscriptionPlan(productId, subscriptionId) { return __async(this, null, function* () { const r = yield this.api.delete( `v1/products/${productId}/subscriptions/${subscriptionId}` ); if (!r) { return void 0; } return true; }); } }; var Product = class { /** * Creates a new Product instance from the given data and Products model. * @param products - The Products model to use for making requests. * @param data - The data to use to populate the Product instance. * @throws Will throw an error if any of the required fields are missing. */ constructor(products, data) { if (!data || !data.id || !data.product_name) { throw new Error("Invalid product data"); } this.id = data.id; this.product_name = data.product_name; Object.assign(this, data); this.products = products; } /** * Updates this product with the given data. * @param data - The data to update this product with. * @returns The updated product if the API call was successful, undefined otherwise. */ update(data) { Object.assign(this, data); return this.products.updateProduct(this); } /** * Deletes this product. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ delete() { return this.products.deleteProduct(this.id); } /** * Refreshes this product from the API. * @returns The updated product if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ refresh() { return this.products.getProduct(this.id); } /** * Creates a new subscription plan for this product. * @param data - The data to create the subscription plan with. * @returns The newly created subscription plan if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ createSubscriptionPlan(data) { return this.products.createASubscriptionPlan(this.id, data); } /** * Retrieves a subscription plan associated with this product. * @param subscriptionId - The ID of the subscription plan to retrieve. * @returns The subscription plan if the API call was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ getSubscriptionPlan(subscriptionId) { return this.products.getASubscriptionPlan(this.id, subscriptionId); } /** * Deletes a subscription plan associated with this product. * @param subscriptionId - The ID of the subscription plan to delete. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteSubscriptionPlan(subscriptionId) { return this.products.deleteASubscriptionPlan(this.id, subscriptionId); } /** * Uploads a product image associated with this product. * @param fileData - The base64 encoded image data. * @param fileName - The name of the image. * @param checksum - The checksum of the image. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ uploadImage(fileData, fileName, checksum) { return this.products.uploadProductImage( this.id, fileData, fileName, checksum ); } /** * Deletes the product image associated with this product. * @returns The result of the API call if it was successful, undefined otherwise. * @throws Will throw an error if the API call fails. */ deleteImage() { return this.products.deleteProductImage(this.id); } }; // src/models/Ecommerce.ts var Ecommerce = class { /** * Creates a new ecommerce model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } get Orders() { return new Order(this.api); } get Subscriptions() { return new Subscription(this.api); } get Transactions() { return new Transaction(this.api); } }; var Order = class { constructor(api) { this.api = api; } getOrders(params) { return __async(this, null, function* () { const queryParams = params ? createParams(params, [ "limit", "offset", "since", "until", "paid", "order", "contact_id" ]) : ""; const r = yield this.api.get(`v1/orders?${queryParams.toString()}`); if (!r) return void 0; return Paginator.wrap(this.api, r, "orders"); }); } createOrder(options, data) { return __async(this, null, function* () { const r = yield this.api.post("v1/orders", __spreadValues(__spreadValues({}, options), data)); if (!r) return void 0; return r; }); } getOrder(id) { return __async(this, null, function* () { const r = yield this.api.get(`v1/orders/${id}`); if (!r) return void 0; return r; }); } deleteOrder(id) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/orders/${id}`); if (!r) return void 0; return true; }); } createItem(orderId, data) { return __async(this, null, function* () { const r = yield this.api.post(`v1/orders/${orderId}/items`, data); if (!r) return void 0; return r; }); } deleteItem(orderId, itemId) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/orders/${orderId}/items/${itemId}`); if (!r) return void 0; return true; }); } getOrderPayments(orderId) { return __async(this, null, function* () { const r = yield this.api.get(`v1/orders/${orderId}/payments`); if (!r) return void 0; return r; }); } createOrderPayment(orderId, data) { return __async(this, null, function* () { const r = yield this.api.post(`v1/orders/${orderId}/payments`, data); if (!r) return void 0; return r; }); } getOrderTransactions(orderId, options) { return __async(this, null, function* () { const queryParams = options ? createParams(options, [ "contact_id", "limit", "offset", "since", "until" ]) : ""; const r = yield this.api.get( `v1/orders/${orderId}/transactions?${queryParams.toString()}` ); if (!r) return void 0; return Paginator.wrap(this.api, r, "transactions"); }); } }; var Subscription = class { constructor(api) { this.api = api; } getSubscriptions() { return __async(this, null, function* () { const r = yield this.api.get("v1/subscriptions"); if (!r) return void 0; return r; }); } createSubscription(data) { return __async(this, null, function* () { const r = yield this.api.post("v1/subscriptions", data); if (!r) return void 0; return r; }); } }; var Transaction = class { constructor(api) { this.api = api; } getTransactions(options) { return __async(this, null, function* () { const queryParams = options ? createParams(options, [ "contact_id", "limit", "offset", "since", "until" ]) : ""; const r = yield this.api.get(`v1/transactions?${queryParams.toString()}`); if (!r) return void 0; return Paginator.wrap(this.api, r, "transactions"); }); } getTransaction(id) { return __async(this, null, function* () { const r = yield this.api.get(`v1/transactions/${id}`); if (!r) return void 0; return r; }); } }; // src/models/File.ts var Files = class { /** * Creates a new Files model. * @param api - The API client to use for making requests. */ constructor(api) { this.api = api; } /** * Lists files with optional filtering options. * @param options - The filtering options. * @returns A promise that resolves to a list of files with pagination. */ listFiles(options) { return __async(this, null, function* () { const params = options ? createParams(options, [ "contact_id", "name", "permission", "type", "viewable", "limit", "offset" ]) : ""; const r = yield this.api.get(`v1/files?${params == null ? void 0 : params.toString()}`); if (!r) return void 0; return Paginator.wrap(this.api, r, "files"); }); } /** * Uploads a new file. * @param file - The file upload request data. * @returns A promise that resolves to the uploaded file response. */ uploadFile(file) { return __async(this, null, function* () { const r = yield this.api.post("v1/files", file); if (!r) return void 0; return r; }); } /** * Retrieves a file by ID. * @param id - The ID of the file to retrieve. * @returns A promise that resolves to the file response. */ getFile(id) { return __async(this, null, function* () { const r = yield this.api.get(`v1/files/${id}`); if (!r) return void 0; return r; }); } /** * Replaces an existing file by ID. * @param id - The ID of the file to replace. * @param file - The file upload request data. * @returns A promise that resolves to the replaced file response. */ replaceFile(id, file) { return __async(this, null, function* () { const r = yield this.api.put(`v1/files/${id}`, file); if (!r) return void 0; return r; }); } /** * Deletes a file by ID. * @param id - The ID of the file to delete. * @returns A promise that resolves to true if the file was deleted, otherwise undefined. */ deleteFile(id) { return __async(this, null, function* () { const r = yield this.api.delete(`v1/files/${id}`); if (!r) return void 0; return true; }); } }; // src/models/Email.ts var Emails = class { /** * Creates a new Email model. *