@intelligence-cloud/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2838 @@
1
+ 'use strict';
2
+
3
+ // src/generated/spec.ts
4
+ var OPERATIONS = { "login": { "method": "POST", "path": "/auth/login", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v", "status": "v" } }, "summary": "Sign in" }, "refresh": { "method": "POST", "path": "/auth/refresh", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v" } }, "summary": "Renew the access token" }, "logout": { "method": "POST", "path": "/auth/logout", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "message": "v" } }, "summary": "Sign out" }, "getResellerBranding": { "method": "GET", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read reseller branding" }, "updateResellerBranding": { "method": "PATCH", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update reseller branding" }, "getResellerSmtpSettings": { "method": "GET", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read outbound email (SMTP) settings" }, "saveResellerSmtpSettings": { "method": "PATCH", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Save outbound email (SMTP) settings" }, "deleteResellerSmtpSettings": { "method": "DELETE", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove outbound email (SMTP) settings" }, "listCompanies": { "method": "GET", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "summary": "List customer companies" }, "createCompany": { "method": "POST", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } }, "invited_user": { "o": { "id": "v", "email": "v", "display_name": "v", "status": "v", "role": "v", "invited_at": "v", "invite_expires_at": "v" } } } }, "summary": "Create a customer company" }, "getCompaniesMfaSummary": { "method": "GET", "path": "/resellers/{resellerId}/companies/mfa", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "total_active": "v", "with_mfa_required": "v", "companies_mfa_default": "v", "mfa_available": "v" } } } }, "summary": "Read the MFA default for new companies" }, "getCompany": { "method": "GET", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a company" }, "updateCompany": { "method": "PATCH", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a company" }, "deactivateCompany": { "method": "POST", "path": "/companies/{companyId}/deactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a company" }, "reactivateCompany": { "method": "POST", "path": "/companies/{companyId}/reactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a company" }, "getCompanySecuritySettings": { "method": "GET", "path": "/companies/{companyId}/security-settings", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "min_password_length": "v", "require_uppercase": "v", "require_numbers": "v", "require_special_chars": "v", "password_expiry_days": "v", "session_timeout_minutes": "v", "allowed_ip_ranges": { "a": "v" }, "password_policy_source": "v", "password_policy_inherited_fields": { "a": "v" } } } } }, "summary": "Read a company's security settings" }, "getCompanyBranding": { "method": "GET", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read company branding overrides" }, "updateCompanyBranding": { "method": "PATCH", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update company branding overrides" }, "listCompanyDomains": { "method": "GET", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } } }, "summary": "List claimed domains" }, "claimCompanyDomain": { "method": "POST", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } }, "summary": "Claim a domain" }, "removeCompanyDomain": { "method": "DELETE", "path": "/companies/{companyId}/domains/{domainId}", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove a domain claim" }, "listDomainVerifications": { "method": "GET", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } } }, "summary": "List verification attempts" }, "verifyDomain": { "method": "POST", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } }, "summary": "Check the TXT record now" }, "getIdentityProvider": { "method": "GET", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Read the identity provider connection" }, "connectIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Connect an OpenID Connect provider" }, "disconnectIdentityProvider": { "method": "DELETE", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Disconnect the identity provider" }, "testIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider/test", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "reachable": "v", "checks": { "a": { "o": { "name": "v", "outcome": "v", "detail": "v" } } } } } } }, "summary": "Test the identity provider connection" }, "listProducts": { "method": "GET", "path": "/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List products" }, "listCompanyProducts": { "method": "GET", "path": "/companies/{companyId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "Company products" }, "listUserProducts": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "A user's products" }, "enableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/enable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product on for a user" }, "disableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/disable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product off for a user" }, "listVerticals": { "method": "GET", "path": "/verticals", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "key": "v", "name": "v", "description": "v", "is_active": "v", "display_order": "v" } } } } }, "summary": "List industries" }, "listCompanyLocations": { "method": "GET", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's locations" }, "createLocation": { "method": "POST", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a location" }, "getLocation": { "method": "GET", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a location" }, "updateLocation": { "method": "PATCH", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a location" }, "deactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/deactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a location" }, "reactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/reactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a location" }, "listUserGroups": { "method": "GET", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's groups" }, "createUserGroup": { "method": "POST", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a group" }, "getUserGroup": { "method": "GET", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a group with its members" }, "updateUserGroup": { "method": "PATCH", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Rename a group or set its members" }, "deleteUserGroup": { "method": "DELETE", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "force", "in": "query", "type": "boolean" }], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete a group" }, "getUserGroupMembership": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "A user's groups at a location" }, "setUserGroupMembership": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "Set a user's groups at a location" }, "listConnectorTypes": { "method": "GET", "path": "/connector-types", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List connector types" }, "testConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/test", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v" } } } }, "summary": "Dry-run a connector" }, "listLocationConnectors": { "method": "GET", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "error", "deactivating", "inactive"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's connectors" }, "createConnector": { "method": "POST", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Create a connector" }, "getConnector": { "method": "GET", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read a connector" }, "updateConnector": { "method": "PATCH", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Update a connector" }, "deactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/deactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Stop a connector" }, "reactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/reactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Restart a connector" }, "listCompanyConnectors": { "method": "GET", "path": "/companies/{companyId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "error", "deactivating", "inactive"] }, { "name": "type", "in": "query", "type": "string", "enum": ["netsapiens"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "errors": { "a": { "o": { "id": "v", "name": "v", "type": "v", "location_name": "v", "status_message": "v" } } } } }, "summary": "List a company's connectors" }, "listAlertRules": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [{ "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's alert rules" }, "createAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create an alert rule" }, "getAlertRule": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read an alert rule" }, "updateAlertRule": { "method": "PATCH", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update an alert rule" }, "deleteAlertRule": { "method": "DELETE", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete an alert rule" }, "duplicateAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules/{ruleId}/duplicate", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Copy an alert rule" }, "getFirstAlertConfig": { "method": "GET", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Read monitored numbers and the alert webhook" }, "saveFirstAlertConfig": { "method": "PUT", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Set monitored numbers and the alert webhook" }, "testFirstAlertWebhook": { "method": "POST", "path": "/locations/{locationId}/first-alert/config/test-webhook", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v", "status_code": "v" } } } }, "summary": "Test the alert webhook" }, "getAlertNotificationPreferences": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/first-alert/notification-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Read a user's alert email and digest" }, "setAlertEmailPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/email-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert email" }, "setAlertDigestPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/digest-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert digest" }, "getInsightsHubSetup": { "method": "GET", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Read Insights Hub setup" }, "saveInsightsHubSetup": { "method": "POST", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Save Insights Hub setup" }, "updateInsightsHubSetup": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Update Insights Hub setup" }, "getInsightsHubConfig": { "method": "GET", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Read Insights Hub coverage" }, "updateInsightsHubConfig": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Set Insights Hub coverage" }, "getUserInsightsHubAccess": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/insights-hub/access", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "enabled": "v", "group_name": "v" } } } } } }, "summary": "Check a user's Insights Hub access" }, "listCompanyUsers": { "method": "GET", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "role", "in": "query", "type": "string", "enum": ["customer_admin", "frontline_user"] }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's users" }, "createCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": ["Idempotency-Key"], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a user" }, "getCompanyUser": { "method": "GET", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a user" }, "updateCompanyUser": { "method": "PATCH", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a user, role or locations" }, "deactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/deactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a user" }, "reactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a user" }, "resendInvitation": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/resend-invitation", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "invite_expires_at": "v", "message": "v" } } } } } }, "summary": "Resend the invitation email" }, "resetPassword": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reset-password", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "message": "v" } } } } } }, "summary": "Send a password reset email" }, "getUserNumberMappings": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Read a user's numbers" }, "setUserNumberMappings": { "method": "PUT", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Set a user's numbers" }, "listLocationUsers": { "method": "GET", "path": "/locations/{locationId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's users with products and groups" }, "getLocationUser": { "method": "GET", "path": "/locations/{locationId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } } }, "summary": "Read a user at a location" }, "getUserAfterCallSettings": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Read a user's After Call settings" }, "updateUserAfterCallSettings": { "method": "PATCH", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Update a user's After Call settings" }, "getMe": { "method": "GET", "path": "/me", "tag": "Account", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "user_type": "v", "role": "v", "status": "v", "scopes": { "a": "v" }, "reseller_id": "v", "company_id": "v", "location_ids": { "a": "v" }, "enabled_products": { "a": "v" }, "mfa_available": "v" } } } }, "summary": "Who is signed in" }, "listVisibleLocations": { "method": "GET", "path": "/locations", "tag": "Account", "role": "frontline_user", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "Locations this login can see" }, "listCalls": { "method": "GET", "path": "/calls", "tag": "Calls", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "status", "in": "query", "type": "string", "enum": ["completed", "missed", "voicemail", "failed", "cancelled"] }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "has_open_tasks", "in": "query", "type": "string", "enum": ["true"] }, { "name": "multi_leg", "in": "query", "type": "boolean" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "search", "in": "query", "type": "string", "minLength": 2 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total_calls": "v", "completed_calls": "v", "missed_calls": "v", "total_duration": "v", "tasks_done": "v", "pending": "v", "total_tasks": "v" } }, "calls": { "a": { "o": { "id": "v", "location_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "status": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "top_highlight": "v", "highlights": { "a": "v" }, "duration": "v", "leg_count": "v", "task_count": "v", "completed_task_count": "v" } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List calls" }, "getCall": { "method": "GET", "path": "/calls/{callId}", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "call_outcome": "v", "duration": "v", "leg_count": "v", "platform": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "analysis": { "o": { "summary": { "o": { "text": "v", "key_points": { "a": "v" }, "action_items": { "a": "v" } } }, "sentiment": { "o": { "overall": "v" } }, "topics": { "a": { "o": { "name": "v" } } } } }, "vcon": { "o": { "recording_url": "v", "recording_url_expires_at": "v", "recording_mime_type": "v" } }, "tasks": { "a": { "o": { "id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v" } } }, "task_count": "v", "has_more_tasks": "v" } } } }, "summary": "Read a call" }, "getCallTranscript": { "method": "GET", "path": "/calls/{callId}/transcript", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "transcript": { "a": { "o": { "time": "v", "speaker": "v", "name": "v", "text": "v" } } } } } } }, "summary": "Read a call's transcript" }, "listAlerts": { "method": "GET", "path": "/alerts", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "keyword", "in": "query", "type": "string" }, { "name": "topic", "in": "query", "type": "string" }, { "name": "numbers", "in": "query", "type": "array", "maxItems": 25, "items": { "type": "string", "pattern": "^[A-Za-z0-9@#]+$" } }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total": "v" } }, "alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List alerts" }, "getAlertsDashboard": { "method": "GET", "path": "/alerts/dashboard", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "kpis": { "o": { "new_alerts": "v", "monitored": "v", "alert_rate": "v" } }, "top_triggered": { "a": { "o": { "keyword": "v", "count": "v" } } }, "recent_alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } } } }, "summary": "Alert totals" }, "listTasks": { "method": "GET", "path": "/tasks", "tag": "Tasks", "role": "frontline_user", "query": [{ "name": "status", "in": "query", "type": "string", "enum": ["pending", "in_progress", "done", "overdue", "open"] }, { "name": "today_start", "in": "query", "type": "string", "format": "date-time" }, { "name": "call_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "task_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "due_on", "in": "query", "type": "string", "format": "date" }, { "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "call_id": "v", "company_id": "v", "location_id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v", "completed_at": "v", "created_at": "v", "updated_at": "v" } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } }, "summary": { "o": { "total": "v", "done": "v", "in_progress": "v", "pending": "v", "overdue": "v" } } } }, "summary": "List tasks" }, "getInsightsDashboard": { "method": "GET", "path": "/insights/dashboard", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "start", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "end", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "trending_limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 10 }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "stats": { "o": { "total_calls": "v", "answered_calls": "v", "unanswered_calls": "v" } }, "trending_topics": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v", "previous_call_count": "v", "percentage_change": "v", "trend_data": { "a": { "o": { "day": "v", "current": "v", "previous": "v" } } } } } }, "topic_call_volumes": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v" } } } } } } }, "summary": "Insights Hub dashboard" }, "listTopicCalls": { "method": "GET", "path": "/insights/topics/{slug}/calls", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["positive", "neutral", "negative"] }, { "name": "outcome", "in": "query", "type": "string", "enum": ["completed", "missed", "pending"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": ["slug"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "date": "v", "caller_name": "v", "summary": "v", "phone_number": "v", "sentiment": "v", "sentiment_label": "v", "outcome": "v" } } }, "meta": { "o": { "total": "v", "has_more": "v", "next_cursor": "v" } } } }, "summary": "Calls for one topic" }, "getAfterCallWebhook": { "method": "GET", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read the After Call webhook" }, "saveAfterCallWebhook": { "method": "PUT", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Set the After Call webhook" }, "testAfterCallWebhook": { "method": "POST", "path": "/locations/{locationId}/after-call/automation/test", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "success": "v", "http_status": "v", "response_time_ms": "v" } } } }, "summary": "Send a test After Call event" } };
5
+ var WEBHOOK_SHAPES = { "afterCallSummary": { "o": { "version": "v", "type": "v", "is_test": "v", "location_id": "v", "timestamp": "v", "call": { "o": { "id": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "duration_seconds": "v", "call_date": "v", "platform": "v" } }, "summary": { "o": { "text": "v", "sentiment": "v", "key_points": { "a": "v" }, "action_items": { "a": "v" } } }, "location": { "o": { "id": "v", "company_id": "v", "connector_id": "v" } } } }};
6
+
7
+ // src/errors.ts
8
+ var IntelligenceCloudError = class extends Error {
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = new.target.name;
12
+ }
13
+ };
14
+ var ApiError = class extends IntelligenceCloudError {
15
+ status;
16
+ code;
17
+ requestId;
18
+ operationId;
19
+ /** The server's error text, when it sent one. May contain customer data: don't log it. */
20
+ serverMessage;
21
+ constructor(status, code, message, extra = {}) {
22
+ super(message, extra.cause !== void 0 ? { cause: extra.cause } : void 0);
23
+ this.status = status;
24
+ this.code = code;
25
+ this.requestId = extra.requestId ?? null;
26
+ this.operationId = extra.operationId ?? null;
27
+ this.serverMessage = extra.serverMessage ?? null;
28
+ }
29
+ };
30
+ function apiErrorText(status, code, requestId, hint) {
31
+ let text = `HTTP ${status}${code ? ` ${code}` : ""}`;
32
+ if (hint) text += `: ${hint}`;
33
+ if (requestId) text += ` (request_id ${requestId})`;
34
+ return text;
35
+ }
36
+ var AuthError = class extends ApiError {
37
+ };
38
+ var MfaRequiredError = class extends AuthError {
39
+ constructor() {
40
+ super(200, "mfa_required", "Integration users need MFA off for their company. API keys arrive in December 2026.");
41
+ }
42
+ };
43
+ var PasswordExpiredError = class extends AuthError {
44
+ constructor() {
45
+ super(200, "password_expired", "The password has expired. Change it in the app, then sign in again.");
46
+ }
47
+ };
48
+ var NotFoundError = class extends ApiError {
49
+ };
50
+ var ConflictError = class extends ApiError {
51
+ /** On an extension conflict: the requested extensions the API refused. Empty otherwise. */
52
+ extensions;
53
+ constructor(status, code, message, extra = {}) {
54
+ super(status, code, message, extra);
55
+ this.extensions = extra.extensions ?? [];
56
+ }
57
+ };
58
+ var ValidationError = class extends ApiError {
59
+ };
60
+ var RateLimitError = class extends ApiError {
61
+ retryAfter;
62
+ constructor(status, code, message, retryAfter, extra = {}) {
63
+ super(status, code, message, extra);
64
+ this.retryAfter = retryAfter;
65
+ }
66
+ };
67
+ var FilterError = class extends IntelligenceCloudError {
68
+ };
69
+ var ConnectorError = class extends IntelligenceCloudError {
70
+ stateReason;
71
+ status;
72
+ connector;
73
+ constructor(message, stateReason, status, connector) {
74
+ super(message);
75
+ this.stateReason = stateReason;
76
+ this.status = status;
77
+ this.connector = connector;
78
+ }
79
+ };
80
+ var FrontlineRequiredError = class extends IntelligenceCloudError {
81
+ role;
82
+ constructor(role) {
83
+ super(
84
+ `This login has role "${role ?? "unknown"}". Conversation data endpoints return empty lists to admin logins: sign in with a frontline integration user.`
85
+ );
86
+ this.role = role;
87
+ }
88
+ };
89
+ var WorkflowError = class extends IntelligenceCloudError {
90
+ step;
91
+ partial;
92
+ constructor(step2, partial, cause) {
93
+ const why = cause instanceof Error ? cause.message : String(cause);
94
+ super(`Workflow stopped at "${step2}": ${why}`, { cause });
95
+ this.step = step2;
96
+ this.partial = partial;
97
+ }
98
+ };
99
+ var ExtensionMappingError = class extends IntelligenceCloudError {
100
+ userId;
101
+ constructor(userId, cause) {
102
+ super(
103
+ `User ${userId ?? "unknown"}: numbers not mapped (${cause instanceof Error ? cause.message : String(cause)}). Number mappings need an active connector and extensions no other location monitors.`,
104
+ { cause }
105
+ );
106
+ this.userId = userId;
107
+ }
108
+ };
109
+ var WebhookPayloadError = class extends IntelligenceCloudError {
110
+ };
111
+ var PayloadTooLargeError = class extends WebhookPayloadError {
112
+ };
113
+ var EXTENSION_CONFLICT_MESSAGE = "Extension is already monitored at another location.";
114
+
115
+ // src/filters.ts
116
+ var RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i;
117
+ var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
118
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
119
+ var MAX_LOCATION_IDS = 50;
120
+ var MAX_NUMBERS = 25;
121
+ function camel(s) {
122
+ return s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
123
+ }
124
+ function toRfc3339(value, name) {
125
+ let d;
126
+ if (value instanceof Date) {
127
+ d = value;
128
+ } else if (typeof value === "string") {
129
+ if (DATE_ONLY.test(value)) {
130
+ throw new FilterError(`"${name}" needs a full timestamp, e.g. ${value}T00:00:00Z. A date alone is refused.`);
131
+ }
132
+ if (!RFC3339.test(value)) {
133
+ throw new FilterError(`"${name}" must be a full RFC 3339 timestamp with an offset, e.g. 2026-11-01T00:00:00Z.`);
134
+ }
135
+ d = new Date(value);
136
+ } else {
137
+ throw new FilterError(`"${name}" must be a Date or an RFC 3339 timestamp string.`);
138
+ }
139
+ if (Number.isNaN(d.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
140
+ return d.toISOString().replace(/\.000Z$/, "Z");
141
+ }
142
+ function toDateOnly(value, name) {
143
+ if (value instanceof Date) {
144
+ if (Number.isNaN(value.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
145
+ const y = value.getFullYear();
146
+ const m = String(value.getMonth() + 1).padStart(2, "0");
147
+ const d = String(value.getDate()).padStart(2, "0");
148
+ return `${y}-${m}-${d}`;
149
+ }
150
+ if (typeof value === "string" && DATE_ONLY.test(value)) return value;
151
+ throw new FilterError(`"${name}" must be a calendar date (YYYY-MM-DD) or a Date.`);
152
+ }
153
+ function uuid(value, name) {
154
+ if (typeof value !== "string" || !UUID.test(value)) throw new FilterError(`"${name}" must be a UUID.`);
155
+ return value.toLowerCase();
156
+ }
157
+ function digitsOnly(value) {
158
+ return value.replace(/\D/g, "");
159
+ }
160
+ function alertNumber(value) {
161
+ const d = digitsOnly(value);
162
+ return d.length === 11 && d.startsWith("1") ? d.slice(1) : d;
163
+ }
164
+ function scalar(rule, value, name) {
165
+ if (rule.type === "boolean") {
166
+ if (typeof value !== "boolean") throw new FilterError(`"${name}" must be true or false.`);
167
+ return value ? "true" : "false";
168
+ }
169
+ if (rule.type === "integer" || rule.type === "number") {
170
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new FilterError(`"${name}" must be an integer.`);
171
+ if (rule.minimum !== void 0 && value < rule.minimum) throw new FilterError(`"${name}" must be at least ${rule.minimum}.`);
172
+ if (rule.maximum !== void 0 && value > rule.maximum) throw new FilterError(`"${name}" must be at most ${rule.maximum}.`);
173
+ return String(value);
174
+ }
175
+ if (rule.format === "date-time") return toRfc3339(value, name);
176
+ if (rule.format === "date") return toDateOnly(value, name);
177
+ if (rule.format === "uuid") return uuid(value, name);
178
+ if (rule.enum && rule.enum.length === 1 && rule.enum[0] === "true") {
179
+ if (value === true || value === "true") return "true";
180
+ throw new FilterError(`"${name}" only supports true. Leave it out to include every record.`);
181
+ }
182
+ if (typeof value !== "string") throw new FilterError(`"${name}" must be a string.`);
183
+ if (rule.enum && !rule.enum.includes(value)) {
184
+ throw new FilterError(`"${name}" must be one of: ${rule.enum.join(", ")}.`);
185
+ }
186
+ if (rule.minLength !== void 0 && value.trim().length < rule.minLength) {
187
+ throw new FilterError(`"${name}" needs at least ${rule.minLength} characters; shorter values are ignored by the API.`);
188
+ }
189
+ return value;
190
+ }
191
+ function list(rule, value, name) {
192
+ const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : null;
193
+ if (!raw) throw new FilterError(`"${name}" must be a list.`);
194
+ let entries = raw.map((v) => typeof v === "string" ? v.trim() : v);
195
+ if (rule.name === "numbers") {
196
+ entries = entries.map((v) => {
197
+ if (typeof v !== "string" && typeof v !== "number") throw new FilterError(`"${name}" entries must be strings.`);
198
+ const d = alertNumber(String(v));
199
+ if (!d) throw new FilterError(`"${name}" entries must contain digits.`);
200
+ return d;
201
+ });
202
+ } else if (rule.items?.format === "uuid") {
203
+ entries = entries.map((v) => uuid(v, name));
204
+ } else {
205
+ entries = entries.map((v) => {
206
+ if (typeof v !== "string" || v === "") throw new FilterError(`"${name}" entries must be non-empty strings.`);
207
+ if (rule.items?.enum && !rule.items.enum.includes(v)) {
208
+ throw new FilterError(`"${name}" entries must be one of: ${rule.items.enum.join(", ")}.`);
209
+ }
210
+ return v;
211
+ });
212
+ }
213
+ const unique = [...new Set(entries)];
214
+ if (unique.length === 0) throw new FilterError(`"${name}" must not be empty.`);
215
+ const max = rule.name === "location_id" ? Math.min(MAX_LOCATION_IDS, rule.maxItems ?? MAX_LOCATION_IDS) : rule.maxItems;
216
+ if (max !== void 0 && unique.length > max) {
217
+ throw new FilterError(`"${name}" takes at most ${max} entries per request.`);
218
+ }
219
+ return unique.join(",");
220
+ }
221
+ function buildQuery(operationId, rules, options) {
222
+ const byKey = /* @__PURE__ */ new Map();
223
+ for (const r of rules) {
224
+ byKey.set(r.name, r);
225
+ byKey.set(camel(r.name), r);
226
+ }
227
+ const out = {};
228
+ for (const [key, value] of Object.entries(options ?? {})) {
229
+ if (value === void 0 || value === null) continue;
230
+ const rule = byKey.get(key);
231
+ if (!rule) {
232
+ const supported = rules.map((r) => camel(r.name)).join(", ") || "none";
233
+ throw new FilterError(`"${key}" is not a filter of ${operationId}. Supported: ${supported}.`);
234
+ }
235
+ if (rule.name in out) throw new FilterError(`"${key}" was given twice.`);
236
+ out[rule.name] = rule.type === "array" ? list(rule, value, key) : scalar(rule, value, key);
237
+ }
238
+ for (const r of rules) {
239
+ if (r.required && !(r.name in out)) throw new FilterError(`"${camel(r.name)}" is required for ${operationId}.`);
240
+ }
241
+ return out;
242
+ }
243
+
244
+ // src/projection.ts
245
+ function project(value, shape) {
246
+ if (shape === null || shape === void 0 || shape === "*") return value;
247
+ if (value === null || value === void 0) return value;
248
+ if (shape === "v") {
249
+ return typeof value === "object" ? void 0 : value;
250
+ }
251
+ if ("a" in shape) {
252
+ if (!Array.isArray(value)) return void 0;
253
+ return value.map((v) => project(v, shape.a));
254
+ }
255
+ if (typeof value !== "object" || Array.isArray(value)) {
256
+ return void 0;
257
+ }
258
+ const out = {};
259
+ for (const [k, sub] of Object.entries(shape.o)) {
260
+ if (Object.prototype.hasOwnProperty.call(value, k)) {
261
+ const v = project(value[k], sub);
262
+ if (v !== void 0) out[k] = v;
263
+ }
264
+ }
265
+ return out;
266
+ }
267
+ var RECORDING_FIELDS = ["recording_url", "recording_url_expires_at", "recording_mime_type"];
268
+ var ALWAYS_REMOVED_FIELDS = /* @__PURE__ */ new Set(["invitation_link"]);
269
+ function removed(key) {
270
+ return ALWAYS_REMOVED_FIELDS.has(key) || key.endsWith("_ref");
271
+ }
272
+ function scrub(value) {
273
+ if (Array.isArray(value)) return value.map(scrub);
274
+ if (value && typeof value === "object") {
275
+ const out = {};
276
+ for (const [k, v] of Object.entries(value)) {
277
+ if (!removed(k)) out[k] = scrub(v);
278
+ }
279
+ return out;
280
+ }
281
+ return value;
282
+ }
283
+ function projectKeepingUnknown(value, shape) {
284
+ if (value === null || value === void 0) return value;
285
+ if (shape === null || shape === void 0 || shape === "*" || shape === "v") return scrub(value);
286
+ if ("a" in shape) {
287
+ if (!Array.isArray(value)) return scrub(value);
288
+ return value.map((v) => projectKeepingUnknown(v, shape.a));
289
+ }
290
+ if (typeof value !== "object" || Array.isArray(value)) return scrub(value);
291
+ const out = {};
292
+ for (const [k, v] of Object.entries(value)) {
293
+ if (removed(k)) continue;
294
+ const sub = shape.o[k];
295
+ out[k] = sub === void 0 ? scrub(v) : projectKeepingUnknown(v, sub);
296
+ }
297
+ return out;
298
+ }
299
+
300
+ // src/tokens.ts
301
+ var MemoryTokenStore = class {
302
+ tokens = null;
303
+ get() {
304
+ return this.tokens;
305
+ }
306
+ set(tokens) {
307
+ this.tokens = tokens;
308
+ }
309
+ };
310
+ var FileTokenStore = class {
311
+ constructor(path, options = {}) {
312
+ this.path = path;
313
+ this.staleMs = options.staleMs ?? 3e4;
314
+ this.retryMs = options.retryMs ?? 50;
315
+ }
316
+ path;
317
+ staleMs;
318
+ retryMs;
319
+ async get() {
320
+ const fs = await import('fs/promises');
321
+ let text;
322
+ try {
323
+ text = await fs.readFile(this.path, "utf8");
324
+ } catch (err) {
325
+ if (err.code === "ENOENT") return null;
326
+ throw err;
327
+ }
328
+ try {
329
+ const t = JSON.parse(text);
330
+ if (!t || typeof t.accessToken !== "string" || typeof t.refreshToken !== "string") return null;
331
+ return { accessToken: t.accessToken, refreshToken: t.refreshToken, expiresAt: Number(t.expiresAt) || 0 };
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+ async set(tokens) {
337
+ const fs = await import('fs/promises');
338
+ if (tokens === null) {
339
+ await fs.rm(this.path, { force: true });
340
+ return;
341
+ }
342
+ const tmp = `${this.path}.${process.pid}.${Date.now()}.tmp`;
343
+ await fs.writeFile(tmp, JSON.stringify(tokens), { mode: 384 });
344
+ await fs.rename(tmp, this.path);
345
+ }
346
+ async withLock(fn) {
347
+ const fs = await import('fs/promises');
348
+ const lock = `${this.path}.lock`;
349
+ for (; ; ) {
350
+ try {
351
+ const h = await fs.open(lock, "wx", 384);
352
+ await h.close();
353
+ break;
354
+ } catch (err) {
355
+ if (err.code !== "EEXIST") throw err;
356
+ try {
357
+ const st = await fs.stat(lock);
358
+ if (Date.now() - st.mtimeMs > this.staleMs) {
359
+ await fs.rm(lock, { force: true });
360
+ continue;
361
+ }
362
+ } catch {
363
+ continue;
364
+ }
365
+ await new Promise((r) => setTimeout(r, this.retryMs));
366
+ }
367
+ }
368
+ try {
369
+ return await fn();
370
+ } finally {
371
+ await fs.rm(lock, { force: true });
372
+ }
373
+ }
374
+ };
375
+
376
+ // src/core.ts
377
+ var DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1";
378
+ var SDK_VERSION = "0.1.0";
379
+ var SUPPRESS_ERROR_TEXT = /* @__PURE__ */ new Set(["testConnector", "testAfterCallWebhook", "testFirstAlertWebhook"]);
380
+ var NUMBER_MAPPING_OPS = /* @__PURE__ */ new Set(["setUserNumberMappings", "updateUserAfterCallSettings"]);
381
+ var LOGIN_RATE_LIMIT_WAIT_S = 60;
382
+ var RENEW_MARGIN_MS = 3e4;
383
+ var MAX_RETRY_AFTER_MS = 6e4;
384
+ var ALWAYS_PROJECT = /* @__PURE__ */ new Set([
385
+ "getMe",
386
+ "login",
387
+ "refresh",
388
+ "listCalls",
389
+ "getCall",
390
+ "getCallTranscript",
391
+ "listAlerts",
392
+ "getAlertsDashboard",
393
+ "listTasks",
394
+ "getInsightsDashboard",
395
+ "listTopicCalls"
396
+ ]);
397
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
398
+ function checkBaseUrl(baseUrl) {
399
+ let u;
400
+ try {
401
+ u = new URL(baseUrl);
402
+ } catch {
403
+ throw new FilterError(`baseUrl "${baseUrl}" is not a URL.`);
404
+ }
405
+ if (u.protocol === "https:") return baseUrl;
406
+ if (u.protocol === "http:" && LOCAL_HOSTS.has(u.hostname)) return baseUrl;
407
+ throw new FilterError("baseUrl must use https:// (plain http is accepted for localhost only).");
408
+ }
409
+ var Core = class {
410
+ baseUrl;
411
+ email;
412
+ password;
413
+ store;
414
+ timeoutMs;
415
+ maxRetries;
416
+ loginWaitS;
417
+ keepUnknown;
418
+ userAgent;
419
+ fetchImpl;
420
+ sleep;
421
+ random;
422
+ now;
423
+ renewing = null;
424
+ constructor(opts) {
425
+ if (!opts || !opts.email || !opts.password) {
426
+ throw new TypeError("email and password are required (a dedicated integration user with MFA off).");
427
+ }
428
+ this.baseUrl = checkBaseUrl(opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
429
+ this.email = opts.email;
430
+ this.password = opts.password;
431
+ this.store = opts.tokenStore ?? new MemoryTokenStore();
432
+ this.timeoutMs = (opts.timeout ?? 30) * 1e3;
433
+ this.maxRetries = opts.maxRetries ?? 3;
434
+ this.loginWaitS = opts.loginRateLimitWait ?? LOGIN_RATE_LIMIT_WAIT_S;
435
+ this.keepUnknown = opts.keepUnknownFields ?? false;
436
+ this.userAgent = opts.userAgent ?? `intelligence-cloud-sdk-typescript/${SDK_VERSION}`;
437
+ const f = opts.fetch ?? globalThis.fetch;
438
+ if (!f) throw new TypeError("No fetch implementation found. Use Node 20+ or pass `fetch`.");
439
+ this.fetchImpl = f;
440
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
441
+ this.random = opts.random ?? Math.random;
442
+ this.now = opts.now ?? Date.now;
443
+ }
444
+ // -------------------------------------------------------------- public core
445
+ /** Call one documented operation and return its projected response body. */
446
+ async call(operationId, pathArgs, opts = {}) {
447
+ const op = OPERATIONS[operationId];
448
+ const query = buildQuery(operationId, op.query, opts.query ?? {});
449
+ const url = this.url(op, pathArgs, query);
450
+ const res = await this.send(op.method, url, {
451
+ body: op.hasBody ? opts.body ?? {} : void 0,
452
+ headers: opts.headers,
453
+ idempotencyKey: opts.idempotencyKey,
454
+ auth: true,
455
+ operationId
456
+ });
457
+ if (res.status < 200 || res.status >= 300) throw this.toError(res, operationId, op.hasBody ? opts.body : void 0);
458
+ if (res.status === 204 || res.text === "") return void 0;
459
+ if (!this.keepUnknown || ALWAYS_PROJECT.has(operationId)) return project(res.json, op.response);
460
+ const out = projectKeepingUnknown(res.json, op.response);
461
+ if (operationId === "getCall" && out?.data?.vcon && typeof out.data.vcon === "object") {
462
+ const v = out.data.vcon;
463
+ out.data.vcon = Object.fromEntries(RECORDING_FIELDS.filter((k) => k in v).map((k) => [k, v[k]]));
464
+ }
465
+ return out;
466
+ }
467
+ /** Call a paged list operation and return one page. */
468
+ async page(operationId, pathArgs, opts = {}) {
469
+ const body = await this.call(operationId, pathArgs, opts);
470
+ const p = extractPage(body);
471
+ return { items: p.items.map(unwrapRow), nextCursor: p.nextCursor, hasMore: p.hasMore, total: p.total, raw: body };
472
+ }
473
+ /** Iterate every row of a paged list operation, following cursors with limit=100. */
474
+ async *iterate(operationId, pathArgs, query = {}) {
475
+ const { maxItems, ...rest } = query;
476
+ const q = { limit: 100, ...rest };
477
+ let yielded = 0;
478
+ const seen = /* @__PURE__ */ new Set();
479
+ for (; ; ) {
480
+ const body = await this.call(operationId, pathArgs, { query: q });
481
+ const page = extractPage(body);
482
+ for (const item of page.items) {
483
+ if (maxItems !== void 0 && yielded >= maxItems) return;
484
+ yielded++;
485
+ yield unwrapRow(item);
486
+ }
487
+ if (!page.hasMore || !page.nextCursor || seen.has(page.nextCursor)) return;
488
+ if (maxItems !== void 0 && yielded >= maxItems) return;
489
+ seen.add(page.nextCursor);
490
+ q.cursor = page.nextCursor;
491
+ }
492
+ }
493
+ /** Ends ALL sessions of this user (web app too) and forgets the tokens. */
494
+ async logout() {
495
+ const t = await this.store.get();
496
+ if (t && t.accessToken) {
497
+ const res = await this.send("POST", `${this.baseUrl}/auth/logout`, { auth: true, operationId: "logout", body: {} });
498
+ if (res.status >= 300 && res.status !== 401) throw this.toError(res, "logout");
499
+ }
500
+ await this.store.set(null);
501
+ }
502
+ /** Forget the tokens held by this client. Does not sign out on the server. */
503
+ async close() {
504
+ await this.store.set(null);
505
+ }
506
+ // -------------------------------------------------------------- auth
507
+ async accessToken() {
508
+ const t = await this.store.get();
509
+ if (!t || !t.accessToken) return (await this.renew(null)).accessToken;
510
+ if (t.expiresAt - this.now() < RENEW_MARGIN_MS) return (await this.renew(t.accessToken)).accessToken;
511
+ return t.accessToken;
512
+ }
513
+ /**
514
+ * Get fresh tokens. Serialised: concurrent callers share one refresh or login.
515
+ * `failed` is the access token that was rejected (null = none yet); if another caller has
516
+ * already replaced it, the new tokens are reused.
517
+ */
518
+ renew(failed) {
519
+ if (this.renewing) return this.renewing;
520
+ const work = async () => {
521
+ const cur = await this.store.get();
522
+ if (cur && cur.accessToken && cur.accessToken !== failed && cur.expiresAt - this.now() >= RENEW_MARGIN_MS) {
523
+ return cur;
524
+ }
525
+ if (cur && cur.refreshToken) {
526
+ const spent = cur.refreshToken;
527
+ await this.store.set({ ...cur, refreshToken: "" });
528
+ let fresh;
529
+ try {
530
+ fresh = await this.refreshWith(spent);
531
+ } catch (err) {
532
+ if (err instanceof RateLimitError) await this.store.set(cur);
533
+ throw err;
534
+ }
535
+ if (fresh) return fresh;
536
+ }
537
+ return await this.login();
538
+ };
539
+ this.renewing = (async () => {
540
+ try {
541
+ return this.store.withLock ? await this.store.withLock(work) : await work();
542
+ } finally {
543
+ this.renewing = null;
544
+ }
545
+ })();
546
+ return this.renewing;
547
+ }
548
+ /**
549
+ * Swap a refresh token for a new pair. On 429 the same token is tried again after a wait (it was
550
+ * not used); a sign-in is never attempted for a rate-limited refresh. Returns null when the token
551
+ * is refused (spent, expired or revoked), so the caller signs in again.
552
+ */
553
+ async refreshWith(refreshToken) {
554
+ for (let attempt = 0; ; attempt++) {
555
+ const res = await this.send("POST", `${this.baseUrl}/auth/refresh`, {
556
+ body: { refresh_token: refreshToken },
557
+ auth: false,
558
+ operationId: "refresh",
559
+ noRetry: true
560
+ });
561
+ if (res.status === 429) {
562
+ const ra = retryAfterMs(res.headers);
563
+ if (attempt >= this.maxRetries || ra !== null && ra > MAX_RETRY_AFTER_MS) throw this.toError(res, "refresh");
564
+ await this.sleep(this.backoff(attempt + 1, ra));
565
+ continue;
566
+ }
567
+ if (res.status !== 200) return null;
568
+ return this.saveTokens(res.json);
569
+ }
570
+ }
571
+ async login() {
572
+ let waited = false;
573
+ for (; ; ) {
574
+ const res = await this.send("POST", `${this.baseUrl}/auth/login`, {
575
+ body: { email: this.email, password: this.password },
576
+ auth: false,
577
+ operationId: "login",
578
+ noRetry: true
579
+ });
580
+ if (res.status === 429 && !waited && this.loginWaitS > 0) {
581
+ waited = true;
582
+ await this.sleep(this.loginWaitS * 1e3);
583
+ continue;
584
+ }
585
+ if (res.status !== 200) throw this.toError(res, "login");
586
+ const body = res.json;
587
+ if (body && body.status === "mfa_required") throw new MfaRequiredError();
588
+ if (body && body.password_expired === true) throw new PasswordExpiredError();
589
+ return this.saveTokens(body);
590
+ }
591
+ }
592
+ async saveTokens(body) {
593
+ const b = body ?? {};
594
+ if (typeof b.access_token !== "string" || typeof b.refresh_token !== "string") {
595
+ throw new AuthError(200, null, "Sign-in returned no tokens.");
596
+ }
597
+ const tokens = {
598
+ accessToken: b.access_token,
599
+ refreshToken: b.refresh_token,
600
+ expiresAt: this.now() + (typeof b.expires_in === "number" ? b.expires_in : 900) * 1e3
601
+ };
602
+ await this.store.set(tokens);
603
+ return tokens;
604
+ }
605
+ // -------------------------------------------------------------- transport
606
+ url(op, pathArgs, query) {
607
+ let i = 0;
608
+ const path = op.path.replace(/\{([^}]+)\}/g, (_, name) => {
609
+ const v = pathArgs[i++];
610
+ if (typeof v !== "string" || v.trim() === "") {
611
+ throw new TypeError(`Missing path parameter "${name}".`);
612
+ }
613
+ return encodeURIComponent(v);
614
+ });
615
+ const qs = new URLSearchParams(query).toString();
616
+ return `${this.baseUrl}${path}${qs ? `?${qs}` : ""}`;
617
+ }
618
+ async send(method, url, o) {
619
+ let attempt = 0;
620
+ let authRetried = false;
621
+ const safeToRepeat = method !== "POST" || Boolean(o.idempotencyKey);
622
+ for (; ; ) {
623
+ const headers = {
624
+ Accept: "application/json",
625
+ "User-Agent": this.userAgent,
626
+ ...o.headers ?? {}
627
+ };
628
+ if (o.body !== void 0) headers["Content-Type"] = "application/json";
629
+ if (o.idempotencyKey) headers["Idempotency-Key"] = o.idempotencyKey;
630
+ if (attempt > 0 && o.idempotencyKey) headers["Accept-Encoding"] = "identity";
631
+ let token = null;
632
+ if (o.auth) {
633
+ token = await this.accessToken();
634
+ headers.Authorization = `Bearer ${token}`;
635
+ }
636
+ let res;
637
+ try {
638
+ res = await this.fetchOnce(method, url, headers, o.body);
639
+ } catch (err) {
640
+ if (!o.noRetry && safeToRepeat && attempt < this.maxRetries) {
641
+ attempt++;
642
+ await this.sleep(this.backoff(attempt, null));
643
+ continue;
644
+ }
645
+ throw err;
646
+ }
647
+ if (res.status === 401 && o.auth && !authRetried) {
648
+ authRetried = true;
649
+ await this.renew(token);
650
+ continue;
651
+ }
652
+ if (!o.noRetry && attempt < this.maxRetries) {
653
+ const retriable = res.status === 429 || res.status >= 500 && safeToRepeat;
654
+ const ra = retryAfterMs(res.headers);
655
+ if (retriable && (ra === null || ra <= MAX_RETRY_AFTER_MS)) {
656
+ attempt++;
657
+ await this.sleep(this.backoff(attempt, ra));
658
+ continue;
659
+ }
660
+ }
661
+ return res;
662
+ }
663
+ }
664
+ async fetchOnce(method, url, headers, body) {
665
+ const ctrl = new AbortController();
666
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
667
+ try {
668
+ const r = await this.fetchImpl(url, {
669
+ method,
670
+ headers,
671
+ body: body === void 0 ? void 0 : JSON.stringify(body),
672
+ signal: ctrl.signal,
673
+ redirect: "manual",
674
+ cache: "no-store"
675
+ });
676
+ const text = await r.text();
677
+ let json = null;
678
+ if (text) {
679
+ try {
680
+ json = JSON.parse(text);
681
+ } catch {
682
+ json = null;
683
+ }
684
+ }
685
+ return { status: r.status, headers: r.headers, json, text };
686
+ } catch (err) {
687
+ const aborted = err?.name === "AbortError";
688
+ throw new ApiError(0, aborted ? "timeout" : "network_error", aborted ? "Request timed out." : "Network error.", {
689
+ cause: err
690
+ });
691
+ } finally {
692
+ clearTimeout(timer);
693
+ }
694
+ }
695
+ backoff(attempt, retryAfter) {
696
+ const base = Math.min(8e3, 500 * 2 ** (attempt - 1));
697
+ const jittered = base / 2 + this.random() * (base / 2);
698
+ return Math.max(jittered, retryAfter ?? 0);
699
+ }
700
+ // -------------------------------------------------------------- errors
701
+ toError(res, operationId, requestBody) {
702
+ const { code, message: serverText, requestId, hint } = normaliseErrorBody(res);
703
+ let message = apiErrorText(res.status, code, requestId, hint ?? (res.status === 404 ? NOT_FOUND_HINT : null));
704
+ let serverMessage = serverText;
705
+ if (SUPPRESS_ERROR_TEXT.has(operationId)) {
706
+ message = `Request failed with HTTP ${res.status}.`;
707
+ serverMessage = null;
708
+ }
709
+ let extensions = [];
710
+ if (res.status === 409) {
711
+ const requested = requestedNumbers(requestBody);
712
+ if (NUMBER_MAPPING_OPS.has(operationId) || requested.length) {
713
+ extensions = extensionConflictNumbers(serverText ?? "", requested);
714
+ message = EXTENSION_CONFLICT_MESSAGE;
715
+ serverMessage = null;
716
+ }
717
+ }
718
+ const extra = { requestId, operationId, serverMessage };
719
+ switch (true) {
720
+ case res.status === 401:
721
+ return new AuthError(res.status, code, message, extra);
722
+ case res.status === 404:
723
+ return new NotFoundError(res.status, code, message, extra);
724
+ case res.status === 409:
725
+ return new ConflictError(res.status, code, message, { ...extra, extensions });
726
+ case (res.status === 400 || res.status === 422):
727
+ return new ValidationError(res.status, code, message, extra);
728
+ case res.status === 429:
729
+ return new RateLimitError(res.status, code, message, secondsOrNull(retryAfterMs(res.headers)), extra);
730
+ default:
731
+ return new ApiError(res.status, code, message, extra);
732
+ }
733
+ }
734
+ };
735
+ function requestedNumbers(body, out = []) {
736
+ if (Array.isArray(body)) {
737
+ for (const v of body) requestedNumbers(v, out);
738
+ } else if (body && typeof body === "object") {
739
+ for (const [k, v] of Object.entries(body)) {
740
+ if (k === "monitored_numbers" && Array.isArray(v)) {
741
+ for (const n of v) if (!out.includes(String(n))) out.push(String(n));
742
+ } else {
743
+ requestedNumbers(v, out);
744
+ }
745
+ }
746
+ }
747
+ return out;
748
+ }
749
+ function extensionConflictNumbers(message, requested) {
750
+ const wanted = new Set(requested);
751
+ const seen = [];
752
+ for (const tok of (message ?? "").match(/[0-9*#+]+/g) ?? []) {
753
+ if (wanted.has(tok) && !seen.includes(tok)) seen.push(tok);
754
+ }
755
+ return seen;
756
+ }
757
+ var NOT_FOUND_HINT = "Not found, or outside what this login can see.";
758
+ function normaliseErrorBody(res) {
759
+ const b = res.json;
760
+ if (b && typeof b === "object") {
761
+ const e = b.error;
762
+ if (e && typeof e === "object") {
763
+ const eo = e;
764
+ return { code: str(eo.code) ?? str(eo.type), message: str(eo.message), requestId: str(eo.request_id), hint: null };
765
+ }
766
+ if (typeof e === "string") return { code: null, message: e, requestId: null, hint: null };
767
+ if (typeof b.message === "string") {
768
+ return { code: str(b.code) ?? null, message: b.message, requestId: null, hint: null };
769
+ }
770
+ }
771
+ const ct = res.headers?.get?.("content-type") ?? "";
772
+ if (res.status === 404 && !ct.includes("json")) {
773
+ return {
774
+ code: "not_json",
775
+ message: null,
776
+ requestId: null,
777
+ hint: "Non-JSON 404: the request was refused before reaching the API. Long query strings (e.g. many location ids) cause this."
778
+ };
779
+ }
780
+ return { code: null, message: null, requestId: null, hint: null };
781
+ }
782
+ function str(v) {
783
+ return typeof v === "string" && v !== "" ? v : null;
784
+ }
785
+ function retryAfterMs(h) {
786
+ const v = h?.get?.("retry-after");
787
+ if (!v) return null;
788
+ const n = Number(v);
789
+ if (Number.isFinite(n)) return Math.max(0, n * 1e3);
790
+ const t = Date.parse(v);
791
+ return Number.isFinite(t) ? Math.max(0, t - Date.now()) : null;
792
+ }
793
+ function secondsOrNull(ms) {
794
+ return ms === null ? null : Math.round(ms / 1e3);
795
+ }
796
+ function unwrapRow(item) {
797
+ return item && typeof item === "object" && item.attributes && typeof item.attributes === "object" ? item.attributes : item;
798
+ }
799
+ function extractPage(body) {
800
+ const data = body?.data;
801
+ const items = Array.isArray(data) ? data : Array.isArray(data?.calls) ? data.calls : Array.isArray(data?.alerts) ? data.alerts : [];
802
+ const paging = body?.pagination ?? body?.meta ?? body ?? {};
803
+ const nextCursor = typeof paging.next_cursor === "string" && paging.next_cursor ? paging.next_cursor : null;
804
+ const hasMore = Boolean(paging.has_more);
805
+ const total = typeof paging.total_count === "number" ? paging.total_count : typeof paging.total === "number" ? paging.total : typeof data?.summary?.total === "number" ? data.summary.total : typeof data?.summary?.total_calls === "number" ? data.summary.total_calls : null;
806
+ return { items, nextCursor, hasMore, total };
807
+ }
808
+
809
+ // src/generated/resources.ts
810
+ function makeResellers(c) {
811
+ return {
812
+ /** Read reseller branding. `GET /resellers/{resellerId}/branding` */
813
+ getResellerBranding: (resellerId) => c.call("getResellerBranding", [resellerId], {}),
814
+ /** Update reseller branding. `PATCH /resellers/{resellerId}/branding` */
815
+ updateResellerBranding: (resellerId, body) => c.call("updateResellerBranding", [resellerId], { body }),
816
+ /** Read outbound email (SMTP) settings. `GET /resellers/{resellerId}/smtp-settings` */
817
+ getResellerSmtpSettings: (resellerId) => c.call("getResellerSmtpSettings", [resellerId], {}),
818
+ /** Save outbound email (SMTP) settings. `PATCH /resellers/{resellerId}/smtp-settings` */
819
+ saveResellerSmtpSettings: (resellerId, body) => c.call("saveResellerSmtpSettings", [resellerId], { body }),
820
+ /** Remove outbound email (SMTP) settings. `DELETE /resellers/{resellerId}/smtp-settings` */
821
+ deleteResellerSmtpSettings: (resellerId) => c.call("deleteResellerSmtpSettings", [resellerId], {})
822
+ };
823
+ }
824
+ function makeCompanies(c) {
825
+ return {
826
+ /** List customer companies. `GET /resellers/{resellerId}/companies`. One page: rows (unwrapped) in `items`. */
827
+ listCompanies: (resellerId, query = {}) => c.page("listCompanies", [resellerId], { query }),
828
+ /** Every row of `GET /resellers/{resellerId}/companies`, following cursors with limit=100. */
829
+ iterCompanies: (resellerId, query = {}) => c.iterate("listCompanies", [resellerId], query),
830
+ /** Create a customer company. `POST /resellers/{resellerId}/companies` */
831
+ createCompany: (resellerId, body) => c.call("createCompany", [resellerId], { body }),
832
+ /** Read the MFA default for new companies. `GET /resellers/{resellerId}/companies/mfa` */
833
+ getCompaniesMfaSummary: (resellerId) => c.call("getCompaniesMfaSummary", [resellerId], {}),
834
+ /** Read a company. `GET /companies/{companyId}` */
835
+ getCompany: (companyId) => c.call("getCompany", [companyId], {}),
836
+ /** Update a company. `PATCH /companies/{companyId}` */
837
+ updateCompany: (companyId, body) => c.call("updateCompany", [companyId], { body }),
838
+ /** Deactivate a company. `POST /companies/{companyId}/deactivate` */
839
+ deactivateCompany: (companyId) => c.call("deactivateCompany", [companyId], {}),
840
+ /** Reactivate a company. `POST /companies/{companyId}/reactivate` */
841
+ reactivateCompany: (companyId) => c.call("reactivateCompany", [companyId], {}),
842
+ /** Read a company's security settings. `GET /companies/{companyId}/security-settings` */
843
+ getCompanySecuritySettings: (companyId) => c.call("getCompanySecuritySettings", [companyId], {}),
844
+ /** Read company branding overrides. `GET /companies/{companyId}/branding` */
845
+ getCompanyBranding: (companyId) => c.call("getCompanyBranding", [companyId], {}),
846
+ /** Update company branding overrides. `PATCH /companies/{companyId}/branding` */
847
+ updateCompanyBranding: (companyId, body) => c.call("updateCompanyBranding", [companyId], { body })
848
+ };
849
+ }
850
+ function makeSso(c) {
851
+ return {
852
+ /** List claimed domains. `GET /companies/{companyId}/domains` */
853
+ listCompanyDomains: (companyId) => c.call("listCompanyDomains", [companyId], {}),
854
+ /** Claim a domain. `POST /companies/{companyId}/domains` */
855
+ claimCompanyDomain: (companyId, body) => c.call("claimCompanyDomain", [companyId], { body }),
856
+ /** Remove a domain claim. `DELETE /companies/{companyId}/domains/{domainId}` */
857
+ removeCompanyDomain: (companyId, domainId) => c.call("removeCompanyDomain", [companyId, domainId], {}),
858
+ /** List verification attempts. `GET /companies/{companyId}/domains/{domainId}/verifications` */
859
+ listDomainVerifications: (companyId, domainId) => c.call("listDomainVerifications", [companyId, domainId], {}),
860
+ /** Check the TXT record now. `POST /companies/{companyId}/domains/{domainId}/verifications` */
861
+ verifyDomain: (companyId, domainId) => c.call("verifyDomain", [companyId, domainId], {}),
862
+ /** Read the identity provider connection. `GET /companies/{companyId}/identity-provider` */
863
+ getIdentityProvider: (companyId) => c.call("getIdentityProvider", [companyId], {}),
864
+ /** Connect an OpenID Connect provider. `POST /companies/{companyId}/identity-provider` */
865
+ connectIdentityProvider: (companyId, body) => c.call("connectIdentityProvider", [companyId], { body }),
866
+ /** Disconnect the identity provider. `DELETE /companies/{companyId}/identity-provider` */
867
+ disconnectIdentityProvider: (companyId) => c.call("disconnectIdentityProvider", [companyId], {}),
868
+ /** Test the identity provider connection. `POST /companies/{companyId}/identity-provider/test` */
869
+ testIdentityProvider: (companyId) => c.call("testIdentityProvider", [companyId], {})
870
+ };
871
+ }
872
+ function makeProducts(c) {
873
+ return {
874
+ /** List products. `GET /products` */
875
+ listProducts: () => c.call("listProducts", [], {}),
876
+ /** Company products. `GET /companies/{companyId}/products` */
877
+ listCompanyProducts: (companyId) => c.call("listCompanyProducts", [companyId], {}),
878
+ /** A user's products. `GET /companies/{companyId}/users/{userId}/products` */
879
+ listUserProducts: (companyId, userId) => c.call("listUserProducts", [companyId, userId], {}),
880
+ /** Turn a product on for a user. `POST /locations/{locationId}/users/{userId}/products/{productKey}/enable` */
881
+ enableUserProduct: (locationId, userId, productKey) => c.call("enableUserProduct", [locationId, userId, productKey], {}),
882
+ /** Turn a product off for a user. `POST /locations/{locationId}/users/{userId}/products/{productKey}/disable` */
883
+ disableUserProduct: (locationId, userId, productKey) => c.call("disableUserProduct", [locationId, userId, productKey], {})
884
+ };
885
+ }
886
+ function makeLocations(c) {
887
+ return {
888
+ /** List industries. `GET /verticals` */
889
+ listVerticals: () => c.call("listVerticals", [], {}),
890
+ /** List a company's locations. `GET /companies/{companyId}/locations`. One page: rows (unwrapped) in `items`. */
891
+ listCompanyLocations: (companyId, query = {}) => c.page("listCompanyLocations", [companyId], { query }),
892
+ /** Every row of `GET /companies/{companyId}/locations`, following cursors with limit=100. */
893
+ iterCompanyLocations: (companyId, query = {}) => c.iterate("listCompanyLocations", [companyId], query),
894
+ /** Create a location. `POST /companies/{companyId}/locations` */
895
+ createLocation: (companyId, body) => c.call("createLocation", [companyId], { body }),
896
+ /** Read a location. `GET /companies/{companyId}/locations/{locationId}` */
897
+ getLocation: (companyId, locationId) => c.call("getLocation", [companyId, locationId], {}),
898
+ /** Update a location. `PATCH /companies/{companyId}/locations/{locationId}` */
899
+ updateLocation: (companyId, locationId, body) => c.call("updateLocation", [companyId, locationId], { body }),
900
+ /** Deactivate a location. `POST /companies/{companyId}/locations/{locationId}/deactivate` */
901
+ deactivateLocation: (companyId, locationId) => c.call("deactivateLocation", [companyId, locationId], {}),
902
+ /** Reactivate a location. `POST /companies/{companyId}/locations/{locationId}/reactivate` */
903
+ reactivateLocation: (companyId, locationId) => c.call("reactivateLocation", [companyId, locationId], {})
904
+ };
905
+ }
906
+ function makeGroups(c) {
907
+ return {
908
+ /** List a location's groups. `GET /locations/{locationId}/user-groups`. One page: rows (unwrapped) in `items`. */
909
+ listUserGroups: (locationId, query = {}) => c.page("listUserGroups", [locationId], { query }),
910
+ /** Every row of `GET /locations/{locationId}/user-groups`, following cursors with limit=100. */
911
+ iterUserGroups: (locationId, query = {}) => c.iterate("listUserGroups", [locationId], query),
912
+ /** Create a group. `POST /locations/{locationId}/user-groups` */
913
+ createUserGroup: (locationId, body) => c.call("createUserGroup", [locationId], { body }),
914
+ /** Read a group with its members. `GET /locations/{locationId}/user-groups/{groupId}` */
915
+ getUserGroup: (locationId, groupId) => c.call("getUserGroup", [locationId, groupId], {}),
916
+ /** Rename a group or set its members. `PATCH /locations/{locationId}/user-groups/{groupId}` */
917
+ updateUserGroup: (locationId, groupId, body) => c.call("updateUserGroup", [locationId, groupId], { body }),
918
+ /** Delete a group. `DELETE /locations/{locationId}/user-groups/{groupId}` */
919
+ deleteUserGroup: (locationId, groupId, query = {}) => c.call("deleteUserGroup", [locationId, groupId], { query }),
920
+ /** A user's groups at a location. `GET /locations/{locationId}/users/{userId}/group-membership` */
921
+ getUserGroupMembership: (locationId, userId) => c.call("getUserGroupMembership", [locationId, userId], {}),
922
+ /** Set a user's groups at a location. `PUT /locations/{locationId}/users/{userId}/group-membership` */
923
+ setUserGroupMembership: (locationId, userId, body) => c.call("setUserGroupMembership", [locationId, userId], { body })
924
+ };
925
+ }
926
+ function makeConnectors(c) {
927
+ return {
928
+ /** List connector types. `GET /connector-types` */
929
+ listConnectorTypes: () => c.call("listConnectorTypes", [], {}),
930
+ /** Dry-run a connector. `POST /locations/{locationId}/connectors/test` */
931
+ testConnector: (locationId, body) => c.call("testConnector", [locationId], { body }),
932
+ /** List a location's connectors. `GET /locations/{locationId}/connectors`. One page: rows (unwrapped) in `items`. */
933
+ listLocationConnectors: (locationId, query = {}) => c.page("listLocationConnectors", [locationId], { query }),
934
+ /** Every row of `GET /locations/{locationId}/connectors`, following cursors with limit=100. */
935
+ iterLocationConnectors: (locationId, query = {}) => c.iterate("listLocationConnectors", [locationId], query),
936
+ /** Create a connector. `POST /locations/{locationId}/connectors` */
937
+ createConnector: (locationId, body) => c.call("createConnector", [locationId], { body }),
938
+ /** Read a connector. `GET /locations/{locationId}/connectors/{connectorId}` */
939
+ getConnector: (locationId, connectorId) => c.call("getConnector", [locationId, connectorId], {}),
940
+ /** Update a connector. `PATCH /locations/{locationId}/connectors/{connectorId}` */
941
+ updateConnector: (locationId, connectorId, body) => c.call("updateConnector", [locationId, connectorId], { body }),
942
+ /** Stop a connector. `POST /locations/{locationId}/connectors/{connectorId}/deactivate` */
943
+ deactivateConnector: (locationId, connectorId) => c.call("deactivateConnector", [locationId, connectorId], {}),
944
+ /** Restart a connector. `POST /locations/{locationId}/connectors/{connectorId}/reactivate` */
945
+ reactivateConnector: (locationId, connectorId) => c.call("reactivateConnector", [locationId, connectorId], {}),
946
+ /** List a company's connectors. `GET /companies/{companyId}/connectors`. One page: rows (unwrapped) in `items`. */
947
+ listCompanyConnectors: (companyId, query = {}) => c.page("listCompanyConnectors", [companyId], { query }),
948
+ /** Every row of `GET /companies/{companyId}/connectors`, following cursors with limit=100. */
949
+ iterCompanyConnectors: (companyId, query = {}) => c.iterate("listCompanyConnectors", [companyId], query)
950
+ };
951
+ }
952
+ function makeFirstAlert(c) {
953
+ return {
954
+ /** List a location's alert rules. `GET /locations/{locationId}/first-alert/rules`. One page: rows (unwrapped) in `items`. */
955
+ listAlertRules: (locationId, query = {}) => c.page("listAlertRules", [locationId], { query }),
956
+ /** Every row of `GET /locations/{locationId}/first-alert/rules`, following cursors with limit=100. */
957
+ iterAlertRules: (locationId, query = {}) => c.iterate("listAlertRules", [locationId], query),
958
+ /** Create an alert rule. `POST /locations/{locationId}/first-alert/rules` */
959
+ createAlertRule: (locationId, body) => c.call("createAlertRule", [locationId], { body }),
960
+ /** Read an alert rule. `GET /locations/{locationId}/first-alert/rules/{ruleId}` */
961
+ getAlertRule: (locationId, ruleId) => c.call("getAlertRule", [locationId, ruleId], {}),
962
+ /** Update an alert rule. `PATCH /locations/{locationId}/first-alert/rules/{ruleId}` */
963
+ updateAlertRule: (locationId, ruleId, body) => c.call("updateAlertRule", [locationId, ruleId], { body }),
964
+ /** Delete an alert rule. `DELETE /locations/{locationId}/first-alert/rules/{ruleId}` */
965
+ deleteAlertRule: (locationId, ruleId) => c.call("deleteAlertRule", [locationId, ruleId], {}),
966
+ /** Copy an alert rule. `POST /locations/{locationId}/first-alert/rules/{ruleId}/duplicate` */
967
+ duplicateAlertRule: (locationId, ruleId) => c.call("duplicateAlertRule", [locationId, ruleId], {}),
968
+ /** Read monitored numbers and the alert webhook. `GET /locations/{locationId}/first-alert/config` */
969
+ getFirstAlertConfig: (locationId) => c.call("getFirstAlertConfig", [locationId], {}),
970
+ /** Set monitored numbers and the alert webhook. `PUT /locations/{locationId}/first-alert/config` */
971
+ saveFirstAlertConfig: (locationId, body) => c.call("saveFirstAlertConfig", [locationId], { body }),
972
+ /** Test the alert webhook. `POST /locations/{locationId}/first-alert/config/test-webhook` */
973
+ testFirstAlertWebhook: (locationId, body) => c.call("testFirstAlertWebhook", [locationId], { body }),
974
+ /** Read a user's alert email and digest. `GET /locations/{locationId}/users/{userId}/first-alert/notification-preferences` */
975
+ getAlertNotificationPreferences: (locationId, userId) => c.call("getAlertNotificationPreferences", [locationId, userId], {}),
976
+ /** Set a user's alert email. `PUT /locations/{locationId}/users/{userId}/first-alert/email-preferences` */
977
+ setAlertEmailPreferences: (locationId, userId, body) => c.call("setAlertEmailPreferences", [locationId, userId], { body }),
978
+ /** Set a user's alert digest. `PUT /locations/{locationId}/users/{userId}/first-alert/digest-preferences` */
979
+ setAlertDigestPreferences: (locationId, userId, body) => c.call("setAlertDigestPreferences", [locationId, userId], { body })
980
+ };
981
+ }
982
+ function makeInsightsHub(c) {
983
+ return {
984
+ /** Read Insights Hub setup. `GET /locations/{locationId}/insights-hub/setup` */
985
+ getInsightsHubSetup: (locationId) => c.call("getInsightsHubSetup", [locationId], {}),
986
+ /** Save Insights Hub setup. `POST /locations/{locationId}/insights-hub/setup` */
987
+ saveInsightsHubSetup: (locationId, body) => c.call("saveInsightsHubSetup", [locationId], { body }),
988
+ /** Update Insights Hub setup. `PATCH /locations/{locationId}/insights-hub/setup` */
989
+ updateInsightsHubSetup: (locationId, body) => c.call("updateInsightsHubSetup", [locationId], { body }),
990
+ /** Read Insights Hub coverage. `GET /locations/{locationId}/insights-hub/config` */
991
+ getInsightsHubConfig: (locationId) => c.call("getInsightsHubConfig", [locationId], {}),
992
+ /** Set Insights Hub coverage. `PATCH /locations/{locationId}/insights-hub/config` */
993
+ updateInsightsHubConfig: (locationId, body) => c.call("updateInsightsHubConfig", [locationId], { body }),
994
+ /** Check a user's Insights Hub access. `GET /locations/{locationId}/users/{userId}/insights-hub/access` */
995
+ getUserInsightsHubAccess: (locationId, userId) => c.call("getUserInsightsHubAccess", [locationId, userId], {})
996
+ };
997
+ }
998
+ function makeUsers(c) {
999
+ return {
1000
+ /** List a company's users. `GET /companies/{companyId}/users`. One page: rows (unwrapped) in `items`. */
1001
+ listCompanyUsers: (companyId, query = {}) => c.page("listCompanyUsers", [companyId], { query }),
1002
+ /** Every row of `GET /companies/{companyId}/users`, following cursors with limit=100. */
1003
+ iterCompanyUsers: (companyId, query = {}) => c.iterate("listCompanyUsers", [companyId], query),
1004
+ /** Create a user. `POST /companies/{companyId}/users` */
1005
+ createCompanyUser: (companyId, body) => c.call("createCompanyUser", [companyId], { body }),
1006
+ /** Read a user. `GET /companies/{companyId}/users/{userId}` */
1007
+ getCompanyUser: (companyId, userId) => c.call("getCompanyUser", [companyId, userId], {}),
1008
+ /** Update a user, role or locations. `PATCH /companies/{companyId}/users/{userId}` */
1009
+ updateCompanyUser: (companyId, userId, body) => c.call("updateCompanyUser", [companyId, userId], { body }),
1010
+ /** Deactivate a user. `POST /companies/{companyId}/users/{userId}/deactivate` */
1011
+ deactivateCompanyUser: (companyId, userId) => c.call("deactivateCompanyUser", [companyId, userId], {}),
1012
+ /** Reactivate a user. `POST /companies/{companyId}/users/{userId}/reactivate` */
1013
+ reactivateCompanyUser: (companyId, userId) => c.call("reactivateCompanyUser", [companyId, userId], {}),
1014
+ /** Resend the invitation email. `POST /companies/{companyId}/users/{userId}/resend-invitation` */
1015
+ resendInvitation: (companyId, userId) => c.call("resendInvitation", [companyId, userId], {}),
1016
+ /** Send a password reset email. `POST /companies/{companyId}/users/{userId}/reset-password` */
1017
+ resetPassword: (companyId, userId) => c.call("resetPassword", [companyId, userId], {}),
1018
+ /** Read a user's numbers. `GET /companies/{companyId}/users/{userId}/connector-mappings` */
1019
+ getUserNumberMappings: (companyId, userId) => c.call("getUserNumberMappings", [companyId, userId], {}),
1020
+ /** Set a user's numbers. `PUT /companies/{companyId}/users/{userId}/connector-mappings` */
1021
+ setUserNumberMappings: (companyId, userId, body) => c.call("setUserNumberMappings", [companyId, userId], { body }),
1022
+ /** List a location's users with products and groups. `GET /locations/{locationId}/users`. One page: rows (unwrapped) in `items`. */
1023
+ listLocationUsers: (locationId, query = {}) => c.page("listLocationUsers", [locationId], { query }),
1024
+ /** Every row of `GET /locations/{locationId}/users`, following cursors with limit=100. */
1025
+ iterLocationUsers: (locationId, query = {}) => c.iterate("listLocationUsers", [locationId], query),
1026
+ /** Read a user at a location. `GET /locations/{locationId}/users/{userId}` */
1027
+ getLocationUser: (locationId, userId) => c.call("getLocationUser", [locationId, userId], {})
1028
+ };
1029
+ }
1030
+ function makeAfterCallSettings(c) {
1031
+ return {
1032
+ /** Read a user's After Call settings. `GET /locations/{locationId}/users/{userId}/after-call-settings` */
1033
+ getUserAfterCallSettings: (locationId, userId) => c.call("getUserAfterCallSettings", [locationId, userId], {}),
1034
+ /** Update a user's After Call settings. `PATCH /locations/{locationId}/users/{userId}/after-call-settings` */
1035
+ updateUserAfterCallSettings: (locationId, userId, body) => c.call("updateUserAfterCallSettings", [locationId, userId], { body })
1036
+ };
1037
+ }
1038
+ function makeAccount(c) {
1039
+ return {
1040
+ /** Who is signed in. `GET /me` */
1041
+ getMe: () => c.call("getMe", [], {}),
1042
+ /** Locations this login can see. `GET /locations`. One page: rows (unwrapped) in `items`. */
1043
+ listVisibleLocations: (query = {}) => c.page("listVisibleLocations", [], { query }),
1044
+ /** Every row of `GET /locations`, following cursors with limit=100. */
1045
+ iterVisibleLocations: (query = {}) => c.iterate("listVisibleLocations", [], query)
1046
+ };
1047
+ }
1048
+ function makeCalls(c) {
1049
+ return {
1050
+ /** List calls. `GET /calls`. One page: rows (unwrapped) in `items`. */
1051
+ listCalls: (query = {}) => c.page("listCalls", [], { query }),
1052
+ /** Every row of `GET /calls`, following cursors with limit=100. */
1053
+ iterCalls: (query = {}) => c.iterate("listCalls", [], query),
1054
+ /** Read a call. `GET /calls/{callId}` */
1055
+ getCall: (callId) => c.call("getCall", [callId], {}),
1056
+ /** Read a call's transcript. `GET /calls/{callId}/transcript` */
1057
+ getCallTranscript: (callId) => c.call("getCallTranscript", [callId], {})
1058
+ };
1059
+ }
1060
+ function makeAlerts(c) {
1061
+ return {
1062
+ /** List alerts. `GET /alerts`. One page: rows (unwrapped) in `items`. */
1063
+ listAlerts: (query = {}) => c.page("listAlerts", [], { query }),
1064
+ /** Every row of `GET /alerts`, following cursors with limit=100. */
1065
+ iterAlerts: (query = {}) => c.iterate("listAlerts", [], query),
1066
+ /** Alert totals. `GET /alerts/dashboard` */
1067
+ getAlertsDashboard: (query = {}) => c.call("getAlertsDashboard", [], { query })
1068
+ };
1069
+ }
1070
+ function makeTasks(c) {
1071
+ return {
1072
+ /** List tasks. `GET /tasks`. One page: rows (unwrapped) in `items`. */
1073
+ listTasks: (query = {}) => c.page("listTasks", [], { query }),
1074
+ /** Every row of `GET /tasks`, following cursors with limit=100. */
1075
+ iterTasks: (query = {}) => c.iterate("listTasks", [], query)
1076
+ };
1077
+ }
1078
+ function makeInsights(c) {
1079
+ return {
1080
+ /** Insights Hub dashboard. `GET /insights/dashboard` */
1081
+ getInsightsDashboard: (query = {}) => c.call("getInsightsDashboard", [], { query }),
1082
+ /** Calls for one topic. `GET /insights/topics/{slug}/calls`. One page: rows (unwrapped) in `items`. */
1083
+ listTopicCalls: (slug, query = {}) => c.page("listTopicCalls", [slug], { query }),
1084
+ /** Every row of `GET /insights/topics/{slug}/calls`, following cursors with limit=100. */
1085
+ iterTopicCalls: (slug, query = {}) => c.iterate("listTopicCalls", [slug], query)
1086
+ };
1087
+ }
1088
+ function makeWebhooks(c) {
1089
+ return {
1090
+ /** Read the After Call webhook. `GET /locations/{locationId}/after-call/automation` */
1091
+ getAfterCallWebhook: (locationId) => c.call("getAfterCallWebhook", [locationId], {}),
1092
+ /** Set the After Call webhook. `PUT /locations/{locationId}/after-call/automation` */
1093
+ saveAfterCallWebhook: (locationId, body) => c.call("saveAfterCallWebhook", [locationId], { body }),
1094
+ /** Send a test After Call event. `POST /locations/{locationId}/after-call/automation/test` */
1095
+ testAfterCallWebhook: (locationId) => c.call("testAfterCallWebhook", [locationId], {})
1096
+ };
1097
+ }
1098
+
1099
+ // src/intelligence.ts
1100
+ var CALL_FILTERS = [
1101
+ "phone",
1102
+ "text",
1103
+ "dateFrom",
1104
+ "dateTo",
1105
+ "status",
1106
+ "sentiment",
1107
+ "hasOpenTasks",
1108
+ "multiLeg",
1109
+ "locationIds",
1110
+ "companyId",
1111
+ "cursor",
1112
+ "limit"
1113
+ ];
1114
+ var ALERT_FILTERS = [
1115
+ "alertName",
1116
+ "numbers",
1117
+ "text",
1118
+ "sentiment",
1119
+ "dateFrom",
1120
+ "dateTo",
1121
+ "locationIds",
1122
+ "topic",
1123
+ "companyId",
1124
+ "cursor",
1125
+ "limit"
1126
+ ];
1127
+ var TASK_FILTERS = [
1128
+ "status",
1129
+ "todayStart",
1130
+ "callId",
1131
+ "taskId",
1132
+ "dueOn",
1133
+ "dateFrom",
1134
+ "dateTo",
1135
+ "search",
1136
+ "locationIds",
1137
+ "companyId",
1138
+ "cursor",
1139
+ "limit"
1140
+ ];
1141
+ var TOPIC_FILTERS = ["dateFrom", "dateTo", "sentiment", "outcome", "search", "locationIds", "companyId", "cursor", "limit"];
1142
+ function only(given, allowed, method) {
1143
+ for (const [k, v] of Object.entries(given)) {
1144
+ if (v === void 0) continue;
1145
+ if (!allowed.includes(k)) {
1146
+ throw new FilterError(`"${k}" is not a filter of ${method}. Supported: ${allowed.join(", ")}.`);
1147
+ }
1148
+ }
1149
+ }
1150
+ function renameLocationIds(f) {
1151
+ const q = {};
1152
+ for (const [k, v] of Object.entries(f)) q[k === "locationIds" ? "location_id" : k] = v;
1153
+ return q;
1154
+ }
1155
+ var Intelligence = class {
1156
+ constructor(c, checkRole) {
1157
+ this.c = c;
1158
+ this.checkRole = checkRole;
1159
+ }
1160
+ c;
1161
+ checkRole;
1162
+ roleCheck = null;
1163
+ // ------------------------------------------------------------------ account
1164
+ /** The signed-in user (`GET /me`). */
1165
+ async whoami() {
1166
+ return (await this.c.account.getMe()).data ?? {};
1167
+ }
1168
+ /** Throws `FrontlineRequiredError` unless this login is a frontline user. Checked once, then cached. */
1169
+ requireFrontline() {
1170
+ if (!this.roleCheck) {
1171
+ this.roleCheck = this.whoami().then((me) => {
1172
+ if (me.role !== "frontline_user") throw new FrontlineRequiredError(me.role ?? null);
1173
+ return me;
1174
+ });
1175
+ this.roleCheck.catch(() => {
1176
+ this.roleCheck = null;
1177
+ });
1178
+ }
1179
+ return this.roleCheck;
1180
+ }
1181
+ async frontline() {
1182
+ if (this.checkRole) await this.requireFrontline();
1183
+ }
1184
+ // ------------------------------------------------------------------ calls
1185
+ callQuery(f) {
1186
+ only(f, CALL_FILTERS, "searchCalls");
1187
+ if (f.phone !== void 0 && f.text !== void 0) {
1188
+ throw new FilterError("Give phone or text, not both: the API has one search field.");
1189
+ }
1190
+ return {
1191
+ date_from: f.dateFrom,
1192
+ date_to: f.dateTo,
1193
+ status: f.status,
1194
+ sentiment: f.sentiment,
1195
+ has_open_tasks: f.hasOpenTasks,
1196
+ multi_leg: f.multiLeg,
1197
+ location_id: f.locationIds,
1198
+ company_id: f.companyId,
1199
+ search: f.phone ?? f.text,
1200
+ cursor: f.cursor,
1201
+ limit: f.limit
1202
+ };
1203
+ }
1204
+ /** One page of calls, newest first, with totals for the whole filter in `summary`. */
1205
+ async searchCalls(filters = {}) {
1206
+ const q = this.callQuery(filters);
1207
+ await this.frontline();
1208
+ const page = await this.c.calls.listCalls(q);
1209
+ return { ...page, summary: page.raw.data?.summary ?? {} };
1210
+ }
1211
+ /** Every call that matches, following cursors with limit=100. Stop early with `maxItems`. */
1212
+ async *iterCalls(filters = {}) {
1213
+ const { maxItems, ...f } = filters;
1214
+ const q = this.callQuery(f);
1215
+ await this.frontline();
1216
+ yield* this.c.calls.iterCalls({ ...q, maxItems });
1217
+ }
1218
+ /** Full detail of one call. NotFoundError when the call is outside this login's view. */
1219
+ async getCall(callId) {
1220
+ await this.frontline();
1221
+ return (await this.c.calls.getCall(callId)).data ?? {};
1222
+ }
1223
+ /** Transcript lines in order ("Speaker 1" … "Speaker N"; `name` when known). */
1224
+ async getTranscript(callId) {
1225
+ await this.frontline();
1226
+ return (await this.c.calls.getCallTranscript(callId)).data?.transcript ?? [];
1227
+ }
1228
+ /**
1229
+ * The call's recording link and when it expires. Nothing else from the conversation record is
1230
+ * returned. The link is a signed HTTPS URL to the WAV audio: fetch it with a plain GET and no
1231
+ * Authorization header (Range requests work). It is valid for 120 minutes. Treat it as a secret:
1232
+ * never log or store it, and call this again for a fresh link. `url` is null when the call has
1233
+ * no recording.
1234
+ */
1235
+ async getRecordingUrl(callId) {
1236
+ const call = await this.getCall(callId);
1237
+ const v = call.vcon;
1238
+ return { url: v?.recording_url ?? null, expiresAt: v?.recording_url_expires_at ?? null };
1239
+ }
1240
+ // ------------------------------------------------------------------ alerts
1241
+ alertQuery(f) {
1242
+ only(f, ALERT_FILTERS, "searchAlerts");
1243
+ return {
1244
+ keyword: f.alertName,
1245
+ numbers: f.numbers,
1246
+ search: f.text,
1247
+ sentiment: f.sentiment,
1248
+ date_from: f.dateFrom,
1249
+ date_to: f.dateTo,
1250
+ location_id: f.locationIds,
1251
+ topic: f.topic,
1252
+ company_id: f.companyId,
1253
+ cursor: f.cursor,
1254
+ limit: f.limit
1255
+ };
1256
+ }
1257
+ /** One page of First Alert hits, newest first. `total` counts every match. */
1258
+ async searchAlerts(filters = {}) {
1259
+ const q = this.alertQuery(filters);
1260
+ await this.frontline();
1261
+ return this.c.alerts.listAlerts(q);
1262
+ }
1263
+ async *iterAlerts(filters = {}) {
1264
+ const { maxItems, ...f } = filters;
1265
+ const q = this.alertQuery(f);
1266
+ await this.frontline();
1267
+ yield* this.c.alerts.iterAlerts({ ...q, maxItems });
1268
+ }
1269
+ /**
1270
+ * One alert by id (there is no alert detail endpoint: this searches by id, no date window).
1271
+ * Returns null when the alert is not visible. With `withCall: true` the call detail is added as `call`.
1272
+ */
1273
+ async getAlert(alertId, options = {}) {
1274
+ const id = alertId.trim().toLowerCase();
1275
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) {
1276
+ throw new FilterError("alertId must be a UUID.");
1277
+ }
1278
+ const page = await this.searchAlerts({ text: id, limit: 10 });
1279
+ const alert = page.items.find((a) => (a.id ?? "").toLowerCase() === id);
1280
+ if (!alert) return null;
1281
+ if (options.withCall && alert.call_id) return { ...alert, call: await this.getCall(alert.call_id) };
1282
+ return alert;
1283
+ }
1284
+ /** Alert totals for a window (default: 00:00 UTC seven days ago until now). */
1285
+ async getAlertsDashboard(filters = {}) {
1286
+ only(filters, ["dateFrom", "dateTo", "locationIds", "companyId"], "getAlertsDashboard");
1287
+ await this.frontline();
1288
+ return (await this.c.alerts.getAlertsDashboard(renameLocationIds(filters))).data ?? {};
1289
+ }
1290
+ // ------------------------------------------------------------------ tasks
1291
+ /** One page of follow-up tasks, newest first. No default date window. */
1292
+ async listTasks(filters = {}) {
1293
+ only(filters, TASK_FILTERS, "listTasks");
1294
+ await this.frontline();
1295
+ const page = await this.c.tasks.listTasks(renameLocationIds(filters));
1296
+ return { ...page, summary: page.raw.summary ?? {} };
1297
+ }
1298
+ async *iterTasks(filters = {}) {
1299
+ const { maxItems, ...f } = filters;
1300
+ only(f, TASK_FILTERS, "iterTasks");
1301
+ await this.frontline();
1302
+ yield* this.c.tasks.iterTasks({ ...renameLocationIds(f), maxItems });
1303
+ }
1304
+ // ------------------------------------------------------------------ insights
1305
+ /** Insights Hub dashboard for a window. `start` and `end` are required. */
1306
+ async getInsightsDashboard(filters) {
1307
+ only(filters, ["start", "end", "trendingLimit", "locationIds", "companyId"], "getInsightsDashboard");
1308
+ await this.frontline();
1309
+ return (await this.c.insights.getInsightsDashboard(renameLocationIds(filters))).data ?? {};
1310
+ }
1311
+ /** One page of calls for a topic slug (from the dashboard's `topic_call_volumes`). */
1312
+ async listTopicCalls(slug, filters = {}) {
1313
+ only(filters, TOPIC_FILTERS, "listTopicCalls");
1314
+ await this.frontline();
1315
+ return this.c.insights.listTopicCalls(slug, renameLocationIds(filters));
1316
+ }
1317
+ async *iterTopicCalls(slug, filters = {}) {
1318
+ const { maxItems, ...f } = filters;
1319
+ only(f, TOPIC_FILTERS, "iterTopicCalls");
1320
+ await this.frontline();
1321
+ yield* this.c.insights.iterTopicCalls(slug, { ...renameLocationIds(f), maxItems });
1322
+ }
1323
+ // ------------------------------------------------------------------ webhook configuration
1324
+ /** The location's After Call webhook, or null when none is set. */
1325
+ async getAfterCallWebhook(locationId) {
1326
+ return (await this.c.webhooks.getAfterCallWebhook(locationId)).data ?? null;
1327
+ }
1328
+ /**
1329
+ * Set the location's After Call webhook (HTTPS). It receives every call at the location,
1330
+ * whatever users' number mappings say. `enabled: false` pauses it (there is no delete).
1331
+ */
1332
+ async setAfterCallWebhook(locationId, url, enabled = true) {
1333
+ if (!/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1334
+ const r = await this.c.webhooks.saveAfterCallWebhook(locationId, { webhook_url: url, enabled });
1335
+ return r.data ?? {};
1336
+ }
1337
+ /** Send the test event to the saved URL. Returns only whether your endpoint answered 2xx, and its status. */
1338
+ async testAfterCallWebhook(locationId) {
1339
+ const d = (await this.c.webhooks.testAfterCallWebhook(locationId)).data ?? {};
1340
+ return { success: Boolean(d.success), http_status: d.http_status ?? null };
1341
+ }
1342
+ /** The location's First Alert webhook URL, or null. */
1343
+ async getFirstAlertWebhook(locationId) {
1344
+ return (await this.c.firstAlert.getFirstAlertConfig(locationId)).data?.webhook_url ?? null;
1345
+ }
1346
+ /**
1347
+ * Set (or, with null, clear) the location's First Alert webhook URL. Read → merge → write: the
1348
+ * configuration PUT would otherwise clear the monitored numbers.
1349
+ */
1350
+ async setFirstAlertWebhook(locationId, url) {
1351
+ if (url !== null && !/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1352
+ return (await this.c.firstAlert.setWebhookUrl(locationId, url)).data ?? {};
1353
+ }
1354
+ /** Send a test request to `url` (default: the saved URL). Returns only success and your endpoint's status. */
1355
+ async testFirstAlertWebhook(locationId, url) {
1356
+ const target = url ?? await this.getFirstAlertWebhook(locationId);
1357
+ if (!target) throw new FilterError("No First Alert webhook URL is set for this location; pass one.");
1358
+ const d = (await this.c.firstAlert.testFirstAlertWebhook(locationId, { url: target })).data ?? {};
1359
+ return { success: Boolean(d.success), http_status: d.status_code ?? null };
1360
+ }
1361
+ };
1362
+
1363
+ // src/util.ts
1364
+ async function uuid4() {
1365
+ const c = globalThis.crypto;
1366
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
1367
+ let bytes;
1368
+ if (c && typeof c.getRandomValues === "function") {
1369
+ bytes = c.getRandomValues(new Uint8Array(16));
1370
+ } else {
1371
+ const nodeCrypto = await import('crypto');
1372
+ bytes = new Uint8Array(nodeCrypto.randomBytes(16));
1373
+ }
1374
+ bytes[6] = bytes[6] & 15 | 64;
1375
+ bytes[8] = bytes[8] & 63 | 128;
1376
+ const h = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
1377
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1378
+ }
1379
+ function numbersFor(mappings, connectorId) {
1380
+ const out = [];
1381
+ for (const m of mappings ?? []) if (m.connector_id === connectorId) out.push(...m.monitored_numbers ?? []);
1382
+ return [...new Set(out)];
1383
+ }
1384
+ function mergeMappings(current, connectorId, add = [], remove = []) {
1385
+ const byConnector = /* @__PURE__ */ new Map();
1386
+ for (const m of current ?? []) {
1387
+ if (!m.connector_id) continue;
1388
+ const list2 = byConnector.get(m.connector_id) ?? [];
1389
+ list2.push(...m.monitored_numbers ?? []);
1390
+ byConnector.set(m.connector_id, list2);
1391
+ }
1392
+ const drop = new Set(remove);
1393
+ const mine = (byConnector.get(connectorId) ?? []).filter((n) => !drop.has(n));
1394
+ for (const n of add) if (!mine.includes(n)) mine.push(n);
1395
+ byConnector.set(connectorId, mine);
1396
+ const out = [];
1397
+ for (const [connector_id, nums] of byConnector) {
1398
+ const uniq2 = [...new Set(nums)];
1399
+ if (uniq2.length) out.push({ connector_id, monitored_numbers: uniq2 });
1400
+ }
1401
+ return out;
1402
+ }
1403
+ function sameSet(a, b) {
1404
+ const sa = new Set(a);
1405
+ const sb = new Set(b);
1406
+ if (sa.size !== sb.size) return false;
1407
+ for (const x of sa) if (!sb.has(x)) return false;
1408
+ return true;
1409
+ }
1410
+ function diff(current, target) {
1411
+ const c = new Set(current);
1412
+ const t = new Set(target);
1413
+ return { add: [...t].filter((x) => !c.has(x)), remove: [...c].filter((x) => !t.has(x)) };
1414
+ }
1415
+
1416
+ // src/workflows.ts
1417
+ var ALL_PRODUCTS = ["after-call-copilot", "first-alert-copilot", "insights-hub"];
1418
+ var MANAGER_ALERTS_GROUP = "Manager Alerts";
1419
+ var INSIGHTS_HUB_ACCESS_GROUP = "Insights Hub Access";
1420
+ var UPSET_CUSTOMER_RULE = "Upset Customer";
1421
+ var CUSTOMER_THREAT_RULE = "Customer Threat";
1422
+ var DEFAULT_VERTICAL_KEY = "csps-msps";
1423
+ var THREAT_PHRASES_MISSING = "Customer Threat phrases are provided by your Tresic contact.";
1424
+ var INTEGRATION_DEPARTMENT = "integration";
1425
+ function companyNameConflictMessage(name) {
1426
+ return `A company named '${name}' already exists with a different primary contact. Pass companyId to use an existing company, or choose a different company name.`;
1427
+ }
1428
+ function upsetCustomerRule(groupIds, enabled = false) {
1429
+ return {
1430
+ name: UPSET_CUSTOMER_RULE,
1431
+ priority: "high",
1432
+ match_logic: "any",
1433
+ enabled,
1434
+ triggers: [{ trigger_type: "sentiment", config: { operator: "lt", threshold: -40 } }],
1435
+ group_ids: groupIds
1436
+ };
1437
+ }
1438
+ function customerThreatRule(groupIds, phrases, enabled = false) {
1439
+ if (!phrases || phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1440
+ return {
1441
+ name: CUSTOMER_THREAT_RULE,
1442
+ priority: "critical",
1443
+ match_logic: "all",
1444
+ enabled,
1445
+ triggers: [
1446
+ { trigger_type: "sentiment", config: { operator: "lt", threshold: -20 } },
1447
+ { trigger_type: "keyword_match", config: { match_logic: "any", keywords: [...phrases] } }
1448
+ ],
1449
+ group_ids: groupIds
1450
+ };
1451
+ }
1452
+ async function step(name, partial, fn) {
1453
+ try {
1454
+ return await fn();
1455
+ } catch (err) {
1456
+ if (err instanceof WorkflowError || err instanceof ExtensionMappingError || err instanceof FilterError) throw err;
1457
+ throw new WorkflowError(name, partial, err);
1458
+ }
1459
+ }
1460
+ function canonical(v) {
1461
+ if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
1462
+ if (v && typeof v === "object") {
1463
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
1464
+ }
1465
+ return JSON.stringify(v ?? null);
1466
+ }
1467
+ var CONNECTOR_RANK = { active: 0, connecting: 1, error: 2, deactivating: 3, inactive: 4 };
1468
+ function isIntegration(u) {
1469
+ return (u.department ?? "").trim().toLowerCase() === INTEGRATION_DEPARTMENT;
1470
+ }
1471
+ function isManager(u) {
1472
+ return !isIntegration(u) && ALL_PRODUCTS.every((p) => u.enabledProducts.includes(p));
1473
+ }
1474
+ function isFrontline(u) {
1475
+ return !isIntegration(u) && u.enabledProducts.length === 1 && u.enabledProducts[0] === "after-call-copilot";
1476
+ }
1477
+ var norm = (s) => (s ?? "").trim().toLowerCase();
1478
+ var Workflows = class {
1479
+ constructor(c) {
1480
+ this.c = c;
1481
+ }
1482
+ c;
1483
+ // ------------------------------------------------------------------ lookups
1484
+ async bestConnector(locationId) {
1485
+ let best = null;
1486
+ for await (const row of this.c.connectors.iterLocationConnectors(locationId)) {
1487
+ if (!best || (CONNECTOR_RANK[row.status ?? ""] ?? 9) < (CONNECTOR_RANK[best.status ?? ""] ?? 9)) best = row;
1488
+ }
1489
+ return best;
1490
+ }
1491
+ async resolve(ref) {
1492
+ return typeof ref === "string" ? this.getSeatCustomer(ref) : ref;
1493
+ }
1494
+ requireConnector(customer) {
1495
+ if (!customer.connectorId) {
1496
+ throw new IntelligenceCloudError("This customer has no connector at its location, so numbers can't be mapped.");
1497
+ }
1498
+ return customer.connectorId;
1499
+ }
1500
+ /**
1501
+ * Find the user by email (reactivating and assigning to the location if needed) or create them.
1502
+ * Re-running a workflow therefore carries on with the same user.
1503
+ */
1504
+ async ensureUser(customer, u) {
1505
+ if (!u?.email || !u.firstName || !u.lastName) throw new FilterError("email, firstName and lastName are required.");
1506
+ const users = this.c.users;
1507
+ const found = await users.findUserByEmail(customer.companyId, u.email);
1508
+ if (!found?.id) {
1509
+ const r = await users.createCompanyUser(
1510
+ customer.companyId,
1511
+ {
1512
+ email: u.email,
1513
+ first_name: u.firstName,
1514
+ last_name: u.lastName,
1515
+ phone_number: u.phoneNumber,
1516
+ role: "frontline_user",
1517
+ location_ids: [customer.locationId],
1518
+ send_invitation: false,
1519
+ // the invitation is emailed last, once the user is set up
1520
+ auth_method: u.authMethod ?? "password"
1521
+ },
1522
+ { idempotencyKey: u.idempotencyKey }
1523
+ );
1524
+ const id = r.data?.attributes?.id;
1525
+ if (!id) throw new IntelligenceCloudError("User create returned no id.");
1526
+ return { id, created: true, status: r.data?.attributes?.status ?? "invited" };
1527
+ }
1528
+ if (found.status === "deactivated") await users.reactivateCompanyUser(customer.companyId, found.id);
1529
+ const detail = (await users.getCompanyUser(customer.companyId, found.id)).data?.attributes ?? {};
1530
+ if (detail.role !== "frontline_user") {
1531
+ throw new FilterError(`${u.email} is a ${detail.role}; Seat users are frontline users.`);
1532
+ }
1533
+ if (!(detail.locations ?? []).some((l) => l.location_id === customer.locationId)) {
1534
+ await users.addLocations(customer.companyId, found.id, [customer.locationId]);
1535
+ }
1536
+ return { id: found.id, created: false, status: detail.status ?? null };
1537
+ }
1538
+ /** The last step: email the invitation to a user who has not accepted one yet. */
1539
+ async invite(customer, u, userId, status) {
1540
+ if (u.sendInvitation === false || status !== "invited") return false;
1541
+ await this.c.users.resendInvitation(customer.companyId, userId);
1542
+ return true;
1543
+ }
1544
+ /** Replace the user's numbers on the customer's connector; a refusal becomes ExtensionMappingError. */
1545
+ async mapNumbers(customer, userId, numbers) {
1546
+ const connectorId = this.requireConnector(customer);
1547
+ try {
1548
+ await this.c.users.setNumbers(customer.companyId, userId, connectorId, numbers);
1549
+ } catch (err) {
1550
+ if (err instanceof ValidationError || err instanceof ConflictError) throw new ExtensionMappingError(userId, err);
1551
+ throw err;
1552
+ }
1553
+ }
1554
+ /** Lines at the location: First Alert's monitored numbers for the customer's connector. */
1555
+ async locationLines(customer) {
1556
+ if (!customer.connectorId) return [];
1557
+ const cfg = (await this.c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
1558
+ return numbersFor(cfg?.connector_mappings, customer.connectorId);
1559
+ }
1560
+ excluded(customer, id, email) {
1561
+ if ((customer.excludeUserIds ?? []).includes(id)) return true;
1562
+ const e = (email ?? "").trim().toLowerCase();
1563
+ return Boolean(e) && (customer.excludeEmails ?? []).some((x) => x.trim().toLowerCase() === e);
1564
+ }
1565
+ /** Active or invited frontline users at the location (not excluded), with their department. */
1566
+ async seatUsers(customer) {
1567
+ const departments = /* @__PURE__ */ new Map();
1568
+ for await (const u of this.c.users.iterCompanyUsers(customer.companyId, { locationId: [customer.locationId] })) {
1569
+ if (u?.id) departments.set(u.id, u.department ?? null);
1570
+ }
1571
+ const out = [];
1572
+ for await (const a of this.c.users.iterLocationUsers(customer.locationId)) {
1573
+ if (!a?.id || a.status === "deactivated" || a.role !== "frontline_user") continue;
1574
+ if (this.excluded(customer, a.id, a.email)) continue;
1575
+ out.push({
1576
+ id: a.id,
1577
+ email: a.email ?? "",
1578
+ displayName: a.display_name ?? "",
1579
+ status: a.status ?? "",
1580
+ enabledProducts: [...a.enabled_products ?? []],
1581
+ groups: [...a.groups ?? []],
1582
+ department: departments.get(a.id) ?? null
1583
+ });
1584
+ }
1585
+ return out;
1586
+ }
1587
+ /** Managers and integration users: the users who hold every line. */
1588
+ async lineHolders(customer) {
1589
+ const all = await this.seatUsers(customer);
1590
+ return all.filter((u) => isManager(u) || isIntegration(u));
1591
+ }
1592
+ /** Lines held by end users who hold exactly one line (users holding several are not seats). */
1593
+ async endUserLines(customer, connectorId, exceptUserId) {
1594
+ const lines = /* @__PURE__ */ new Set();
1595
+ for (const u of await this.listFrontlineUsers(customer)) {
1596
+ if (u.id === exceptUserId) continue;
1597
+ const nums = await this.c.users.userNumbers(customer.companyId, u.id, connectorId);
1598
+ if (nums.length === 1) lines.add(nums[0]);
1599
+ }
1600
+ return lines;
1601
+ }
1602
+ // ------------------------------------------------------------------ workflows
1603
+ /** Rebuild the customer object (location, groups, rules, connector) from a company id. */
1604
+ async getSeatCustomer(companyId, options = {}) {
1605
+ const company = (await this.c.companies.getCompany(companyId)).data?.attributes;
1606
+ if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
1607
+ let loc = null;
1608
+ if (options.locationName) {
1609
+ loc = await this.c.locations.findLocation(companyId, options.locationName);
1610
+ } else {
1611
+ for await (const row of this.c.locations.iterCompanyLocations(companyId, { isActive: true })) {
1612
+ loc = row;
1613
+ break;
1614
+ }
1615
+ }
1616
+ if (!loc?.id) throw new NotFoundError(404, "NOT_FOUND", "The company has no matching active location.");
1617
+ const locationId = loc.id;
1618
+ const ma = await this.c.groups.findGroup(locationId, MANAGER_ALERTS_GROUP);
1619
+ const iha = await this.c.groups.findGroup(locationId, INSIGHTS_HUB_ACCESS_GROUP);
1620
+ const upset = await this.c.firstAlert.findRule(locationId, UPSET_CUSTOMER_RULE);
1621
+ const threat = await this.c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE);
1622
+ const conn = await this.bestConnector(locationId);
1623
+ return {
1624
+ companyId,
1625
+ companyName: company.company_name ?? "",
1626
+ locationId,
1627
+ locationName: loc.location_name ?? "",
1628
+ groups: { managerAlerts: ma?.id ?? null, insightsHubAccess: iha?.id ?? null },
1629
+ rules: { upsetCustomer: upset?.id ?? null, customerThreat: threat?.id ?? null },
1630
+ connectorId: conn?.id ?? null,
1631
+ connectorStatus: conn?.status ?? null,
1632
+ connectorStateReason: conn?.state_reason ?? null
1633
+ };
1634
+ }
1635
+ /**
1636
+ * Create (or finish) a Base Intelligence Seat customer. Idempotent: objects that already exist
1637
+ * (found by name) are kept, so a re-run completes a half-built customer.
1638
+ */
1639
+ async provisionSeatCustomer(spec) {
1640
+ const c = this.c;
1641
+ if (!spec?.companyName || !spec.primaryAdmin || !spec.location?.name) {
1642
+ throw new FilterError("companyName, primaryAdmin and location are required.");
1643
+ }
1644
+ const phrases = [...spec.threatPhrases ?? []];
1645
+ const created = [];
1646
+ const existing = [];
1647
+ const partial = { created, existing };
1648
+ const resellerId = spec.resellerId ?? await step("whoami", partial, async () => {
1649
+ const me = await c.whoami();
1650
+ if (!me.reseller_id) throw new IntelligenceCloudError("This login has no reseller id; pass resellerId.");
1651
+ return me.reseller_id;
1652
+ });
1653
+ let company;
1654
+ if (spec.companyId) {
1655
+ const id = spec.companyId;
1656
+ company = await step("get_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes ?? null);
1657
+ if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
1658
+ } else {
1659
+ const sameName = await step("find_company", partial, () => c.companies.findCompanies(resellerId, spec.companyName));
1660
+ const want = norm(spec.primaryAdmin.email);
1661
+ const matches = [];
1662
+ for (const row of sameName) {
1663
+ if (!row.id) continue;
1664
+ const id = row.id;
1665
+ const detail = await step("find_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes);
1666
+ if (detail && norm(detail.primary_admin_contact_email) === want) matches.push(detail);
1667
+ }
1668
+ if (sameName.length && matches.length !== 1) {
1669
+ throw new ConflictError(409, "company_name_conflict", companyNameConflictMessage(spec.companyName));
1670
+ }
1671
+ company = matches[0] ?? null;
1672
+ }
1673
+ if (company?.id && company.is_active === false) {
1674
+ if (!spec.reactivate) {
1675
+ throw new FilterError("The company exists but is deactivated. Set reactivate: true to reactivate it.");
1676
+ }
1677
+ const id = company.id;
1678
+ await step("reactivate_company", partial, () => c.companies.reactivateCompany(id));
1679
+ }
1680
+ if (!company && phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1681
+ if (!company) {
1682
+ company = await step("create_company", partial, async () => {
1683
+ const r = await c.companies.createCompany(resellerId, {
1684
+ company_name: spec.companyName,
1685
+ company_code: spec.companyCode,
1686
+ primary_admin_contact_name: spec.primaryAdmin.name,
1687
+ primary_admin_contact_email: spec.primaryAdmin.email,
1688
+ primary_admin_contact_phone: spec.primaryAdmin.phone,
1689
+ enabled_products: ALL_PRODUCTS
1690
+ });
1691
+ created.push("company");
1692
+ return r.data.attributes;
1693
+ });
1694
+ } else {
1695
+ existing.push("company");
1696
+ }
1697
+ const companyId = company.id;
1698
+ partial.companyId = companyId;
1699
+ if (spec.mfaOff) {
1700
+ await step("mfa_off", partial, async () => {
1701
+ const cur = (await c.companies.getCompany(companyId)).data?.attributes;
1702
+ if (cur?.mfa_enforced !== false) await c.companies.updateCompany(companyId, { mfa_enforced: false });
1703
+ const check = (await c.companies.getCompany(companyId)).data?.attributes;
1704
+ if (check?.mfa_enforced !== false) throw new IntelligenceCloudError("MFA is still on after the update.");
1705
+ });
1706
+ }
1707
+ await step("company_products", partial, () => c.companies.addProducts(companyId, ALL_PRODUCTS));
1708
+ let loc = await step("find_location", partial, () => c.locations.findLocation(companyId, spec.location.name));
1709
+ if (!loc) {
1710
+ loc = await step("create_location", partial, async () => {
1711
+ let verticalId = spec.location.verticalId;
1712
+ if (!verticalId) {
1713
+ const key = spec.location.verticalKey ?? DEFAULT_VERTICAL_KEY;
1714
+ const v = ((await c.locations.listVerticals()).data ?? []).find((x) => x.key === key);
1715
+ if (!v?.id) throw new IntelligenceCloudError(`No industry with key "${key}".`);
1716
+ verticalId = v.id;
1717
+ }
1718
+ const r = await c.locations.createLocation(companyId, {
1719
+ location_name: spec.location.name,
1720
+ street: spec.location.street,
1721
+ city: spec.location.city,
1722
+ state: spec.location.state,
1723
+ country: spec.location.country,
1724
+ zipcode: spec.location.zipcode,
1725
+ vertical_id: verticalId,
1726
+ enabled_products: ALL_PRODUCTS
1727
+ });
1728
+ created.push("location");
1729
+ return r.data.attributes;
1730
+ });
1731
+ } else {
1732
+ if (loc.is_active === false) {
1733
+ if (!spec.reactivate) {
1734
+ throw new FilterError("The location exists but is deactivated. Set reactivate: true to reactivate it.");
1735
+ }
1736
+ const lid = loc.id;
1737
+ await step("reactivate_location", partial, () => c.locations.reactivateLocation(companyId, lid));
1738
+ }
1739
+ await step("location_products", partial, () => c.locations.addProducts(companyId, loc.id, ALL_PRODUCTS));
1740
+ }
1741
+ const locationId = loc.id;
1742
+ partial.locationId = locationId;
1743
+ const ensureGroup = (name) => step(`group:${name}`, partial, async () => {
1744
+ const found = await c.groups.findGroup(locationId, name);
1745
+ if (found?.id) return found.id;
1746
+ const r = await c.groups.createUserGroup(locationId, { group_name: name });
1747
+ created.push(`group:${name}`);
1748
+ return r.data.attributes.id;
1749
+ });
1750
+ const managerAlerts = await ensureGroup(MANAGER_ALERTS_GROUP);
1751
+ const ihAccess = await ensureGroup(INSIGHTS_HUB_ACCESS_GROUP);
1752
+ partial.groups = { managerAlerts, insightsHubAccess: ihAccess };
1753
+ const ensureRule = (name, body) => step(`rule:${name}`, partial, async () => {
1754
+ const found = await c.firstAlert.findRule(locationId, name);
1755
+ if (!found?.id) {
1756
+ const r = await c.firstAlert.createAlertRule(locationId, body());
1757
+ created.push(`rule:${name}`);
1758
+ return r.data.attributes.id;
1759
+ }
1760
+ const rule = (await c.firstAlert.getAlertRule(locationId, found.id)).data?.attributes ?? {};
1761
+ if (!(rule.groups ?? []).some((g) => g.id === managerAlerts)) {
1762
+ await c.firstAlert.addRuleGroups(locationId, found.id, [managerAlerts]);
1763
+ }
1764
+ const want = body();
1765
+ if (want) {
1766
+ const cur = (rule.triggers ?? []).map((t) => ({ trigger_type: t.trigger_type, config: t.config }));
1767
+ if (canonical(cur) !== canonical(want.triggers)) {
1768
+ await c.firstAlert.updateAlertRule(locationId, found.id, { triggers: want.triggers });
1769
+ }
1770
+ }
1771
+ return found.id;
1772
+ });
1773
+ if (phrases.length === 0 && !await c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE)) {
1774
+ throw new FilterError(THREAT_PHRASES_MISSING);
1775
+ }
1776
+ const rules = {
1777
+ upsetCustomer: await ensureRule(UPSET_CUSTOMER_RULE, () => upsetCustomerRule([managerAlerts])),
1778
+ customerThreat: await ensureRule(
1779
+ CUSTOMER_THREAT_RULE,
1780
+ () => phrases.length ? customerThreatRule([managerAlerts], phrases) : null
1781
+ )
1782
+ };
1783
+ partial.rules = rules;
1784
+ await step("insights_hub", partial, async () => {
1785
+ const setup = (await c.insightsHub.getInsightsHubSetup(locationId)).data?.attributes;
1786
+ if (!(setup?.group_access ?? []).includes(ihAccess)) await c.insightsHub.addGroups(locationId, [ihAccess]);
1787
+ const cfg = (await c.insightsHub.getInsightsHubConfig(locationId)).data?.attributes;
1788
+ if (cfg?.monitor_all_numbers !== true) {
1789
+ await c.insightsHub.updateInsightsHubConfig(locationId, { monitor_all_numbers: true });
1790
+ }
1791
+ });
1792
+ let connectorId = null;
1793
+ let connectorStatus = null;
1794
+ let connectorStateReason = null;
1795
+ if (spec.connector) {
1796
+ const cs = spec.connector;
1797
+ const name = cs.name ?? `${spec.location.name} - NetSapiens`;
1798
+ const conn = await step("connector", partial, async () => {
1799
+ let byDomain = null;
1800
+ let byName = null;
1801
+ for await (const row of c.connectors.iterLocationConnectors(locationId)) {
1802
+ if (!row.id) continue;
1803
+ const detail = (await c.connectors.getConnector(locationId, row.id)).data ?? row;
1804
+ const rank = (x) => x ? CONNECTOR_RANK[x.status ?? ""] ?? 9 : 99;
1805
+ if (norm(detail.config?.domain) === norm(cs.domain) && rank(detail) < rank(byDomain)) byDomain = detail;
1806
+ if (detail.name === name && rank(detail) < rank(byName)) byName = detail;
1807
+ }
1808
+ const found = byDomain ?? byName;
1809
+ const wait = { timeout: cs.timeout };
1810
+ try {
1811
+ if (!found?.id) {
1812
+ const r = await c.connectors.createConnector(
1813
+ locationId,
1814
+ { name, type: "netsapiens", config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1815
+ wait
1816
+ );
1817
+ created.push("connector");
1818
+ return r.data ?? null;
1819
+ }
1820
+ existing.push("connector");
1821
+ const fid = found.id;
1822
+ const unchanged = found.name === name && found.config?.api_url === cs.apiUrl && norm(found.config?.domain) === norm(cs.domain);
1823
+ if (unchanged && found.status === "active") return found;
1824
+ if (unchanged && found.status === "connecting") {
1825
+ return await c.connectors.waitForStatus(locationId, fid, ["active", "error"], wait);
1826
+ }
1827
+ await c.connectors.updateConnector(
1828
+ locationId,
1829
+ fid,
1830
+ { name, config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1831
+ { wait: false }
1832
+ );
1833
+ existing.push("connector:updated");
1834
+ if (found.status === "inactive") {
1835
+ return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
1836
+ }
1837
+ const settled = await c.connectors.waitForStatus(locationId, fid, ["active", "error", "inactive"], wait);
1838
+ if (settled.status === "active") return settled;
1839
+ if (settled.status !== "inactive") await c.connectors.deactivateConnector(locationId, fid, wait);
1840
+ return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
1841
+ } catch (err) {
1842
+ if (!(err instanceof ConnectorError)) throw err;
1843
+ if (!found) created.push("connector");
1844
+ return err.connector ?? null;
1845
+ }
1846
+ });
1847
+ connectorId = conn?.id ?? null;
1848
+ connectorStatus = conn?.status ?? null;
1849
+ connectorStateReason = conn?.state_reason ?? null;
1850
+ partial.connectorId = connectorId;
1851
+ if (connectorId && connectorStatus === "active" && cs.monitoredNumbers?.length) {
1852
+ await step("monitored_numbers", partial, async () => {
1853
+ await c.firstAlert.addMonitoredNumbers(locationId, connectorId, cs.monitoredNumbers);
1854
+ await c.insightsHub.addNumbers(locationId, connectorId, cs.monitoredNumbers);
1855
+ });
1856
+ }
1857
+ } else {
1858
+ const found = await step("connector", partial, () => this.bestConnector(locationId));
1859
+ connectorId = found?.id ?? null;
1860
+ connectorStatus = found?.status ?? null;
1861
+ connectorStateReason = found?.state_reason ?? null;
1862
+ }
1863
+ let ssoTxtRecord = null;
1864
+ if (spec.sso?.domain) {
1865
+ ssoTxtRecord = await step("sso_domain", partial, async () => {
1866
+ const d = (await c.sso.claimCompanyDomain(companyId, { domain: spec.sso.domain })).data;
1867
+ return { type: d?.verification?.type ?? "TXT", name: d?.verification?.name ?? "", value: d?.verification?.value ?? "" };
1868
+ });
1869
+ }
1870
+ return {
1871
+ companyId,
1872
+ companyName: spec.companyName,
1873
+ locationId,
1874
+ locationName: spec.location.name,
1875
+ groups: { managerAlerts, insightsHubAccess: ihAccess },
1876
+ rules,
1877
+ connectorId,
1878
+ connectorStatus,
1879
+ connectorStateReason,
1880
+ created,
1881
+ existing,
1882
+ ssoTxtRecord
1883
+ };
1884
+ }
1885
+ /**
1886
+ * Switch on the customer's two alert rules (Upset Customer, Customer Threat). Rules already on are
1887
+ * left as they are. Returns the ids of the rules this call switched on.
1888
+ */
1889
+ async activateSeatAlerts(ref) {
1890
+ const c = this.c;
1891
+ const customer = await this.resolve(ref);
1892
+ const switched = [];
1893
+ await step("activate_alerts", { switched }, async () => {
1894
+ for (const id of [customer.rules.upsetCustomer, customer.rules.customerThreat]) {
1895
+ if (!id) continue;
1896
+ const r = (await c.firstAlert.getAlertRule(customer.locationId, id)).data?.attributes;
1897
+ if (r?.enabled !== true) {
1898
+ await c.firstAlert.updateAlertRule(customer.locationId, id, { enabled: true });
1899
+ switched.push(id);
1900
+ }
1901
+ }
1902
+ });
1903
+ return switched;
1904
+ }
1905
+ /**
1906
+ * End user: create (or find) the user without an invitation (frontline, After Call only, at the
1907
+ * location), alert email off, map their extension, then add the extension to every manager's
1908
+ * mapping and to the First Alert and Insights Hub numbers, and last email the invitation (unless
1909
+ * `user.sendInvitation` is false). A refused mapping stops before managers, First Alert and
1910
+ * Insights Hub are touched and throws ExtensionMappingError; no invitation has been sent.
1911
+ */
1912
+ async addFrontlineUser(ref, user, extension) {
1913
+ const c = this.c;
1914
+ const ext = String(extension ?? "").trim();
1915
+ if (!ext) throw new FilterError("extension is required.");
1916
+ const customer = await this.resolve(ref);
1917
+ if (!customer.connectorId) throw new FilterError("This customer has no connector; add one before adding end users.");
1918
+ const connectorId = customer.connectorId;
1919
+ const partial = {};
1920
+ const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1921
+ partial.userId = userId;
1922
+ await step("enable_after_call", partial, () => c.products.enableUserProduct(customer.locationId, userId, "after-call-copilot"));
1923
+ await step(
1924
+ "alert_email_off",
1925
+ partial,
1926
+ () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
1927
+ );
1928
+ await step("map_extension", partial, () => this.mapNumbers(customer, userId, [ext]));
1929
+ const managersUpdated = [];
1930
+ partial.managersUpdated = managersUpdated;
1931
+ await step("managers", partial, async () => {
1932
+ for (const m of await this.lineHolders(customer)) {
1933
+ if (m.id === userId) continue;
1934
+ const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
1935
+ if (cur.includes(ext)) continue;
1936
+ await this.mapNumbers(customer, m.id, [...cur, ext]);
1937
+ managersUpdated.push(m.id);
1938
+ }
1939
+ });
1940
+ await step("first_alert_numbers", partial, () => c.firstAlert.addMonitoredNumbers(customer.locationId, connectorId, [ext]));
1941
+ await step("insights_hub_numbers", partial, () => c.insightsHub.addNumbers(customer.locationId, connectorId, [ext]));
1942
+ const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1943
+ return {
1944
+ userId,
1945
+ email: user.email,
1946
+ kind: "frontline",
1947
+ extensions: [ext],
1948
+ managersUpdated,
1949
+ created,
1950
+ invited,
1951
+ alertsActivated: []
1952
+ };
1953
+ }
1954
+ /**
1955
+ * Manager: create (or find) the user without an invitation, with After Call, First Alert and
1956
+ * Insights Hub at the location, both groups, alert email on for every rule they receive, and a
1957
+ * mapping of exactly the end-user lines at the location. The manager's own phone line is not
1958
+ * captured on the Seat: it is never mapped, nor added to First Alert or Insights Hub, and an
1959
+ * extension passed as the third argument throws FilterError. Then, with `activateAlerts`
1960
+ * (default true), switch the customer's two alert rules on (see activateSeatAlerts), and last
1961
+ * email the invitation (unless `user.sendInvitation` is false). A refused mapping throws
1962
+ * ExtensionMappingError: the rules stay as they were and no invitation has been sent.
1963
+ */
1964
+ async addManager(ref, user, options = {}) {
1965
+ const c = this.c;
1966
+ const opts = options ?? {};
1967
+ if (typeof opts !== "object" || Object.keys(opts).some((k) => k !== "activateAlerts")) {
1968
+ throw new FilterError("A manager's own phone line is not captured on the Seat: addManager takes no extension.");
1969
+ }
1970
+ const customer = await this.resolve(ref);
1971
+ const partial = {};
1972
+ const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1973
+ partial.userId = userId;
1974
+ await step("enable_products", partial, async () => {
1975
+ for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
1976
+ });
1977
+ await step("groups", partial, async () => {
1978
+ const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
1979
+ if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
1980
+ });
1981
+ await step("alert_email_on", partial, async () => {
1982
+ const prefs = await c.firstAlert.getAlertNotificationPreferences(customer.locationId, userId);
1983
+ const alerts = (prefs.emailNotifications?.alerts ?? []).filter((a) => a.alertId).map((a) => ({ alertId: a.alertId, emailEnabled: true }));
1984
+ await c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: true, alerts });
1985
+ });
1986
+ const lines = await step("read_lines", partial, () => this.locationLines(customer));
1987
+ const all = [...lines];
1988
+ if (all.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, all));
1989
+ const alertsActivated = opts.activateAlerts ?? true ? await this.activateSeatAlerts(customer) : [];
1990
+ partial.alertsActivated = alertsActivated;
1991
+ const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1992
+ return { userId, email: user.email, kind: "manager", extensions: all, managersUpdated: [], created, invited, alertsActivated };
1993
+ }
1994
+ /**
1995
+ * Integration user (reads calls, alerts and insights for another system; never a seat or a
1996
+ * manager): create (or find) the user without an invitation, tag it `department: "integration"`,
1997
+ * switch on After Call, First Alert and Insights Hub, add it to both groups, switch every alert
1998
+ * email off, map all lines, and last email the invitation (unless `user.sendInvitation` is false;
1999
+ * the person who holds the integration's password accepts it). Integration users keep every line
2000
+ * as end users come and go (like managers) and release no lines when removed. The user must sign
2001
+ * in with a password (`authMethod: "password"`). Never switches alerts on.
2002
+ */
2003
+ async addIntegrationUser(ref, user) {
2004
+ const c = this.c;
2005
+ if ((user?.authMethod ?? "password") !== "password") {
2006
+ throw new FilterError('An integration user signs in with a password (authMethod: "password").');
2007
+ }
2008
+ const customer = await this.resolve(ref);
2009
+ const partial = {};
2010
+ const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
2011
+ partial.userId = userId;
2012
+ await step(
2013
+ "tag_integration",
2014
+ partial,
2015
+ () => c.users.updateCompanyUser(customer.companyId, userId, { department: INTEGRATION_DEPARTMENT })
2016
+ );
2017
+ await step("enable_products", partial, async () => {
2018
+ for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
2019
+ });
2020
+ await step("groups", partial, async () => {
2021
+ const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
2022
+ if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
2023
+ });
2024
+ await step(
2025
+ "alert_email_off",
2026
+ partial,
2027
+ () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
2028
+ );
2029
+ const lines = await step("read_lines", partial, () => this.locationLines(customer));
2030
+ if (lines.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, lines));
2031
+ const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
2032
+ return { userId, email: user.email, kind: "integration", extensions: lines, managersUpdated: [], created, invited, alertsActivated: [] };
2033
+ }
2034
+ /** Move an end user from one extension to another: their mapping, every manager and integration user, First Alert, Insights Hub. */
2035
+ async changeUserExtension(ref, userId, oldExtension, newExtension) {
2036
+ const c = this.c;
2037
+ const oldExt = String(oldExtension ?? "").trim();
2038
+ const newExt = String(newExtension ?? "").trim();
2039
+ if (!oldExt || !newExt) throw new FilterError("oldExtension and newExtension are required.");
2040
+ const customer = await this.resolve(ref);
2041
+ const connectorId = this.requireConnector(customer);
2042
+ const swap = (cur) => [.../* @__PURE__ */ new Set([...cur.filter((n) => n !== oldExt), newExt])];
2043
+ const partial = { userId };
2044
+ await step(
2045
+ "user_mapping",
2046
+ partial,
2047
+ async () => this.mapNumbers(customer, userId, swap(await c.users.userNumbers(customer.companyId, userId, connectorId)))
2048
+ );
2049
+ const managersUpdated = [];
2050
+ partial.managersUpdated = managersUpdated;
2051
+ await step("managers", partial, async () => {
2052
+ for (const m of await this.lineHolders(customer)) {
2053
+ if (m.id === userId) continue;
2054
+ const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2055
+ const target = swap(cur);
2056
+ if (sameSet(cur, target)) continue;
2057
+ await this.mapNumbers(customer, m.id, target);
2058
+ managersUpdated.push(m.id);
2059
+ }
2060
+ });
2061
+ await step("first_alert_numbers", partial, async () => {
2062
+ const cfg = (await c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
2063
+ await c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, swap(numbersFor(cfg?.connector_mappings, connectorId)));
2064
+ });
2065
+ await step("insights_hub_numbers", partial, async () => {
2066
+ const setup = (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes;
2067
+ await c.insightsHub.setNumbers(customer.locationId, connectorId, swap(numbersFor(setup?.connector_mappings, connectorId)));
2068
+ });
2069
+ return { userId, oldExtension: oldExt, newExtension: newExt, managersUpdated };
2070
+ }
2071
+ /**
2072
+ * Remove a user, in this order: leave every group, clear their number mapping, take their line off
2073
+ * managers, integration users, First Alert and Insights Hub (unless `keepExtensions`), then
2074
+ * deactivate. Products are left as they are.
2075
+ *
2076
+ * Only an end user releases a line, and only a line no other end user at the location still
2077
+ * holds. Managers, integration users (`department: "integration"`), excluded users and any
2078
+ * non-manager holding more than one line release nothing: every other line stays where it is.
2079
+ */
2080
+ async removeUser(ref, userId, options = {}) {
2081
+ const c = this.c;
2082
+ const customer = await this.resolve(ref);
2083
+ const partial = { userId };
2084
+ const row = await step("read_user", partial, async () => (await c.users.getLocationUser(customer.locationId, userId)).data?.attributes ?? {});
2085
+ const detail = await step("read_user", partial, async () => (await c.users.getCompanyUser(customer.companyId, userId)).data?.attributes ?? {});
2086
+ const u = { enabledProducts: [...row.enabled_products ?? []], department: detail.department ?? null };
2087
+ const connectorId = customer.connectorId;
2088
+ const mappings = await step("read_mapping", partial, async () => (await c.users.getUserNumberMappings(customer.companyId, userId)).data ?? []);
2089
+ const own = connectorId ? numbersFor(mappings, connectorId) : [];
2090
+ const kind = isIntegration(u) || this.excluded(customer, userId, detail.email ?? row.email) ? "integration" : isManager(u) ? "manager" : own.length > 1 ? "integration" : "frontline";
2091
+ let release = [];
2092
+ if (kind === "frontline" && !options.keepExtensions && connectorId && own.length) {
2093
+ const held = /* @__PURE__ */ new Set();
2094
+ await step("read_end_user_lines", partial, async () => {
2095
+ for (const f of await this.listFrontlineUsers(customer)) {
2096
+ if (f.id === userId) continue;
2097
+ for (const n of await c.users.userNumbers(customer.companyId, f.id, connectorId)) held.add(n);
2098
+ }
2099
+ });
2100
+ release = own.filter((n) => !held.has(n));
2101
+ }
2102
+ await step("groups", partial, () => c.groups.removeUserFromGroups(customer.locationId, userId));
2103
+ if (mappings.length) {
2104
+ await step("clear_mapping", partial, () => c.users.setUserNumberMappings(customer.companyId, userId, { mappings: [] }));
2105
+ }
2106
+ const managersUpdated = [];
2107
+ if (release.length && connectorId) {
2108
+ partial.managersUpdated = managersUpdated;
2109
+ await step("managers", partial, async () => {
2110
+ for (const m of await this.lineHolders(customer)) {
2111
+ if (m.id === userId) continue;
2112
+ const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2113
+ if (!cur.some((n) => release.includes(n))) continue;
2114
+ await this.mapNumbers(customer, m.id, cur.filter((n) => !release.includes(n)));
2115
+ managersUpdated.push(m.id);
2116
+ }
2117
+ });
2118
+ await step("first_alert_numbers", partial, () => c.firstAlert.removeMonitoredNumbers(customer.locationId, connectorId, release));
2119
+ await step("insights_hub_numbers", partial, () => c.insightsHub.removeNumbers(customer.locationId, connectorId, release));
2120
+ }
2121
+ await step("deactivate", partial, async () => {
2122
+ try {
2123
+ await c.users.deactivateCompanyUser(customer.companyId, userId);
2124
+ } catch (err) {
2125
+ if (!(err instanceof ConflictError)) throw err;
2126
+ }
2127
+ });
2128
+ return { userId, kind, extensionsReleased: release, managersUpdated };
2129
+ }
2130
+ /** End users: invited or active frontline users with After Call only (integration and excluded users left out). */
2131
+ async listFrontlineUsers(ref) {
2132
+ const customer = await this.resolve(ref);
2133
+ return (await this.seatUsers(customer)).filter(isFrontline);
2134
+ }
2135
+ /** Managers: invited or active frontline users with After Call, First Alert and Insights Hub (integration and excluded users left out). */
2136
+ async listManagers(ref) {
2137
+ const customer = await this.resolve(ref);
2138
+ return (await this.seatUsers(customer)).filter(isManager);
2139
+ }
2140
+ /** Integration users at the location: users tagged `department: "integration"`. */
2141
+ async listIntegrationUsers(ref) {
2142
+ const customer = await this.resolve(ref);
2143
+ return (await this.seatUsers(customer)).filter(isIntegration);
2144
+ }
2145
+ /**
2146
+ * A customer leaves. In order: pause the After Call webhook (the address is kept; it can't be
2147
+ * deleted), clear the First Alert webhook address (numbers kept), deactivate the connector (which
2148
+ * stops call capture), deactivate the integration users, and deactivate the company (unless
2149
+ * `deactivateCompany: false`). Steps already done are skipped, so it is safe to run again.
2150
+ * Ask your Tresic contact about the retention of the customer's data.
2151
+ */
2152
+ async offboardCustomer(ref, options = {}) {
2153
+ const c = this.c;
2154
+ const customer = await this.resolve(ref);
2155
+ const loc = customer.locationId;
2156
+ const result = {
2157
+ webhookPaused: false,
2158
+ firstAlertWebhookCleared: false,
2159
+ connectorDeactivated: false,
2160
+ integrationUsersDeactivated: [],
2161
+ companyDeactivated: false
2162
+ };
2163
+ const partial = result;
2164
+ const already = (err) => {
2165
+ if (!(err instanceof ConflictError)) throw err;
2166
+ };
2167
+ await step("pause_after_call_webhook", partial, async () => {
2168
+ let hook = null;
2169
+ try {
2170
+ hook = (await c.webhooks.getAfterCallWebhook(loc)).data ?? null;
2171
+ } catch (err) {
2172
+ if (!(err instanceof NotFoundError)) throw err;
2173
+ }
2174
+ if (hook?.webhook_url && hook.enabled !== false) {
2175
+ await c.webhooks.saveAfterCallWebhook(loc, { webhook_url: hook.webhook_url, enabled: false });
2176
+ result.webhookPaused = true;
2177
+ }
2178
+ });
2179
+ await step("clear_first_alert_webhook", partial, async () => {
2180
+ const cfg = (await c.firstAlert.getFirstAlertConfig(loc)).data;
2181
+ if (cfg?.webhook_url) {
2182
+ await c.firstAlert.setWebhookUrl(loc, null);
2183
+ result.firstAlertWebhookCleared = true;
2184
+ }
2185
+ });
2186
+ await step("deactivate_connector", partial, async () => {
2187
+ const conn = customer.connectorId ? (await c.connectors.getConnector(loc, customer.connectorId)).data ?? null : await this.bestConnector(loc);
2188
+ if (conn?.id && conn.status !== "inactive" && conn.status !== "deactivating") {
2189
+ try {
2190
+ await c.connectors.deactivateConnector(loc, conn.id);
2191
+ result.connectorDeactivated = true;
2192
+ } catch (err) {
2193
+ already(err);
2194
+ }
2195
+ }
2196
+ });
2197
+ await step("deactivate_integration_users", partial, async () => {
2198
+ for (const u of await this.listIntegrationUsers(customer)) {
2199
+ try {
2200
+ await c.users.deactivateCompanyUser(customer.companyId, u.id);
2201
+ result.integrationUsersDeactivated.push(u.id);
2202
+ } catch (err) {
2203
+ already(err);
2204
+ }
2205
+ }
2206
+ });
2207
+ if (options.deactivateCompany ?? true) {
2208
+ await step("deactivate_company", partial, async () => {
2209
+ try {
2210
+ await c.companies.deactivateCompany(customer.companyId);
2211
+ result.companyDeactivated = true;
2212
+ } catch (err) {
2213
+ already(err);
2214
+ }
2215
+ });
2216
+ }
2217
+ return result;
2218
+ }
2219
+ /**
2220
+ * Recompute the union of end-user extensions (end users holding exactly one line) and push it to
2221
+ * every manager, integration user, First Alert and Insights Hub. Managers and integration users end up with exactly
2222
+ * these lines; any other number on their mapping is removed. `dryRun: true` returns the diff without writing.
2223
+ */
2224
+ async syncNumbers(ref, options = {}) {
2225
+ const c = this.c;
2226
+ const customer = await this.resolve(ref);
2227
+ const connectorId = this.requireConnector(customer);
2228
+ const partial = {};
2229
+ const lines = await step("read_frontline_numbers", partial, () => this.endUserLines(customer, connectorId));
2230
+ const union = [...lines].sort();
2231
+ const fa = await step(
2232
+ "read_first_alert",
2233
+ partial,
2234
+ async () => numbersFor((await c.firstAlert.getFirstAlertConfig(customer.locationId)).data?.connector_mappings, connectorId)
2235
+ );
2236
+ const ih = await step(
2237
+ "read_insights_hub",
2238
+ partial,
2239
+ async () => numbersFor(
2240
+ (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes?.connector_mappings,
2241
+ connectorId
2242
+ )
2243
+ );
2244
+ const managers = [];
2245
+ await step("read_managers", partial, async () => {
2246
+ for (const m of await this.lineHolders(customer)) {
2247
+ const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2248
+ const target = union;
2249
+ const d = diff(cur, target);
2250
+ if (d.add.length || d.remove.length) managers.push({ userId: m.id, ...d });
2251
+ }
2252
+ });
2253
+ const result = {
2254
+ dryRun: Boolean(options.dryRun),
2255
+ lines: union,
2256
+ managers,
2257
+ firstAlert: diff(fa, union),
2258
+ insightsHub: diff(ih, union)
2259
+ };
2260
+ if (options.dryRun) return result;
2261
+ await step("apply_managers", partial, async () => {
2262
+ for (const m of managers) {
2263
+ const cur = await c.users.userNumbers(customer.companyId, m.userId, connectorId);
2264
+ await this.mapNumbers(customer, m.userId, [...cur.filter((n) => !m.remove.includes(n)), ...m.add]);
2265
+ }
2266
+ });
2267
+ if (result.firstAlert.add.length || result.firstAlert.remove.length) {
2268
+ await step("apply_first_alert", partial, () => c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, union));
2269
+ }
2270
+ if (result.insightsHub.add.length || result.insightsHub.remove.length) {
2271
+ await step("apply_insights_hub", partial, () => c.insightsHub.setNumbers(customer.locationId, connectorId, union));
2272
+ }
2273
+ return result;
2274
+ }
2275
+ };
2276
+
2277
+ // src/client.ts
2278
+ function uniq(xs) {
2279
+ return [...new Set(xs)];
2280
+ }
2281
+ var Client = class {
2282
+ /** @internal transport, auth, retries, projection */
2283
+ core;
2284
+ resellers;
2285
+ companies;
2286
+ sso;
2287
+ products;
2288
+ locations;
2289
+ groups;
2290
+ connectors;
2291
+ firstAlert;
2292
+ insightsHub;
2293
+ users;
2294
+ afterCallSettings;
2295
+ account;
2296
+ calls;
2297
+ alerts;
2298
+ tasks;
2299
+ insights;
2300
+ webhooks;
2301
+ /** Conversation intelligence helpers (frontline credentials). */
2302
+ intelligence;
2303
+ /** Base Intelligence Seat workflows (admin credentials). */
2304
+ workflows;
2305
+ constructor(options) {
2306
+ const c = this.core = new Core(options);
2307
+ this.resellers = makeResellers(c);
2308
+ this.sso = makeSso(c);
2309
+ this.products = makeProducts(c);
2310
+ this.account = makeAccount(c);
2311
+ this.calls = makeCalls(c);
2312
+ this.alerts = makeAlerts(c);
2313
+ this.tasks = makeTasks(c);
2314
+ this.insights = makeInsights(c);
2315
+ this.webhooks = makeWebhooks(c);
2316
+ this.afterCallSettings = makeAfterCallSettings(c);
2317
+ const companies = makeCompanies(c);
2318
+ const companyProducts = async (companyId) => (await companies.getCompany(companyId)).data?.attributes?.enabled_products ?? [];
2319
+ this.companies = {
2320
+ ...companies,
2321
+ /** Turn products on for a company, keeping the others (`enabled_products` is a full replacement). */
2322
+ addProducts: async (companyId, productKeys) => {
2323
+ const cur = await companyProducts(companyId);
2324
+ const next = uniq([...cur, ...productKeys]);
2325
+ if (next.length === cur.length) return companies.getCompany(companyId);
2326
+ return companies.updateCompany(companyId, { enabled_products: next });
2327
+ },
2328
+ /** Turn products off for a company, keeping the others. A company keeps at least one product. */
2329
+ removeProducts: async (companyId, productKeys) => {
2330
+ const cur = await companyProducts(companyId);
2331
+ const next = cur.filter((k) => !productKeys.includes(k));
2332
+ if (next.length === 0) throw new FilterError("A company keeps at least one product; the API ignores an empty list.");
2333
+ if (next.length === cur.length) return companies.getCompany(companyId);
2334
+ return companies.updateCompany(companyId, { enabled_products: next });
2335
+ },
2336
+ /**
2337
+ * The first company with exactly this name (the list search is a prefix match), or null.
2338
+ * Company names are not unique: use `findCompanies` and check the contact email, or keep the id.
2339
+ */
2340
+ findCompany: async (resellerId, companyName) => {
2341
+ for await (const row of companies.iterCompanies(resellerId, { search: companyName })) {
2342
+ if (row.company_name === companyName) return row;
2343
+ }
2344
+ return null;
2345
+ },
2346
+ /** Every company with exactly this name under the reseller (names are not unique). */
2347
+ findCompanies: async (resellerId, companyName) => {
2348
+ const out = [];
2349
+ for await (const row of companies.iterCompanies(resellerId, { search: companyName })) {
2350
+ if (row.company_name === companyName) out.push(row);
2351
+ }
2352
+ return out;
2353
+ }
2354
+ };
2355
+ const locations = makeLocations(c);
2356
+ const locationProducts = async (companyId, locationId) => (await locations.getLocation(companyId, locationId)).data?.attributes?.enabled_products ?? [];
2357
+ this.locations = {
2358
+ ...locations,
2359
+ /** Turn products on for a location, keeping the others. They must be on for the company. */
2360
+ addProducts: async (companyId, locationId, productKeys) => {
2361
+ const cur = await locationProducts(companyId, locationId);
2362
+ const next = uniq([...cur, ...productKeys]);
2363
+ if (next.length === cur.length) return locations.getLocation(companyId, locationId);
2364
+ return locations.updateLocation(companyId, locationId, { enabled_products: next });
2365
+ },
2366
+ removeProducts: async (companyId, locationId, productKeys) => {
2367
+ const cur = await locationProducts(companyId, locationId);
2368
+ const next = cur.filter((k) => !productKeys.includes(k));
2369
+ if (next.length === cur.length) return locations.getLocation(companyId, locationId);
2370
+ return locations.updateLocation(companyId, locationId, { enabled_products: next });
2371
+ },
2372
+ /** The location with exactly this name, or null. */
2373
+ findLocation: async (companyId, locationName) => {
2374
+ for await (const row of locations.iterCompanyLocations(companyId, { search: locationName })) {
2375
+ if (row.location_name === locationName) return row;
2376
+ }
2377
+ return null;
2378
+ }
2379
+ };
2380
+ const groups = makeGroups(c);
2381
+ const memberIds = async (locationId, groupId) => ((await groups.getUserGroup(locationId, groupId)).data?.attributes?.members ?? []).map((m) => m.id).filter(Boolean);
2382
+ const userGroupIds = async (locationId, userId) => ((await groups.getUserGroupMembership(locationId, userId)).data ?? []).filter((g) => g.is_member).map((g) => g.id);
2383
+ this.groups = {
2384
+ ...groups,
2385
+ /** Add members to a group (`member_ids` is a full replacement underneath). */
2386
+ addMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, { member_ids: uniq([...await memberIds(locationId, groupId), ...userIds]) }),
2387
+ removeMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, {
2388
+ member_ids: (await memberIds(locationId, groupId)).filter((id) => !userIds.includes(id))
2389
+ }),
2390
+ /** Ids of the groups the user is in at this location. */
2391
+ userGroupIds,
2392
+ /** Add a user to groups at a location (`group_ids` is a full replacement underneath). */
2393
+ addUserToGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
2394
+ group_ids: uniq([...await userGroupIds(locationId, userId), ...groupIds])
2395
+ }),
2396
+ /** Remove a user from some groups, or from every group when `groupIds` is omitted. */
2397
+ removeUserFromGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
2398
+ group_ids: groupIds ? (await userGroupIds(locationId, userId)).filter((id) => !groupIds.includes(id)) : []
2399
+ }),
2400
+ /** The group with exactly this name at the location, or null. */
2401
+ findGroup: async (locationId, groupName) => {
2402
+ for await (const row of groups.iterUserGroups(locationId, { search: groupName })) {
2403
+ if (row.group_name === groupName) return row;
2404
+ }
2405
+ return null;
2406
+ }
2407
+ };
2408
+ const connectors = makeConnectors(c);
2409
+ const waitForStatus = async (locationId, connectorId, final, o = {}) => {
2410
+ const deadline = c.now() + (o.timeout ?? 600) * 1e3;
2411
+ for (; ; ) {
2412
+ const conn = (await connectors.getConnector(locationId, connectorId)).data ?? {};
2413
+ const st = conn.status ?? null;
2414
+ if (st === "error" && (o.raiseOnError ?? true) && !final.includes("error")) {
2415
+ throw new ConnectorError(
2416
+ `Connector is in error${conn.state_reason ? ` (${conn.state_reason})` : ""}.`,
2417
+ conn.state_reason ?? null,
2418
+ st,
2419
+ conn
2420
+ );
2421
+ }
2422
+ if (st && final.includes(st)) return conn;
2423
+ if (c.now() >= deadline) {
2424
+ throw new ConnectorError(`Connector did not settle in time (status ${st ?? "unknown"}).`, null, st, conn);
2425
+ }
2426
+ await c.sleep((o.checkInterval ?? 10) * 1e3);
2427
+ }
2428
+ };
2429
+ const settle = async (locationId, first, final, o, raiseOnError = true) => {
2430
+ if (o.wait === false || !first.data?.id) return first;
2431
+ return { data: await waitForStatus(locationId, first.data.id, final, { ...o, raiseOnError }) };
2432
+ };
2433
+ this.connectors = {
2434
+ ...connectors,
2435
+ waitForStatus,
2436
+ /**
2437
+ * Create a connector (202) and, by default, wait until it is `active`.
2438
+ * Throws `ConnectorError` with `stateReason` (e.g. `invalid_permissions`) when it ends in `error`.
2439
+ */
2440
+ createConnector: async (locationId, body, o = {}) => settle(locationId, await connectors.createConnector(locationId, body), ["active"], o),
2441
+ /** Update a connector; when it reconnects (202), wait until it is `active`. */
2442
+ updateConnector: async (locationId, connectorId, body, o = {}) => {
2443
+ const r = await connectors.updateConnector(locationId, connectorId, body);
2444
+ return r.data?.status === "connecting" ? settle(locationId, r, ["active"], o) : r;
2445
+ },
2446
+ /** Restart a connector and, by default, wait until it is `active` (ConnectorError on `error`). */
2447
+ reactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.reactivateConnector(locationId, connectorId), ["active"], o),
2448
+ /** Stop a connector and, by default, wait until it is `inactive`. */
2449
+ deactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.deactivateConnector(locationId, connectorId), ["inactive"], o, false),
2450
+ /** The connector with exactly this name at the location, or null. */
2451
+ findConnector: async (locationId, name) => {
2452
+ for await (const row of connectors.iterLocationConnectors(locationId, { search: name })) {
2453
+ if (row.name === name) return row;
2454
+ }
2455
+ return null;
2456
+ }
2457
+ };
2458
+ const firstAlert = makeFirstAlert(c);
2459
+ const faSave = async (locationId, change) => {
2460
+ const cfg = (await firstAlert.getFirstAlertConfig(locationId)).data ?? {};
2461
+ return firstAlert.saveFirstAlertConfig(locationId, change(cfg));
2462
+ };
2463
+ const ruleGroupIds = async (locationId, ruleId) => ((await firstAlert.getAlertRule(locationId, ruleId)).data?.attributes?.groups ?? []).map((g) => g.id).filter(Boolean);
2464
+ this.firstAlert = {
2465
+ ...firstAlert,
2466
+ /** Add monitored numbers for one connector, keeping the webhook URL and every other number. */
2467
+ addMonitoredNumbers: (locationId, connectorId, numbers) => faSave(locationId, (cfg) => ({
2468
+ webhook_url: cfg.webhook_url ?? null,
2469
+ connector_mappings: mergeMappings(cfg.connector_mappings, connectorId, numbers)
2470
+ })),
2471
+ removeMonitoredNumbers: (locationId, connectorId, numbers) => faSave(locationId, (cfg) => ({
2472
+ webhook_url: cfg.webhook_url ?? null,
2473
+ connector_mappings: mergeMappings(cfg.connector_mappings, connectorId, [], numbers)
2474
+ })),
2475
+ /** Replace the monitored numbers of one connector; other connectors and the webhook URL are kept. */
2476
+ setMonitoredNumbers: (locationId, connectorId, numbers) => faSave(locationId, (cfg) => ({
2477
+ webhook_url: cfg.webhook_url ?? null,
2478
+ connector_mappings: mergeMappings(
2479
+ (cfg.connector_mappings ?? []).filter((m) => m.connector_id !== connectorId),
2480
+ connectorId,
2481
+ numbers
2482
+ )
2483
+ })),
2484
+ /** Set (null clears) the location alert webhook URL, keeping the monitored numbers. */
2485
+ setWebhookUrl: (locationId, url) => faSave(locationId, (cfg) => ({ webhook_url: url, connector_mappings: mergeMappings(cfg.connector_mappings, "") })),
2486
+ /** Route a rule to more groups (`group_ids` is a full replacement underneath). */
2487
+ addRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, { group_ids: uniq([...await ruleGroupIds(locationId, ruleId), ...groupIds]) }),
2488
+ removeRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, {
2489
+ group_ids: (await ruleGroupIds(locationId, ruleId)).filter((id) => !groupIds.includes(id))
2490
+ }),
2491
+ /** The rule with exactly this name at the location, or null. */
2492
+ findRule: async (locationId, name) => {
2493
+ for await (const row of firstAlert.iterAlertRules(locationId)) {
2494
+ if (row.name === name) return row;
2495
+ }
2496
+ return null;
2497
+ }
2498
+ };
2499
+ const insightsHub = makeInsightsHub(c);
2500
+ const ihSetup = async (locationId) => (await insightsHub.getInsightsHubSetup(locationId)).data?.attributes ?? {};
2501
+ this.insightsHub = {
2502
+ ...insightsHub,
2503
+ /** Add numbers to the location's Insights Hub for one connector (read, merge, PATCH). */
2504
+ addNumbers: async (locationId, connectorId, numbers) => insightsHub.updateInsightsHubSetup(locationId, {
2505
+ connector_mappings: mergeMappings((await ihSetup(locationId)).connector_mappings, connectorId, numbers)
2506
+ }),
2507
+ removeNumbers: async (locationId, connectorId, numbers) => insightsHub.updateInsightsHubSetup(locationId, {
2508
+ connector_mappings: mergeMappings((await ihSetup(locationId)).connector_mappings, connectorId, [], numbers)
2509
+ }),
2510
+ setNumbers: async (locationId, connectorId, numbers) => insightsHub.updateInsightsHubSetup(locationId, {
2511
+ connector_mappings: mergeMappings(
2512
+ ((await ihSetup(locationId)).connector_mappings ?? []).filter((m) => m.connector_id !== connectorId),
2513
+ connectorId,
2514
+ numbers
2515
+ )
2516
+ }),
2517
+ /** Give groups Insights Hub access, keeping the others. Saves the setup (upsert) so it works on a new location. */
2518
+ addGroups: async (locationId, groupIds) => {
2519
+ const cur = await ihSetup(locationId);
2520
+ return insightsHub.saveInsightsHubSetup(locationId, {
2521
+ connector_mappings: mergeMappings(cur.connector_mappings, ""),
2522
+ group_access: uniq([...cur.group_access ?? [], ...groupIds])
2523
+ });
2524
+ },
2525
+ removeGroups: async (locationId, groupIds) => insightsHub.updateInsightsHubSetup(locationId, {
2526
+ group_access: ((await ihSetup(locationId)).group_access ?? []).filter((g) => !groupIds.includes(g))
2527
+ })
2528
+ };
2529
+ const users = makeUsers(c);
2530
+ const findUserByEmail = async (companyId, email) => {
2531
+ const want = email.trim().toLowerCase();
2532
+ for await (const row of users.iterCompanyUsers(companyId, { search: email.trim() })) {
2533
+ if ((row.email ?? "").toLowerCase() === want) return row;
2534
+ }
2535
+ return null;
2536
+ };
2537
+ const currentMappings = async (companyId, userId) => (await users.getUserNumberMappings(companyId, userId)).data ?? [];
2538
+ const userLocationIds = async (companyId, userId) => ((await users.getCompanyUser(companyId, userId)).data?.attributes?.locations ?? []).map((l) => l.location_id).filter(Boolean);
2539
+ this.users = {
2540
+ ...users,
2541
+ /**
2542
+ * Create a user. Always sends an `Idempotency-Key` (a new UUID unless you pass one), reused on
2543
+ * retries. A 422 can leave the user behind: the SDK then finds the user by email and applies
2544
+ * `location_ids` (and role) with PATCH, returning the user. The one-time sign-in link the API
2545
+ * may include is never returned.
2546
+ */
2547
+ createCompanyUser: async (companyId, body, o = {}) => {
2548
+ const key = o.idempotencyKey ?? await uuid4();
2549
+ try {
2550
+ return await c.call("createCompanyUser", [companyId], { body, idempotencyKey: key });
2551
+ } catch (err) {
2552
+ if (!(err instanceof ValidationError) || err.status !== 422 || !body.email) throw err;
2553
+ const found = await findUserByEmail(companyId, body.email);
2554
+ if (!found?.id) throw err;
2555
+ const patch = { role: body.role };
2556
+ if (body.location_ids?.length) patch.location_ids = body.location_ids;
2557
+ try {
2558
+ return await users.updateCompanyUser(companyId, found.id, patch);
2559
+ } catch {
2560
+ throw err;
2561
+ }
2562
+ }
2563
+ },
2564
+ /** The user with exactly this email, or null. */
2565
+ findUserByEmail,
2566
+ /** Assign the user to more locations (`location_ids` is a full replacement underneath). */
2567
+ addLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, { location_ids: uniq([...await userLocationIds(companyId, userId), ...locationIds]) }),
2568
+ removeLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, {
2569
+ location_ids: (await userLocationIds(companyId, userId)).filter((id) => !locationIds.includes(id))
2570
+ }),
2571
+ /** The numbers mapped to the user (for one connector, or all). */
2572
+ userNumbers: async (companyId, userId, connectorId) => {
2573
+ const cur = await currentMappings(companyId, userId);
2574
+ return connectorId ? numbersFor(cur, connectorId) : uniq(cur.flatMap((m) => m.monitored_numbers ?? []));
2575
+ },
2576
+ /** Map more numbers to the user for one connector (read, merge, PUT). The connector must be `active`. */
2577
+ addNumbers: async (companyId, userId, connectorId, numbers) => users.setUserNumberMappings(companyId, userId, {
2578
+ mappings: mergeMappings(await currentMappings(companyId, userId), connectorId, numbers)
2579
+ }),
2580
+ removeNumbers: async (companyId, userId, connectorId, numbers) => users.setUserNumberMappings(companyId, userId, {
2581
+ mappings: mergeMappings(await currentMappings(companyId, userId), connectorId, [], numbers)
2582
+ }),
2583
+ /** Replace the user's numbers on one connector; other connectors are kept. */
2584
+ setNumbers: async (companyId, userId, connectorId, numbers) => users.setUserNumberMappings(companyId, userId, {
2585
+ mappings: mergeMappings(
2586
+ (await currentMappings(companyId, userId)).filter((m) => m.connector_id !== connectorId),
2587
+ connectorId,
2588
+ numbers
2589
+ )
2590
+ }),
2591
+ /** Swap one number for another in the user's mapping, in a single write. */
2592
+ replaceNumber: async (companyId, userId, connectorId, oldNumber, newNumber) => users.setUserNumberMappings(companyId, userId, {
2593
+ mappings: mergeMappings(await currentMappings(companyId, userId), connectorId, [newNumber], [oldNumber])
2594
+ })
2595
+ };
2596
+ this.intelligence = new Intelligence(this, options.checkRole ?? true);
2597
+ this.workflows = new Workflows(this);
2598
+ }
2599
+ // ================================================================ session
2600
+ /** Ends ALL sessions of this user (web app and other jobs too). The SDK never calls it on its own. */
2601
+ logout() {
2602
+ return this.core.logout();
2603
+ }
2604
+ /** Forget this client's tokens. Does not sign out on the server. */
2605
+ close() {
2606
+ return this.core.close();
2607
+ }
2608
+ // ================================================================ intelligence shortcuts
2609
+ whoami() {
2610
+ return this.intelligence.whoami();
2611
+ }
2612
+ requireFrontline() {
2613
+ return this.intelligence.requireFrontline();
2614
+ }
2615
+ searchCalls(filters) {
2616
+ return this.intelligence.searchCalls(filters);
2617
+ }
2618
+ iterCalls(filters) {
2619
+ return this.intelligence.iterCalls(filters);
2620
+ }
2621
+ getCall(callId) {
2622
+ return this.intelligence.getCall(callId);
2623
+ }
2624
+ getTranscript(callId) {
2625
+ return this.intelligence.getTranscript(callId);
2626
+ }
2627
+ getRecordingUrl(callId) {
2628
+ return this.intelligence.getRecordingUrl(callId);
2629
+ }
2630
+ searchAlerts(filters) {
2631
+ return this.intelligence.searchAlerts(filters);
2632
+ }
2633
+ iterAlerts(filters) {
2634
+ return this.intelligence.iterAlerts(filters);
2635
+ }
2636
+ getAlert(alertId, options) {
2637
+ return this.intelligence.getAlert(alertId, options);
2638
+ }
2639
+ getAlertsDashboard(filters) {
2640
+ return this.intelligence.getAlertsDashboard(filters);
2641
+ }
2642
+ listTasks(filters) {
2643
+ return this.intelligence.listTasks(filters);
2644
+ }
2645
+ iterTasks(filters) {
2646
+ return this.intelligence.iterTasks(filters);
2647
+ }
2648
+ getInsightsDashboard(filters) {
2649
+ return this.intelligence.getInsightsDashboard(filters);
2650
+ }
2651
+ listTopicCalls(slug, filters) {
2652
+ return this.intelligence.listTopicCalls(slug, filters);
2653
+ }
2654
+ iterTopicCalls(slug, filters) {
2655
+ return this.intelligence.iterTopicCalls(slug, filters);
2656
+ }
2657
+ getAfterCallWebhook(locationId) {
2658
+ return this.intelligence.getAfterCallWebhook(locationId);
2659
+ }
2660
+ setAfterCallWebhook(locationId, url, enabled = true) {
2661
+ return this.intelligence.setAfterCallWebhook(locationId, url, enabled);
2662
+ }
2663
+ testAfterCallWebhook(locationId) {
2664
+ return this.intelligence.testAfterCallWebhook(locationId);
2665
+ }
2666
+ getFirstAlertWebhook(locationId) {
2667
+ return this.intelligence.getFirstAlertWebhook(locationId);
2668
+ }
2669
+ setFirstAlertWebhook(locationId, url) {
2670
+ return this.intelligence.setFirstAlertWebhook(locationId, url);
2671
+ }
2672
+ testFirstAlertWebhook(locationId, url) {
2673
+ return this.intelligence.testFirstAlertWebhook(locationId, url);
2674
+ }
2675
+ // ================================================================ workflow shortcuts
2676
+ provisionSeatCustomer(...a) {
2677
+ return this.workflows.provisionSeatCustomer(...a);
2678
+ }
2679
+ getSeatCustomer(...a) {
2680
+ return this.workflows.getSeatCustomer(...a);
2681
+ }
2682
+ addFrontlineUser(...a) {
2683
+ return this.workflows.addFrontlineUser(...a);
2684
+ }
2685
+ addManager(...a) {
2686
+ return this.workflows.addManager(...a);
2687
+ }
2688
+ activateSeatAlerts(...a) {
2689
+ return this.workflows.activateSeatAlerts(...a);
2690
+ }
2691
+ changeUserExtension(...a) {
2692
+ return this.workflows.changeUserExtension(...a);
2693
+ }
2694
+ removeUser(...a) {
2695
+ return this.workflows.removeUser(...a);
2696
+ }
2697
+ listFrontlineUsers(...a) {
2698
+ return this.workflows.listFrontlineUsers(...a);
2699
+ }
2700
+ listManagers(...a) {
2701
+ return this.workflows.listManagers(...a);
2702
+ }
2703
+ addIntegrationUser(...a) {
2704
+ return this.workflows.addIntegrationUser(...a);
2705
+ }
2706
+ listIntegrationUsers(...a) {
2707
+ return this.workflows.listIntegrationUsers(...a);
2708
+ }
2709
+ offboardCustomer(...a) {
2710
+ return this.workflows.offboardCustomer(...a);
2711
+ }
2712
+ syncNumbers(...a) {
2713
+ return this.workflows.syncNumbers(...a);
2714
+ }
2715
+ };
2716
+
2717
+ // src/webhooks.ts
2718
+ var MAX_EVENT_BYTES = 262144;
2719
+ function isUnknownEvent(e) {
2720
+ return e.kind === "unknown";
2721
+ }
2722
+ function parseAfterCallEvent(body, options = {}) {
2723
+ const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
2724
+ let obj = body;
2725
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
2726
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
2727
+ if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
2728
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
2729
+ try {
2730
+ obj = JSON.parse(text);
2731
+ } catch {
2732
+ throw new WebhookPayloadError("Body is not JSON.");
2733
+ }
2734
+ }
2735
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
2736
+ const o = obj;
2737
+ if (o.type !== "end_of_call_summary") {
2738
+ return {
2739
+ kind: "unknown",
2740
+ type: typeof o.type === "string" ? o.type : null,
2741
+ version: typeof o.version === "string" ? o.version : null,
2742
+ raw: o
2743
+ };
2744
+ }
2745
+ if (typeof o.version !== "string" || !o.version.startsWith("1.")) {
2746
+ throw new WebhookPayloadError("Unsupported event version.");
2747
+ }
2748
+ if (!o.call || typeof o.call !== "object" || typeof o.call.id !== "string" || !o.call.id) {
2749
+ throw new WebhookPayloadError("Event has no call.id.");
2750
+ }
2751
+ if (typeof o.location_id !== "string") throw new WebhookPayloadError("Event has no location_id.");
2752
+ const event = project(o, WEBHOOK_SHAPES.afterCallSummary);
2753
+ return { ...event, is_test: o.is_test === true };
2754
+ }
2755
+ var MemoryDedupStore = class {
2756
+ constructor(maxSize = 1e4) {
2757
+ this.maxSize = maxSize;
2758
+ }
2759
+ maxSize;
2760
+ keys = /* @__PURE__ */ new Map();
2761
+ checkAndAdd(key) {
2762
+ if (this.keys.has(key)) {
2763
+ this.keys.delete(key);
2764
+ this.keys.set(key, true);
2765
+ return true;
2766
+ }
2767
+ this.keys.set(key, true);
2768
+ if (this.keys.size > this.maxSize) {
2769
+ const oldest = this.keys.keys().next().value;
2770
+ if (oldest !== void 0) this.keys.delete(oldest);
2771
+ }
2772
+ return false;
2773
+ }
2774
+ };
2775
+ var Deduplicator = class {
2776
+ store;
2777
+ constructor(options = {}) {
2778
+ this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
2779
+ }
2780
+ /** True if this id was seen before. The first call for an id records it and returns false. */
2781
+ async isDuplicate(id) {
2782
+ return Boolean(await this.store.checkAndAdd(id));
2783
+ }
2784
+ /** @deprecated Use `isDuplicate` (same result). */
2785
+ seen(id) {
2786
+ return this.isDuplicate(id);
2787
+ }
2788
+ };
2789
+
2790
+ exports.ALL_PRODUCTS = ALL_PRODUCTS;
2791
+ exports.ALWAYS_REMOVED_FIELDS = ALWAYS_REMOVED_FIELDS;
2792
+ exports.ApiError = ApiError;
2793
+ exports.AuthError = AuthError;
2794
+ exports.CUSTOMER_THREAT_RULE = CUSTOMER_THREAT_RULE;
2795
+ exports.Client = Client;
2796
+ exports.ConflictError = ConflictError;
2797
+ exports.ConnectorError = ConnectorError;
2798
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
2799
+ exports.Deduplicator = Deduplicator;
2800
+ exports.EXTENSION_CONFLICT_MESSAGE = EXTENSION_CONFLICT_MESSAGE;
2801
+ exports.ExtensionMappingError = ExtensionMappingError;
2802
+ exports.FileTokenStore = FileTokenStore;
2803
+ exports.FilterError = FilterError;
2804
+ exports.FrontlineRequiredError = FrontlineRequiredError;
2805
+ exports.INSIGHTS_HUB_ACCESS_GROUP = INSIGHTS_HUB_ACCESS_GROUP;
2806
+ exports.INTEGRATION_DEPARTMENT = INTEGRATION_DEPARTMENT;
2807
+ exports.Intelligence = Intelligence;
2808
+ exports.IntelligenceCloudError = IntelligenceCloudError;
2809
+ exports.MANAGER_ALERTS_GROUP = MANAGER_ALERTS_GROUP;
2810
+ exports.MAX_EVENT_BYTES = MAX_EVENT_BYTES;
2811
+ exports.MAX_LOCATION_IDS = MAX_LOCATION_IDS;
2812
+ exports.MAX_NUMBERS = MAX_NUMBERS;
2813
+ exports.MAX_RETRY_AFTER_MS = MAX_RETRY_AFTER_MS;
2814
+ exports.MemoryDedupStore = MemoryDedupStore;
2815
+ exports.MemoryTokenStore = MemoryTokenStore;
2816
+ exports.MfaRequiredError = MfaRequiredError;
2817
+ exports.NotFoundError = NotFoundError;
2818
+ exports.PasswordExpiredError = PasswordExpiredError;
2819
+ exports.PayloadTooLargeError = PayloadTooLargeError;
2820
+ exports.RateLimitError = RateLimitError;
2821
+ exports.SDK_VERSION = SDK_VERSION;
2822
+ exports.THREAT_PHRASES_MISSING = THREAT_PHRASES_MISSING;
2823
+ exports.UPSET_CUSTOMER_RULE = UPSET_CUSTOMER_RULE;
2824
+ exports.ValidationError = ValidationError;
2825
+ exports.WebhookPayloadError = WebhookPayloadError;
2826
+ exports.WorkflowError = WorkflowError;
2827
+ exports.Workflows = Workflows;
2828
+ exports.alertNumber = alertNumber;
2829
+ exports.companyNameConflictMessage = companyNameConflictMessage;
2830
+ exports.customerThreatRule = customerThreatRule;
2831
+ exports.digitsOnly = digitsOnly;
2832
+ exports.isFrontline = isFrontline;
2833
+ exports.isIntegration = isIntegration;
2834
+ exports.isManager = isManager;
2835
+ exports.isUnknownEvent = isUnknownEvent;
2836
+ exports.parseAfterCallEvent = parseAfterCallEvent;
2837
+ exports.toRfc3339 = toRfc3339;
2838
+ exports.upsetCustomerRule = upsetCustomerRule;