keap-client
Version:
A client to work with Infusionsoft/Keap API.
1,554 lines (1,544 loc) • 62.3 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
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/index.ts
var src_exports = {};
__export(src_exports, {
KeapClient: () => KeapClient
});
module.exports = __toCommonJS(src_exports);
// 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 {
return Promise.reject(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
var import_url = require("url");
function createParams(options, keysToValidate) {
const params = new import_url.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 with optional filtering.
* @param parameters - Options for fetching contacts.
* @param parameters.email - Optional email address to query on.
* @param parameters.family_name - Optional last name or surname to query on.
* @param parameters.given_name - Optional first name or forename to query on.
* @param parameters.limit - Sets a total of items to return.
* @param parameters.offset - Sets a beginning range of items to return.
* @param parameters.optional_properties - List of Contact properties to include in the response.
* @param parameters.order - Attribute to order items by.
* @param parameters.order_direction - How to order the data (ascending or descending).
* @param parameters.since - Date to start searching from on LastUpdated (ex. 2017-01-01T22:17:59.039Z).
* @param parameters.until - Date to search to on LastUpdated (ex. 2017-01-01T22:17:59.039Z).
* @example
* const contacts = await contactsInstance.getContacts({
* limit: 5,
* offset: 10,
* order: "date_created",
* order_direction: "DESCENDING"
* });
* @returns A paginator containing the list of contacts.
*/
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"
]).toString() : "";
const response = yield this.api.get(`v1/contacts?${params}`);
const responseObj = response;
if (!responseObj || !Object.prototype.hasOwnProperty.call(responseObj, "contacts")) {
throw new Error("Invalid response format: missing contacts property");
}
if (responseObj.contacts === null) {
throw new Error("No contacts found in response");
}
const contacts = responseObj.contacts.map((contact) => {
if (contact === null) {
throw new Error("Contact data is null");
}
return new Contact(this, contact);
});
return Paginator.wrap(this.api, __spreadProps(__spreadValues({}, response), { contacts }), "contacts");
});
}
/**
* Creates a new contact in Keap.
* Note: Contact must contain at least one item in email_addresses or phone_numbers,
* and country_code is required if region is specified on the addresses.
* @param contactData - The data to create a contact with.
* @returns The newly created contact.
* @example
* const contact = await contactsInstance.createContact({
* given_name: 'John',
* family_name: 'Doe',
* email_addresses: [
* {
* email: "john.doe@example.com",
* field: "EMAIL1"
* }
* ]
* });
*/
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 response = yield this.api.post("v1/contacts", contactData);
return new Contact(this, response);
});
}
/**
* 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.
* @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);
return new Contact(this, r);
});
}
/**
* Deletes a contact by ID.
* @param contactId - The ID of the contact to delete.
* @returns True if the contact was successfully deleted.
* @example
* const result = await contactsInstance.deleteContact(123);
* if (result) {
* console.log("Contact deleted successfully");
* }
*/
deleteContact(contactId) {
return __async(this, null, function* () {
yield this.api.delete(`v1/contacts/${contactId}`);
return true;
});
}
/**
* Fetches a single contact by ID.
* @param contactId - The ID of the contact to fetch.
* @returns The contact.
* @example
* const contact = await contactsInstance.getContact(123);
* console.log(contact.given_name); // "Jane"
* console.log(contact.family_name); // "Doe"
*/
getContact(contactId) {
return __async(this, null, function* () {
const response = yield this.api.get(`v1/contacts/${contactId}`);
return new Contact(this, response);
});
}
/**
* Fetches the contact model schema.
* @returns The contact model.
* @example
* const contactModel = await contactsInstance.getContactModel();
* console.log(contactModel);
*/
getContactModel() {
return __async(this, null, function* () {
const response = yield this.api.get("v1/contacts/model");
return response;
});
}
/**
* Creates a new custom contact field.
* @param customFieldData - The data to create a custom field with.
* @returns The newly created custom field.
* @example
* const customField = await contactsInstance.createCustomField({
* field_type: "Text",
* label: "Custom Field Name"
* });
*/
createCustomField(customFieldData) {
return __async(this, null, function* () {
const response = yield this.api.post(
"v1/contacts/customFields",
customFieldData
);
return response;
});
}
/**
* Creates a new contact if the contact does not exist, or updates the contact if it does.
* @param contactData - The data to create or update a contact with.
* @returns The newly created or updated contact.
* @example
* const contact = await contactsInstance.createOrUpdate({
* given_name: "Jane",
* family_name: "Doe"
* });
* console.log(contact); // {given_name: "Jane", family_name: "Doe", id: 123}
*/
createOrUpdate(contactData) {
return __async(this, null, function* () {
const response = yield this.api.put("v1/contacts", contactData);
return new Contact(this, response);
});
}
/**
* 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.
*/
getCreditCards(contactId) {
return __async(this, null, function* () {
const response = yield this.api.get(`v1/contacts/${contactId}/creditCards`);
return response;
});
}
/**
* 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 The newly created credit card.
*/
createCreditCard(contactId, creditCardData) {
return __async(this, null, function* () {
const response = yield this.api.post(
`v1/contacts/${contactId}/creditCards`,
creditCardData
);
return response;
});
}
/**
* 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.
*/
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()}`
);
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.
*/
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.
*/
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()}`
);
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
update(data) {
return __async(this, null, function* () {
const r = yield this.contacts.updateContact(this.id, data);
return new Contact(this.contacts, r);
});
}
/**
* Deletes the contact.
* @returns The result of the API call if it was successful.
* @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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
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.
*/
getAccountInfo() {
return __async(this, null, function* () {
return yield this.api.get("v1/account/profile");
});
}
/**
* Updates the current account information.
* @returns The account information if the API call was successful.
*/
updateAccountInfo(data) {
return __async(this, null, function* () {
return yield this.api.put("v1/account/profile", data);
});
}
};
// 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 with optional filtering.
* @param parameters - Options for fetching opportunities, like page size and page number.
* @param parameters.limit - Sets a total of items to return
* @param parameters.offset - Sets a beginning range of items to return
* @param parameters.order - Attribute to order items by
* @param parameters.search_term - Returns opportunities that match contact or opportunity fields
* @param parameters.stage_id - Returns opportunities for the provided stage id
* @param parameters.user_id - Returns opportunities for the provided user id
* @example
* const opportunities = await opportunitiesInstance.getOpportunities({
* limit: 5,
* offset: 10,
* order: "date_created"
* });
* @returns A paginator containing the list of opportunities.
*/
getOpportunities(parameters) {
return __async(this, null, function* () {
let queryParams = "";
if (parameters) {
queryParams = createParams(parameters, [
"user_id",
"stage_id",
"limit",
"offset",
"order",
"search_term"
]).toString();
}
const response = yield this.api.get(`v1/opportunities?${queryParams}`);
const responseObj = response;
if (!responseObj || !Object.prototype.hasOwnProperty.call(responseObj, "opportunities")) {
throw new Error(
"Invalid response format: missing opportunities property"
);
}
if (responseObj.opportunities === null) {
throw new Error("No opportunities found");
}
const opportunities = responseObj.opportunities.map((opp) => {
if (opp === null) {
throw new Error("Opportunity data is null");
}
return new Opportunity(this, opp);
});
return Paginator.wrap(
this.api,
__spreadProps(__spreadValues({}, response), {
opportunities
}),
"opportunities"
);
});
}
/**
* Creates a new opportunity.
* @param data - The data to create the opportunity with.
* @returns The newly created opportunity.
* @example
* const opportunity = await opportunitiesInstance.createOpportunity({
* contact_id: 1,
* opportunity_title: "New Opportunity",
* stage_id: 1
* });
*/
createOpportunity(data) {
return __async(this, null, function* () {
const response = yield this.api.post("v1/opportunities", data);
return new Opportunity(this, response);
});
}
/**
* Replaces an existing opportunity.
* @param data - The data to replace the opportunity with.
* @returns The replaced opportunity.
* @example
* const updatedOpportunity = await opportunitiesInstance.replaceOpportunity({
* id: 123,
* opportunity_title: "Updated Title",
* stage_id: 2
* });
*/
replaceOpportunity(data) {
return __async(this, null, function* () {
if (!data.id) {
throw new Error("Opportunity ID is required for replacement");
}
const response = yield this.api.put(`v1/opportunities/${data.id}`, data);
return new Opportunity(this, response);
});
}
/**
* Retrieves an opportunity by ID.
* @param id - The ID of the opportunity to fetch.
* @returns The opportunity.
* @example
* const opportunity = await opportunitiesInstance.getOpportunity(123);
*/
getOpportunity(id) {
return __async(this, null, function* () {
const response = yield this.api.get(`v1/opportunities/${id}`);
return new Opportunity(this, response);
});
}
/**
* Deletes an opportunity by ID.
* @param id - The ID of the opportunity to delete.
* @returns True if the opportunity was successfully deleted.
* @example
* const deleted = await opportunitiesInstance.deleteOpportunity(123);
* if (deleted) console.log("Opportunity deleted successfully");
*/
deleteOpportunity(id) {
return __async(this, null, function* () {
yield this.api.delete(`v1/opportunities/${id}`);
return true;
});
}
/**
* Updates an existing opportunity.
* @param data - The data to update the opportunity with.
* @returns The updated opportunity.
* @example
* const updatedOpportunity = await opportunitiesInstance.updateOpportunity({
* id: 123,
* opportunity_title: "Updated Title"
* });
*/
updateOpportunity(data) {
return __async(this, null, function* () {
if (!data.id) {
throw new Error("Opportunity ID is required for update");
}
const response = yield this.api.patch(`v1/opportunities/${data.id}`, data);
return new Opportunity(this, response);
});
}
};
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 with optional filtering.
* @param options - Options for fetching products, like page size and page number.
* @param options.active - Filter by active status.
* @param options.limit - Maximum number of products to return.
* @param options.offset - Number of products to skip.
* @returns A paginator containing the list of products.
* @example
* const products = await productsInstance.getProducts({
* active: true,
* limit: 10
* });
*/
getProducts(options) {
return __async(this, null, function* () {
let queryParams = "";
if (options) {
queryParams = createParams(options, [
"active",
"limit",
"offset"
]).toString();
}
const response = yield this.api.get(`v1/products?${queryParams}`);
const responseObj = response;
if (!responseObj || !Object.prototype.hasOwnProperty.call(responseObj, "products")) {
throw new Error("Invalid response format: missing products property");
}
if (!responseObj.products) {
throw new Error("No products found in response");
}
const products = responseObj.products.map((product) => {
if (product === null) {
throw new Error("Product data is null");
}
return new Product(this, product);
});
return Paginator.wrap(
this.api,
__spreadProps(__spreadValues({}, response), {
products
}),
"products"
);
});
}
/**
* Creates a new product.
* @param data - The data to create a product with.
* @returns The newly created product.
* @example
* const product = await productsInstance.createProduct({
* product_name: "New Product",
* product_short_description: "A great product",
* product_price: 99.99
* });
*/
createProduct(data) {
return __async(this, null, function* () {
const response = yield this.api.post("v1/products", data);
return new Product(this, response);
});
}
/**
* Fetches a single product by ID.
* @param productId - The ID of the product to fetch.
* @returns The product.
* @example
* const product = await productsInstance.getProduct(123);
*/
getProduct(productId) {
return __async(this, null, function* () {
const response = yield this.api.get(`v1/products/${productId}`);
return new Product(this, response);
});
}
/**
* Updates a product.
* @param data - The data to update the product with.
* @returns The updated product.
* @example
* const updatedProduct = await productsInstance.updateProduct({
* id: 123,
* product_name: "Updated Product Name"
* });
*/
updateProduct(data) {
return __async(this, null, function* () {
if (!data.id) {
throw new Error("Product ID is required for update");
}
const response = yield this.api.patch(`v1/products/${data.id}`, data);
return new Product(this, response);
});
}
/**
* 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;
}
/**
* Fetches a list of orders with optional filtering.
* @param params - Optional parameters for filtering orders.
* @returns A paginator containing the list of orders.
* @example
* const orders = await ecommerce.Orders.getOrders({
* limit: 10,
* paid: true
* });
*/
getOrders(params) {
return __async(this, null, function* () {
const queryParams = params ? createParams(params, [
"limit",
"offset",
"since",
"until",
"paid",
"order",
"contact_id"
]).toString() : "";
const response = yield this.api.get(`v1/orders?${queryParams}`);
return Paginator.wrap(this.api, response, "orders");
});
}
/**
* Creates a new order.
* @param options - Required order configuration.
* @param data - Additional order data.
* @returns The newly created order.
* @example
* const order = await ecommerce.Orders.createOrder(
* {
* contact_id: 123,
* order_date: "2023-01-01T00:00:00Z",
* order_title: "New Order",
* order_type: "Online"
* },
* orderData
* );
*/
createOrder(options, data) {
return __async(this, null, function* () {
const response = yield this.api.post("v1/orders", __spreadValues(__spreadValues({}, options), data));
return response;
});
}
/**
* Retrieves a specific order by ID.
* @param id - The ID of the order to retrieve.
* @returns The order.
* @example
* const order = await ecommerce.Orders.getOrder(123);
*/
getOrder(id) {
return __async(this, null, function* () {
const response = yield this.api.get(`v1/orders/${id}`);
return response;
});
}
/**
* Deletes an order by ID.
* @param id - The ID of the order to delete.
* @returns True if the order was successfully deleted.
* @example
* const deleted = await ecommerce.Orders.deleteOrder(123);
* if (deleted) console.log("Order deleted successfully");
*/
deleteOrder(id) {
return __async(this, null, function* () {
yield this.api.delete(`v1/orders/${id}`);
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");
return Paginator.wrap(this.api, r, "subscriptions");
});
}
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 paginator containing the list of files.
* @example
* const files = await filesInstance.listFiles({
* contact_id: 123,
* viewable: "PUBLIC"
* });
*/
listFiles(options) {
return __async(this, null, function* () {
const params = options ? createParams(options, [
"contact_id",
"name",
"permission",
"type",
"viewable",
"limit",
"offset"
]).toString() : "";
const response = yield this.api.get(`v1/files?${params}`);
return Paginator.wrap(this.api, response, "files");
});
}
/**
* Uploads a new file.
* @param file - The file upload request data.
* @returns The uploaded file response.
* @example
* const uploadedFile = await filesInstance.uploadFile({
* file_data: base64Data,
* file_name: "document.pdf",
* contact_id: 123
* });
*/
uploadFile(file) {
return __async(this, null, function* () {
const response = yield this.api.post("v1/files", file);
return response;
});
}
/**
* Retrieves a file by ID.
* @param id - The ID of