@ecodrix/erix-api 3.0.0 → 3.1.1

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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import qe from"repl";import{Command as Ue}from"commander";import Ve from"dotenv";import o from"picocolors";import _e from"axios";import Ce from"axios-retry";var oe="https://api.ecodrix.com";function Se(r="v1",e=oe){return`${e.replace(/\/+$/,"")}/${r}/api`}var ce=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends ce{status;code;constructor(e,t,n){super(e),this.name="APIError",this.status=t,this.code=n}},h=class extends m{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},x=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var i=class{constructor(e){this.client=e}client;async post(e,t,n){try{let s=this.buildConfig(n);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let n=this.buildConfig(t);return(await this.client.get(e,n)).data}catch(n){this.handleError(n)}}async patch(e,t,n){try{let s=this.buildConfig(n);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,n){try{let s=this.buildConfig(n);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let n=this.buildConfig(t);return(await this.client.delete(e,n)).data}catch(n){this.handleError(n)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){if(e.response){let t=e.response.status,n=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new h(n);case 403:throw new h(n);case 429:throw new x(n);default:throw new m(n,t,s)}}throw new m(e.message||"Network Error")}};var pe=class extends i{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},w=class extends i{notes;constructor(e){super(e),this.notes=new pe(e)}async timeline(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/product/erix/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/product/erix/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/product/erix/crm/leads/${e}/calls`,t)}};var k=class extends i{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var v=class extends i{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,n){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,n?{fileUrl:n}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var R=class extends i{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var Me=["open","won","lost","archived"],P=class extends i{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],n=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:Me.map(a=>({label:`${a.charAt(0).toUpperCase()}${a.slice(1)}`,value:a}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(a=>({key:`metadata.extra.${a.name}`,label:a.label||a.name,type:a.type||"string",required:!!a.required,options:a.options,group:"Custom Fields"}));return{name:"Lead",fields:[...n,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let n=[];for(let s=0;s<e.length;s+=t){let c=e.slice(s,s+t).map(u=>this.create(u)),g=await Promise.allSettled(c);for(let u of g)if(u.status==="fulfilled")n.push(u.value);else throw u.reason}return n}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t={...e};return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,n=!0;for(;n;){let s=await this.list({...e,page:t}),a=Array.isArray(s.data)?s.data:s||[];if(a.length===0){n=!1;break}for(let c of a)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&a.length>0?t++:n=!1}}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,n={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:n})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,n){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:n})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,n){return this.patch(`/product/erix/crm/notes/${t}`,n)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var A=class extends i{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var I=class extends i{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:n.map(s=>({key:s._id,label:s.name,type:"string",required:!0,options:[{label:s.name,value:s._id}],group:"Stages",uiHints:{color:s.color||"#cbd5e1",probability:s.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var S=class extends i{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var C=class extends i{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){return this.post("/platform/inbox/conversations",{address:e.phone,channel:e.channel??"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var T=class extends i{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){let n=t.fileName??e.name??"file",s=e.type||"application/octet-stream",a=await this.post("/infra/storage/files/upload-url",{folder:t.folder??"inbox",filename:n,contentType:s}),{uploadUrl:c,key:g}=a.data,u=await fetch(c,{method:"PUT",headers:{"Content-Type":s},body:e});if(!u.ok)throw new Error(`upload failed (${u.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:g,sizeBytes:e.size}),{key:g,mimeType:s,fileName:n}}};var $=class extends i{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var E=class extends i{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var O=class extends i{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var D=class extends i{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var M=class extends i{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,n){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:n})}async addSigner(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,n)}async sign(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,n??{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,n)}};var L=class extends i{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var N=class extends i{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var _=class extends i{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var q=class extends i{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var U=class extends i{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let n=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(n,t):this.get(n)}async preview(e,t,n,s){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:n,onEmptyVariable:s})}async getVariableManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let a of n)if(a.text){let c=a.text.match(/{{(\d+)}}/g);if(c)for(let g of c){let u=g.replace(/{{|}}/g,"");s.push({key:`var_${u}`,label:`${a.type} Var {{${u}}}`,type:"string",required:!0,group:a.type,description:`Variable placeholder in template ${a.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import Le from"axios";var V=class extends i{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let n=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:s,key:a}=n.data;await Le.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:a,sizeBytes:c})}};var B=class extends i{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},F=class extends i{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var K=class extends i{async system(){return(await this.get("/health")).data}};var j=class extends i{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var W=class extends i{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var H=class extends i{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){return(await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t}))?.data??{entries:[],hasMore:!1}}async followups(e){return(await super.get(`/platform/tenants/persona/${e}/followups`))?.data?.entries??[]}};var le=class extends i{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},z=class{copilot;constructor(e){this.copilot=new le(e)}};var Y=class extends i{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",{kind:"text",...e})}async addUrl(e){return this.post("/platform/knowledge/sources",{kind:"url",...e})}async addFile(e,t={}){let n=await new T(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:n.key,mimeType:n.mimeType,title:t.title??n.fileName??"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",{query:e,...t?{limit:t}:{}})}};var Q=class extends i{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,n){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:n})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var G=class extends i{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var ue=class extends i{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},ge=class extends i{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},de=class extends i{async listPublic(){return this.get("/platform/billing/plans/public")}},me=class extends i{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},ye=class extends i{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},he=class extends i{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},J=class{entitlements;subscriptions;plans;checkout;user;credits;constructor(e){this.entitlements=new ue(e),this.subscriptions=new ge(e),this.plans=new de(e),this.checkout=new me(e),this.user=new ye(e),this.credits=new he(e)}};var X=class extends i{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var Z=class extends i{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},ee=class extends i{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},te=class extends i{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var fe=class{messages;conversations;constructor(e){this.messages=new T(e),this.conversations=new C(e)}},Te=class{leads;pipelines;activities;analytics;scoring;payments;chat;events;invoices;checkout;projects;niche;documents;invoiceExport;ai;constructor(e){this.leads=new P(e),this.pipelines=new I(e),this.activities=new w(e),this.analytics=new k(e),this.scoring=new S(e),this.payments=new A(e),this.chat=new fe(e),this.events=new E(e),this.invoices=new O(e),this.checkout=new $(e),this.projects=new M(e),this.niche=new D(e),this.documents=new v(e),this.invoiceExport=new R(e),this.ai=new Q(e)}},ne=class{erix;constructor(e){this.erix=new Te(e)}},be=class{config;templates;constructor(e){this.config=new q(e),this.templates=new N(e)}},xe=class{templates;constructor(e){this.templates=new U(e)}},we=class{email;whatsapp;meet;connections;constructor(e){this.email=new be(e),this.whatsapp=new xe(e),this.meet=new _(e),this.connections=new L(e)}},ke=class{files;folders;media;constructor(e){this.files=new F(e),this.folders=new B(e),this.media=new V(e)}},re=class{connect;storage;constructor(e){this.connect=new we(e),this.storage=new ke(e)}},ve=class{onboarding;persona;constructor(e){this.onboarding=new W(e),this.persona=new H(e)}},Re=class{me;members;sessions;notifications;constructor(e){this.me=new Z(e),this.members=new ee(e),this.sessions=new te(e),this.notifications=new j(e)}},se=class{auth;users;tenants;billing;support;ai;knowledge;health;constructor(e){this.auth=new G(e),this.users=new Re(e),this.tenants=new ve(e),this.billing=new J(e),this.support=new X(e),this.ai=new z(e),this.knowledge=new Y(e),this.health=new K(e)}};var b=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},ie=class{async constructEvent(e,t,n){if(!t)throw new b("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let a=await import("crypto"),g=a.createHmac("sha256",n).update(e).digest("hex");if(!a.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new b("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(a){throw a instanceof b?a:new b(`Webhook payload parsing failed: ${a.message}`)}}};var Pe=typeof process<"u"&&"3.0.0"||"2.0.0";var Ae=Ce.default??Ce,ae=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;apiVersion;platform;product;infra;webhooks;constructor(e){let t=e.proxy;if(!e.apiKey&&!t)throw new h("API Key is required");this.clientCode=e.clientCode?.toUpperCase(),this.apiVersion=e.version??"v1";let n=e.baseUrl??oe,s=Se(this.apiVersion,t?.url??n),a=e.socketUrl||n,c=typeof window<"u"&&typeof window.document<"u",g=c?"browser":typeof process<"u"?`node ${process.version}`:"unknown",u=c?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",Oe={...t?{}:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""},"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Pe,runtime:g,os:u})};if(this.client=_e.create({baseURL:s,headers:Oe,timeout:e.timeout??3e4}),Ae(this.client,{retries:3,retryDelay:Ae.exponentialDelay,retryCondition:d=>Ae.isNetworkOrIdempotentRequestError(d)||d.response?.status===429,onRetry:(d,De,Ie)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${d}/3): ${Ie.method?.toUpperCase()} ${Ie.url}. Reason: ${De.message}`)}}),this.platform=new se(this.client),this.product=new ne(this.client),this.infra=new re(this.client),this.webhooks=new ie,t){if(t.ticket){let d=t.ticket;this.initSocket(a,async()=>({ticket:await d()}))}}else{let d={apiKey:e.apiKey,clientCode:e.clientCode?.toUpperCase()||""};this.initSocket(a,async()=>d,{"x-api-key":d.apiKey,"x-client-code":d.clientCode})}if(c){let d={version:Pe,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=d}}initSocket(e,t,n){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{auth:a=>{t().then(c=>a({...c,lastSeq:this.lastSeq}),()=>a({lastSeq:this.lastSeq}))},extraHeaders:n}),this.setupSocket();for(let{type:a,args:c}of this.socketQueue)a==="joinRoom"?this.socket.emit("join-room",c[0]):a==="leaveRoom"?this.socket.emit("leave-room",c[0]):a==="on"?this.socket.on(c[0],c[1]):a==="off"?this.socket.off(c[0],c[1]):a==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}lastSeq;setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{this.socket?.active||setTimeout(()=>{this.closed||this.socket?.connect()},5e3)}),this.socket.onAny((...e)=>{let t=e.at(-1)?.seq;typeof t=="number"&&t>(this.lastSeq??0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}closed=!1;disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,n,s){try{return(await this.client.request({method:e,url:t,data:n,params:s})).data}catch(a){throw a.response?new m(a.response.data?.message||a.response.data?.error||"Raw Execution Failed",a.response.status,a.response.data?.code):new m(a.message||"Network Error")}}};Ve.config();var $e="3.0.0";var Be="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",y=new Ue;y.name("erix").description(Be).version($e);function f(r){let e=r.key||process.env.ECOD_API_KEY,t=r.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(o.red("Error: API Key is missing.")),console.log(o.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new ae({apiKey:e,clientCode:t,baseUrl:r.baseUrl||process.env.ECOD_BASE_URL})}y.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");y.command("whoami").description("Verify current authentication and tenant status").action(async(r,e)=>{let t=e.parent.opts(),n=f(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await n.request("GET","/api/saas/me/profile");console.log(o.green("\u2714 Authenticated successfully!")),console.log(`${o.bold("User ID:")} ${s.id}`),console.log(`${o.bold("Organisation:")} ${s.organisation?.name||"N/A"}`),t.client&&console.log(`${o.bold("Tenant Code:")} ${o.magenta(t.client)}`)}catch(s){console.error(o.red("\u2716 Authentication failed")),console.error(o.dim(s.message)),process.exit(1)}});var Fe=y.command("whatsapp").description("WhatsApp Business API operations");Fe.command("send-template").description("Send a WhatsApp template message").argument("<phone>","Recipient phone number").argument("<template>","Template name").option("-v, --vars <json>","Template variables as JSON string","[]").action(async(r,e,t,n)=>{let s=n.parent.parent.opts(),a=f(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${r}...`));let g=await a.product.erix.chat.messages.sendTemplate({to:r,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var Ee=y.command("crm").description("CRM and Lead management");Ee.command("leads").description("List recent leads").option("-l, --limit <number>","Number of leads to fetch","10").option("-s, --status <status>","Filter by lead status").option("-p, --pipeline <id>","Filter by pipeline ID").option("-q, --search <query>","Search by name or email").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{let s=Number.parseInt(r.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let a={limit:s};r.status&&(a.status=r.status),r.pipeline&&(a.pipelineId=r.pipeline),r.search&&(a.search=r.search);let c=await n.product.erix.leads.list(a),g=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(u=>({ID:u.id||u._id,Name:`${u.firstName} ${u.lastName||""}`.trim(),Phone:u.phone,Status:u.status,Score:u.score||0,Created:new Date(u.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});Ee.command("pipelines").description("List all CRM pipelines").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await n.product.erix.pipelines.list(),a=s.data||s||[];if(a.length===0){console.log(o.yellow("No pipelines found."));return}console.table(a.map(c=>({ID:c.id||c._id,Name:c.name,Default:c.isDefault?"Yes":"No",Stages:c.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var Ke=y.command("analytics").description("Business Intelligence Analytics");Ke.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{console.log(o.cyan(`Fetching overview metrics for last ${r.range}...`));let s=await n.product.erix.analytics.overview({range:r.range}),a=s.data||s;console.log(`
2
+ import qe from"repl";import{Command as Ue}from"commander";import Ve from"dotenv";import o from"picocolors";import _e from"axios";import Ce from"axios-retry";var oe="https://api.ecodrix.com";function Se(r="v1",e=oe){return`${e.replace(/\/+$/,"")}/${r}/api`}var ce=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends ce{status;code;constructor(e,t,n){super(e),this.name="APIError",this.status=t,this.code=n}},h=class extends m{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},x=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var i=class{constructor(e){this.client=e}client;async post(e,t,n){try{let s=this.buildConfig(n);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let n=this.buildConfig(t);return(await this.client.get(e,n)).data}catch(n){this.handleError(n)}}async patch(e,t,n){try{let s=this.buildConfig(n);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,n){try{let s=this.buildConfig(n);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let n=this.buildConfig(t);return(await this.client.delete(e,n)).data}catch(n){this.handleError(n)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){if(e.response){let t=e.response.status,n=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new h(n);case 403:throw new h(n);case 429:throw new x(n);default:throw new m(n,t,s)}}throw new m(e.message||"Network Error")}};var le=class extends i{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},w=class extends i{notes;constructor(e){super(e),this.notes=new le(e)}async timeline(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/product/erix/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/product/erix/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/product/erix/crm/leads/${e}/calls`,t)}};var k=class extends i{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var v=class extends i{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,n){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,n?{fileUrl:n}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var R=class extends i{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var Me=["open","won","lost","archived"],P=class extends i{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],n=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:Me.map(a=>({label:`${a.charAt(0).toUpperCase()}${a.slice(1)}`,value:a}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(a=>({key:`metadata.extra.${a.name}`,label:a.label||a.name,type:a.type||"string",required:!!a.required,options:a.options,group:"Custom Fields"}));return{name:"Lead",fields:[...n,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let n=[];for(let s=0;s<e.length;s+=t){let c=e.slice(s,s+t).map(u=>this.create(u)),g=await Promise.allSettled(c);for(let u of g)if(u.status==="fulfilled")n.push(u.value);else throw u.reason}return n}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t={...e};return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,n=!0;for(;n;){let s=await this.list({...e,page:t}),a=Array.isArray(s.data)?s.data:s||[];if(a.length===0){n=!1;break}for(let c of a)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&a.length>0?t++:n=!1}}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,n={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:n})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async setFollowUp(e,t,n){return this.patch(`/product/erix/crm/leads/${e}`,{nextFollowUpAt:t,nextFollowUpNote:t?n??null:null})}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,n){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:n})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,n){return this.patch(`/product/erix/crm/notes/${t}`,n)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var A=class extends i{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var I=class extends i{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:n.map(s=>({key:s._id,label:s.name,type:"string",required:!0,options:[{label:s.name,value:s._id}],group:"Stages",uiHints:{color:s.color||"#cbd5e1",probability:s.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var S=class extends i{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var C=class extends i{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){return this.post("/platform/inbox/conversations",{address:e.phone,channel:e.channel??"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var T=class extends i{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){let n=t.fileName??e.name??"file",s=e.type||"application/octet-stream",a=await this.post("/infra/storage/files/upload-url",{folder:t.folder??"inbox",filename:n,contentType:s}),{uploadUrl:c,key:g}=a.data,u=await fetch(c,{method:"PUT",headers:{"Content-Type":s},body:e});if(!u.ok)throw new Error(`upload failed (${u.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:g,sizeBytes:e.size}),{key:g,mimeType:s,fileName:n}}};var $=class extends i{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var E=class extends i{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var O=class extends i{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var D=class extends i{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var M=class extends i{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,n){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:n})}async addSigner(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,n)}async sign(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,n??{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,n){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,n)}};var L=class extends i{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var N=class extends i{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var _=class extends i{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var q=class extends i{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var U=class extends i{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let n=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(n,t):this.get(n)}async preview(e,t,n,s){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:n,onEmptyVariable:s})}async getVariableManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let a of n)if(a.text){let c=a.text.match(/{{(\d+)}}/g);if(c)for(let g of c){let u=g.replace(/{{|}}/g,"");s.push({key:`var_${u}`,label:`${a.type} Var {{${u}}}`,type:"string",required:!0,group:a.type,description:`Variable placeholder in template ${a.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import Le from"axios";var V=class extends i{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let n=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:s,key:a}=n.data;await Le.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:a,sizeBytes:c})}};var B=class extends i{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},F=class extends i{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var K=class extends i{async system(){return(await this.get("/health")).data}};var j=class extends i{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var W=class extends i{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var H=class extends i{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){return(await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t}))?.data??{entries:[],hasMore:!1}}async followups(e){return(await super.get(`/platform/tenants/persona/${e}/followups`))?.data?.entries??[]}};var pe=class extends i{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},z=class{copilot;constructor(e){this.copilot=new pe(e)}};var Y=class extends i{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",{kind:"text",...e})}async addUrl(e){return this.post("/platform/knowledge/sources",{kind:"url",...e})}async addFile(e,t={}){let n=await new T(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:n.key,mimeType:n.mimeType,title:t.title??n.fileName??"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",{query:e,...t?{limit:t}:{}})}};var G=class extends i{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,n){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:n})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async agents(){return this.get("/product/flow/agents")}async updateAgent(e,t){return this.patch(`/product/flow/agents/${encodeURIComponent(e)}`,t)}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var Q=class extends i{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var ue=class extends i{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},ge=class extends i{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},de=class extends i{async listPublic(){return this.get("/platform/billing/plans/public")}},me=class extends i{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},ye=class extends i{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},he=class extends i{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},J=class{entitlements;subscriptions;plans;checkout;user;credits;constructor(e){this.entitlements=new ue(e),this.subscriptions=new ge(e),this.plans=new de(e),this.checkout=new me(e),this.user=new ye(e),this.credits=new he(e)}};var X=class extends i{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var Z=class extends i{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},ee=class extends i{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async updateRole(e,t){return this.patch(`/platform/users/members/${e}`,{role:t})}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},te=class extends i{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var fe=class{messages;conversations;constructor(e){this.messages=new T(e),this.conversations=new C(e)}},Te=class{leads;pipelines;activities;analytics;scoring;payments;chat;events;invoices;checkout;projects;niche;documents;invoiceExport;ai;constructor(e){this.leads=new P(e),this.pipelines=new I(e),this.activities=new w(e),this.analytics=new k(e),this.scoring=new S(e),this.payments=new A(e),this.chat=new fe(e),this.events=new E(e),this.invoices=new O(e),this.checkout=new $(e),this.projects=new M(e),this.niche=new D(e),this.documents=new v(e),this.invoiceExport=new R(e),this.ai=new G(e)}},ne=class{erix;constructor(e){this.erix=new Te(e)}},be=class{config;templates;constructor(e){this.config=new q(e),this.templates=new N(e)}},xe=class{templates;constructor(e){this.templates=new U(e)}},we=class{email;whatsapp;meet;connections;constructor(e){this.email=new be(e),this.whatsapp=new xe(e),this.meet=new _(e),this.connections=new L(e)}},ke=class{files;folders;media;constructor(e){this.files=new F(e),this.folders=new B(e),this.media=new V(e)}},re=class{connect;storage;constructor(e){this.connect=new we(e),this.storage=new ke(e)}},ve=class{onboarding;persona;constructor(e){this.onboarding=new W(e),this.persona=new H(e)}},Re=class{me;members;sessions;notifications;constructor(e){this.me=new Z(e),this.members=new ee(e),this.sessions=new te(e),this.notifications=new j(e)}},se=class{auth;users;tenants;billing;support;ai;knowledge;health;constructor(e){this.auth=new Q(e),this.users=new Re(e),this.tenants=new ve(e),this.billing=new J(e),this.support=new X(e),this.ai=new z(e),this.knowledge=new Y(e),this.health=new K(e)}};var b=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},ie=class{async constructEvent(e,t,n){if(!t)throw new b("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let a=await import("crypto"),g=a.createHmac("sha256",n).update(e).digest("hex");if(!a.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new b("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(a){throw a instanceof b?a:new b(`Webhook payload parsing failed: ${a.message}`)}}};var Pe=typeof process<"u"&&"3.1.1"||"2.0.0";var Ae=Ce.default??Ce,ae=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;apiVersion;platform;product;infra;webhooks;constructor(e){let t=e.proxy;if(!e.apiKey&&!t)throw new h("API Key is required");this.clientCode=e.clientCode?.toUpperCase(),this.apiVersion=e.version??"v1";let n=e.baseUrl??oe,s=Se(this.apiVersion,t?.url??n),a=e.socketUrl||n,c=typeof window<"u"&&typeof window.document<"u",g=c?"browser":typeof process<"u"?`node ${process.version}`:"unknown",u=c?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",Oe={...t?{}:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""},"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Pe,runtime:g,os:u})};if(this.client=_e.create({baseURL:s,headers:Oe,timeout:e.timeout??3e4}),Ae(this.client,{retries:3,retryDelay:Ae.exponentialDelay,retryCondition:d=>Ae.isNetworkOrIdempotentRequestError(d)||d.response?.status===429,onRetry:(d,De,Ie)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${d}/3): ${Ie.method?.toUpperCase()} ${Ie.url}. Reason: ${De.message}`)}}),this.platform=new se(this.client),this.product=new ne(this.client),this.infra=new re(this.client),this.webhooks=new ie,t){if(t.ticket){let d=t.ticket;this.initSocket(a,async()=>({ticket:await d()}))}}else{let d={apiKey:e.apiKey,clientCode:e.clientCode?.toUpperCase()||""};this.initSocket(a,async()=>d,{"x-api-key":d.apiKey,"x-client-code":d.clientCode})}if(c){let d={version:Pe,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=d}}initSocket(e,t,n){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{auth:a=>{t().then(c=>a({...c,lastSeq:this.lastSeq}),()=>a({lastSeq:this.lastSeq}))},extraHeaders:n}),this.setupSocket();for(let{type:a,args:c}of this.socketQueue)a==="joinRoom"?this.socket.emit("join-room",c[0]):a==="leaveRoom"?this.socket.emit("leave-room",c[0]):a==="on"?this.socket.on(c[0],c[1]):a==="off"?this.socket.off(c[0],c[1]):a==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}lastSeq;setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{this.socket?.active||setTimeout(()=>{this.closed||this.socket?.connect()},5e3)}),this.socket.onAny((...e)=>{let t=e.at(-1)?.seq;typeof t=="number"&&t>(this.lastSeq??0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}closed=!1;disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,n,s){try{return(await this.client.request({method:e,url:t,data:n,params:s})).data}catch(a){throw a.response?new m(a.response.data?.message||a.response.data?.error||"Raw Execution Failed",a.response.status,a.response.data?.code):new m(a.message||"Network Error")}}};Ve.config();var $e="3.1.1";var Be="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",y=new Ue;y.name("erix").description(Be).version($e);function f(r){let e=r.key||process.env.ECOD_API_KEY,t=r.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(o.red("Error: API Key is missing.")),console.log(o.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new ae({apiKey:e,clientCode:t,baseUrl:r.baseUrl||process.env.ECOD_BASE_URL})}y.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");y.command("whoami").description("Verify current authentication and tenant status").action(async(r,e)=>{let t=e.parent.opts(),n=f(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await n.request("GET","/api/saas/me/profile");console.log(o.green("\u2714 Authenticated successfully!")),console.log(`${o.bold("User ID:")} ${s.id}`),console.log(`${o.bold("Organisation:")} ${s.organisation?.name||"N/A"}`),t.client&&console.log(`${o.bold("Tenant Code:")} ${o.magenta(t.client)}`)}catch(s){console.error(o.red("\u2716 Authentication failed")),console.error(o.dim(s.message)),process.exit(1)}});var Fe=y.command("whatsapp").description("WhatsApp Business API operations");Fe.command("send-template").description("Send a WhatsApp template message").argument("<phone>","Recipient phone number").argument("<template>","Template name").option("-v, --vars <json>","Template variables as JSON string","[]").action(async(r,e,t,n)=>{let s=n.parent.parent.opts(),a=f(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${r}...`));let g=await a.product.erix.chat.messages.sendTemplate({to:r,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var Ee=y.command("crm").description("CRM and Lead management");Ee.command("leads").description("List recent leads").option("-l, --limit <number>","Number of leads to fetch","10").option("-s, --status <status>","Filter by lead status").option("-p, --pipeline <id>","Filter by pipeline ID").option("-q, --search <query>","Search by name or email").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{let s=Number.parseInt(r.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let a={limit:s};r.status&&(a.status=r.status),r.pipeline&&(a.pipelineId=r.pipeline),r.search&&(a.search=r.search);let c=await n.product.erix.leads.list(a),g=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(u=>({ID:u.id||u._id,Name:`${u.firstName} ${u.lastName||""}`.trim(),Phone:u.phone,Status:u.status,Score:u.score||0,Created:new Date(u.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});Ee.command("pipelines").description("List all CRM pipelines").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await n.product.erix.pipelines.list(),a=s.data||s||[];if(a.length===0){console.log(o.yellow("No pipelines found."));return}console.table(a.map(c=>({ID:c.id||c._id,Name:c.name,Default:c.isDefault?"Yes":"No",Stages:c.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var Ke=y.command("analytics").description("Business Intelligence Analytics");Ke.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(r,e)=>{let t=e.parent.parent.opts(),n=f(t);try{console.log(o.cyan(`Fetching overview metrics for last ${r.range}...`));let s=await n.product.erix.analytics.overview({range:r.range}),a=s.data||s;console.log(`
3
3
  ${o.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${o.green(a.totalLeads||0)}`),console.log(`Open Value: ${o.yellow(`$${(a.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${o.green(`$${(a.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${o.blue(a.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${o.magenta(`${(a.conversionRate||0).toFixed(2)}%`)}
4
4
  `)}catch(s){console.error(o.red("\u2716 Failed to fetch analytics overview")),console.error(o.dim(s.message))}});var je=y.command("webhooks").description("Webhook utility tools");je.command("verify").description("Verify a cryptographic webhook signature").argument("<payload>","The raw request body string").argument("<signature>","The 'x-ecodrix-signature' header value").argument("<secret>","Your webhook signing secret").action(async(r,e,t,n,s)=>{let a=s.parent.parent.opts(),c=f(a);try{await c.webhooks.constructEvent(r,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(g){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(g.message))}});y.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(r,e)=>{let t=e.parent.opts(),n=f(t);console.log(o.magenta(o.bold(`
5
5
  Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${$e}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
@@ -1 +1 @@
1
- "use strict";var nt=Object.create;var M=Object.defineProperty,rt=Object.defineProperties,st=Object.getOwnPropertyDescriptor,it=Object.getOwnPropertyDescriptors,at=Object.getOwnPropertyNames,He=Object.getOwnPropertySymbols,ot=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var pt=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var Pe=(n,e,t)=>e in n?M(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y=(n,e)=>{for(var t in e||(e={}))ze.call(e,t)&&Pe(n,t,e[t]);if(He)for(var t of He(e))ct.call(e,t)&&Pe(n,t,e[t]);return n},k=(n,e)=>rt(n,it(e));var lt=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of at(e))!ze.call(n,s)&&s!==t&&M(n,s,{get:()=>e[s],enumerable:!(r=st(e,s))||r.enumerable});return n};var F=(n,e,t)=>(t=n!=null?nt(ot(n)):{},Ge(e||!n||!n.__esModule?M(t,"default",{value:n,enumerable:!0}):t,n)),gt=n=>Ge(M({},"__esModule",{value:!0}),n);var a=(n,e,t)=>Pe(n,typeof e!="symbol"?e+"":e,t);var ve=function(n,e){this[0]=n,this[1]=e},Qe=(n,e,t)=>{var r=(g,l,h,d)=>{try{var b=t[g](l),w=(l=b.value)instanceof ve,P=b.done;Promise.resolve(w?l[0]:l).then(m=>w?r(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:P})).catch(m=>r("throw",m,h,d))}catch(m){d(m)}},s=(g,l,h,d)=>p[g]=b=>(l=new Promise((w,P,m)=>(m=()=>r(g,b,w,P),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,p={};return t=t.apply(n,e),p[pt("asyncIterator")]=()=>p,s("next"),s("throw"),s("return"),p};var Tt={};lt(Tt,{APIError:()=>u,APIResource:()=>i,AiAgent:()=>S,AuthenticationError:()=>f,ConnectInfra:()=>N,ECODrIx:()=>R,ECODrIxAPI:()=>R,ERROR_RETRY_CONFIG:()=>_e,EcodrixError:()=>W,EmailConnect:()=>q,ErixChat:()=>B,ErixProduct:()=>L,HTTP_STATUS_ERROR_MAP:()=>tt,InfraDomain:()=>$,KNOWLEDGE_FILE_TYPES:()=>Xe,Knowledge:()=>I,LEAD_STATUS_VALUES:()=>Ie,Onboarding:()=>A,Persona:()=>C,PlatformDomain:()=>O,PlatformTenants:()=>U,PlatformUsers:()=>K,ProductDomain:()=>E,RateLimitError:()=>x,StorageInfra:()=>V,WhatsAppConnect:()=>_,default:()=>ht,getErrorDetails:()=>yt,getRetryConfig:()=>ft,handleAPIError:()=>dt,isAPIError:()=>mt});module.exports=gt(Tt);var et=F(require("axios"),1),qe=F(require("axios-retry"),1);var Ae="https://api.ecodrix.com";function Ye(n="v1",e=Ae){return`${e.replace(/\/+$/,"")}/${n}/api`}var W=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends W{constructor(t,r,s){super(t);a(this,"status");a(this,"code");this.name="APIError",this.status=r,this.code=s}},f=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},x=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var i=class{constructor(e){a(this,"client",e)}async post(e,t,r){try{let s=this.buildConfig(r);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let r=this.buildConfig(t);return(await this.client.get(e,r)).data}catch(r){this.handleError(r)}}async patch(e,t,r){try{let s=this.buildConfig(r);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,r){try{let s=this.buildConfig(r);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let r=this.buildConfig(t);return(await this.client.delete(e,r)).data}catch(r){this.handleError(r)}}buildConfig(e){if(!e)return;let t=y({},e);return e.idempotencyKey&&(t.headers=k(y({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,r,s;if(e.response){let o=e.response.status,p=((t=e.response.data)==null?void 0:t.message)||((r=e.response.data)==null?void 0:r.error)||"API Request Failed",g=(s=e.response.data)==null?void 0:s.code;switch(o){case 401:throw new f(p);case 403:throw new f(p);case 429:throw new x(p);default:throw new u(p,o,g)}}throw new u(e.message||"Network Error")}};var Ce=class extends i{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},H=class extends i{constructor(t){super(t);a(this,"notes");this.notes=new Ce(t)}async timeline(t,r){return this.get(`/product/erix/crm/leads/${t}/timeline`,{params:r})}async list(t,r){return this.get(`/product/erix/crm/leads/${t}/activities`,{params:y({},r)})}async log(t){return this.post(`/product/erix/crm/leads/${t.leadId}/activities`,t)}async logCall(t,r){return this.post(`/product/erix/crm/leads/${t}/calls`,r)}};var z=class extends i{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var G=class extends i{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,r){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,r?{fileUrl:r}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var Q=class extends i{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var Ie=["open","won","lost","archived"],Y=class extends i{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],r=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:Ie.map(o=>({label:`${o.charAt(0).toUpperCase()}${o.slice(1)}`,value:o}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...r,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let r=[];for(let s=0;s<e.length;s+=t){let p=e.slice(s,s+t).map(l=>this.create(l)),g=await Promise.allSettled(p);for(let l of g)if(l.status==="fulfilled")r.push(l.value);else throw l.reason}return r}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=y({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return Qe(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let s=yield new ve(this.list(k(y({},e),{page:t}))),o=Array.isArray(s.data)?s.data:s||[];if(o.length===0){r=!1;break}for(let p of o)yield p;s.pagination&&t<s.pagination.pages||!s.pagination&&o.length>0?t++:r=!1}})}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,r={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:r})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,r){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:r})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,r){return this.patch(`/product/erix/crm/notes/${t}`,r)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var J=class extends i{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var X=class extends i{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var s,o;let t=await this.retrieve(e),r=Array.isArray((s=t.data)==null?void 0:s.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:r.map(p=>({key:p._id,label:p.name,type:"string",required:!0,options:[{label:p.name,value:p._id}],group:"Stages",uiHints:{color:p.color||"#cbd5e1",probability:p.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var Z=class extends i{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var ee=class extends i{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){var t;return this.post("/platform/inbox/conversations",{address:e.phone,channel:(t=e.channel)!=null?t:"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var v=class extends i{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){var h,d,b;let r=(d=(h=t.fileName)!=null?h:e.name)!=null?d:"file",s=e.type||"application/octet-stream",o=await this.post("/infra/storage/files/upload-url",{folder:(b=t.folder)!=null?b:"inbox",filename:r,contentType:s}),{uploadUrl:p,key:g}=o.data,l=await fetch(p,{method:"PUT",headers:{"Content-Type":s},body:e});if(!l.ok)throw new Error(`upload failed (${l.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:g,sizeBytes:e.size}),{key:g,mimeType:s,fileName:r}}};var te=class extends i{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var ne=class extends i{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var re=class extends i{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var se=class extends i{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var ie=class extends i{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,r){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:r})}async addSigner(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,r)}async sign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,r!=null?r:{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,r)}};var ae=class extends i{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var oe=class extends i{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var ce=class extends i{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var pe=class extends i{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var le=class extends i{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let r=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(r,t):this.get(r)}async preview(e,t,r,s){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:r,onEmptyVariable:s})}async getVariableManifest(e){var o,p;let t=await this.retrieve(e),r=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],s=[];for(let g of r)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");s.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((p=t.data)==null?void 0:p.name)||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};var Je=F(require("axios"),1);var ge=class extends i{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let r=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:s,key:o}=r.data;await Je.default.put(s,e,{headers:{"Content-Type":t.contentType}});let p=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:o,sizeBytes:p})}};var ue=class extends i{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},de=class extends i{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var me=class extends i{async system(){return(await this.get("/health")).data}};var ye=class extends i{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var A=class extends i{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var C=class extends i{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){var s;let r=await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t});return(s=r==null?void 0:r.data)!=null?s:{entries:[],hasMore:!1}}async followups(e){var r,s;let t=await super.get(`/platform/tenants/persona/${e}/followups`);return(s=(r=t==null?void 0:t.data)==null?void 0:r.entries)!=null?s:[]}};var Se=class extends i{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},fe=class{constructor(e){a(this,"copilot");this.copilot=new Se(e)}};var Xe=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/markdown","text/csv","text/html","image/png","image/jpeg","image/webp"],I=class extends i{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",y({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",y({kind:"url"},e))}async addFile(e,t={}){var s,o;let r=await new v(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(o=(s=t.title)!=null?s:r.fileName)!=null?o:"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",y({query:e},t?{limit:t}:{}))}};var S=class extends i{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,r){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:r})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var he=class extends i{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var Ee=class extends i{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},$e=class extends i{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},Oe=class extends i{async listPublic(){return this.get("/platform/billing/plans/public")}},De=class extends i{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},Me=class extends i{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},Fe=class extends i{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},Te=class{constructor(e){a(this,"entitlements");a(this,"subscriptions");a(this,"plans");a(this,"checkout");a(this,"user");a(this,"credits");this.entitlements=new Ee(e),this.subscriptions=new $e(e),this.plans=new Oe(e),this.checkout=new De(e),this.user=new Me(e),this.credits=new Fe(e)}};var xe=class extends i{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var be=class extends i{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},we=class extends i{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},ke=class extends i{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var B=class{constructor(e){a(this,"messages");a(this,"conversations");this.messages=new v(e),this.conversations=new ee(e)}},L=class{constructor(e){a(this,"leads");a(this,"pipelines");a(this,"activities");a(this,"analytics");a(this,"scoring");a(this,"payments");a(this,"chat");a(this,"events");a(this,"invoices");a(this,"checkout");a(this,"projects");a(this,"niche");a(this,"documents");a(this,"invoiceExport");a(this,"ai");this.leads=new Y(e),this.pipelines=new X(e),this.activities=new H(e),this.analytics=new z(e),this.scoring=new Z(e),this.payments=new J(e),this.chat=new B(e),this.events=new ne(e),this.invoices=new re(e),this.checkout=new te(e),this.projects=new ie(e),this.niche=new se(e),this.documents=new G(e),this.invoiceExport=new Q(e),this.ai=new S(e)}},E=class{constructor(e){a(this,"erix");this.erix=new L(e)}},q=class{constructor(e){a(this,"config");a(this,"templates");this.config=new pe(e),this.templates=new oe(e)}},_=class{constructor(e){a(this,"templates");this.templates=new le(e)}},N=class{constructor(e){a(this,"email");a(this,"whatsapp");a(this,"meet");a(this,"connections");this.email=new q(e),this.whatsapp=new _(e),this.meet=new ce(e),this.connections=new ae(e)}},V=class{constructor(e){a(this,"files");a(this,"folders");a(this,"media");this.files=new de(e),this.folders=new ue(e),this.media=new ge(e)}},$=class{constructor(e){a(this,"connect");a(this,"storage");this.connect=new N(e),this.storage=new V(e)}},U=class{constructor(e){a(this,"onboarding");a(this,"persona");this.onboarding=new A(e),this.persona=new C(e)}},K=class{constructor(e){a(this,"me");a(this,"members");a(this,"sessions");a(this,"notifications");this.me=new be(e),this.members=new we(e),this.sessions=new ke(e),this.notifications=new ye(e)}},O=class{constructor(e){a(this,"auth");a(this,"users");a(this,"tenants");a(this,"billing");a(this,"support");a(this,"ai");a(this,"knowledge");a(this,"health");this.auth=new he(e),this.users=new K(e),this.tenants=new U(e),this.billing=new Te(e),this.support=new xe(e),this.ai=new fe(e),this.knowledge=new I(e),this.health=new me(e)}};var D=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},Re=class{async constructEvent(e,t,r){if(!t)throw new D("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",r).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new D("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof D?o:new D(`Webhook payload parsing failed: ${o.message}`)}}};var Be=typeof process!="undefined"&&"3.0.0"||"2.0.0";var Ze,Le=(Ze=qe.default.default)!=null?Ze:qe.default,R=class{constructor(e){a(this,"client");a(this,"socket",null);a(this,"socketPromise",null);a(this,"socketQueue",[]);a(this,"clientCode");a(this,"apiVersion");a(this,"platform");a(this,"product");a(this,"infra");a(this,"webhooks");a(this,"lastSeq");a(this,"closed",!1);var d,b,w,P,m,Ne,Ve,Ue;let t=e.proxy;if(!e.apiKey&&!t)throw new f("API Key is required");this.clientCode=(d=e.clientCode)==null?void 0:d.toUpperCase(),this.apiVersion=(b=e.version)!=null?b:"v1";let r=(w=e.baseUrl)!=null?w:Ae,s=Ye(this.apiVersion,(P=t==null?void 0:t.url)!=null?P:r),o=e.socketUrl||r,p=typeof window!="undefined"&&typeof window.document!="undefined",g=p?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",l=p?((m=globalThis.navigator)==null?void 0:m.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",h=k(y({},t?{}:{"x-api-key":e.apiKey,"x-client-code":((Ne=e.clientCode)==null?void 0:Ne.toUpperCase())||""}),{"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Be,runtime:g,os:l})});if(this.client=et.default.create({baseURL:s,headers:h,timeout:(Ve=e.timeout)!=null?Ve:3e4}),Le(this.client,{retries:3,retryDelay:Le.exponentialDelay,retryCondition:T=>{var j;return Le.isNetworkOrIdempotentRequestError(T)||((j=T.response)==null?void 0:j.status)===429},onRetry:(T,j,Ke)=>{var je,We;typeof process!="undefined"&&((je=process.env)==null?void 0:je.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(We=Ke.method)==null?void 0:We.toUpperCase()} ${Ke.url}. Reason: ${j.message}`)}}),this.platform=new O(this.client),this.product=new E(this.client),this.infra=new $(this.client),this.webhooks=new Re,t){if(t.ticket){let T=t.ticket;this.initSocket(o,async()=>({ticket:await T()}))}}else{let T={apiKey:e.apiKey,clientCode:((Ue=e.clientCode)==null?void 0:Ue.toUpperCase())||""};this.initSocket(o,async()=>T,{"x-api-key":T.apiKey,"x-client-code":T.clientCode})}if(p){let T={version:Be,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T}}initSocket(e,t,r){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{auth:o=>{t().then(p=>o(k(y({},p),{lastSeq:this.lastSeq})),()=>o({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:o,args:p}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",p[0]):o==="leaveRoom"?this.socket.emit("leave-room",p[0]):o==="on"?this.socket.on(p[0],p[1]):o==="off"?this.socket.off(p[0],p[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{var e;(e=this.socket)!=null&&e.active||setTimeout(()=>{var t;this.closed||(t=this.socket)==null||t.connect()},5e3)}),this.socket.onAny((...e)=>{var r,s;let t=(r=e.at(-1))==null?void 0:r.seq;typeof t=="number"&&t>((s=this.lastSeq)!=null?s:0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,r,s){var o,p,g;try{return(await this.client.request({method:e,url:t,data:r,params:s})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((p=l.response.data)==null?void 0:p.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var tt={401:f,403:f,429:x};function dt(n){var e,t,r;if(n.response){let s=n.response.status,o=((e=n.response.data)==null?void 0:e.message)||((t=n.response.data)==null?void 0:t.error)||"API Request Failed",p=(r=n.response.data)==null?void 0:r.code,g=tt[s]||u;throw g===f?new f(o):g===x?new x(o):new u(o,s,p)}throw new u(n.message||"Network Error")}function mt(n,e){return n instanceof e}function yt(n){return n instanceof f?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof x?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof u?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var _e={[f.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[x.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function ft(n){let e=n.constructor.name;return _e[e]||_e[u.name]}var ht=R;0&&(module.exports={APIError,APIResource,AiAgent,AuthenticationError,ConnectInfra,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,EmailConnect,ErixChat,ErixProduct,HTTP_STATUS_ERROR_MAP,InfraDomain,KNOWLEDGE_FILE_TYPES,Knowledge,LEAD_STATUS_VALUES,Onboarding,Persona,PlatformDomain,PlatformTenants,PlatformUsers,ProductDomain,RateLimitError,StorageInfra,WhatsAppConnect,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
1
+ "use strict";var nt=Object.create;var M=Object.defineProperty,rt=Object.defineProperties,st=Object.getOwnPropertyDescriptor,it=Object.getOwnPropertyDescriptors,at=Object.getOwnPropertyNames,He=Object.getOwnPropertySymbols,ot=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var pt=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var Pe=(n,e,t)=>e in n?M(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y=(n,e)=>{for(var t in e||(e={}))ze.call(e,t)&&Pe(n,t,e[t]);if(He)for(var t of He(e))ct.call(e,t)&&Pe(n,t,e[t]);return n},k=(n,e)=>rt(n,it(e));var lt=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of at(e))!ze.call(n,s)&&s!==t&&M(n,s,{get:()=>e[s],enumerable:!(r=st(e,s))||r.enumerable});return n};var F=(n,e,t)=>(t=n!=null?nt(ot(n)):{},Ge(e||!n||!n.__esModule?M(t,"default",{value:n,enumerable:!0}):t,n)),gt=n=>Ge(M({},"__esModule",{value:!0}),n);var a=(n,e,t)=>Pe(n,typeof e!="symbol"?e+"":e,t);var Ae=function(n,e){this[0]=n,this[1]=e},Qe=(n,e,t)=>{var r=(g,l,h,d)=>{try{var x=t[g](l),w=(l=x.value)instanceof Ae,P=x.done;Promise.resolve(w?l[0]:l).then(m=>w?r(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:P})).catch(m=>r("throw",m,h,d))}catch(m){d(m)}},s=(g,l,h,d)=>p[g]=x=>(l=new Promise((w,P,m)=>(m=()=>r(g,x,w,P),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,p={};return t=t.apply(n,e),p[pt("asyncIterator")]=()=>p,s("next"),s("throw"),s("return"),p};var Tt={};lt(Tt,{APIError:()=>u,APIResource:()=>i,AiAgent:()=>S,AuthenticationError:()=>f,ConnectInfra:()=>N,ECODrIx:()=>R,ECODrIxAPI:()=>R,ERROR_RETRY_CONFIG:()=>_e,EcodrixError:()=>W,EmailConnect:()=>q,ErixChat:()=>B,ErixProduct:()=>L,HTTP_STATUS_ERROR_MAP:()=>tt,InfraDomain:()=>$,KNOWLEDGE_FILE_TYPES:()=>Xe,Knowledge:()=>I,LEAD_STATUS_VALUES:()=>Ie,Onboarding:()=>v,Persona:()=>C,PlatformDomain:()=>O,PlatformTenants:()=>U,PlatformUsers:()=>K,ProductDomain:()=>E,RateLimitError:()=>b,StorageInfra:()=>V,WhatsAppConnect:()=>_,default:()=>ht,getErrorDetails:()=>yt,getRetryConfig:()=>ft,handleAPIError:()=>dt,isAPIError:()=>mt});module.exports=gt(Tt);var et=F(require("axios"),1),qe=F(require("axios-retry"),1);var ve="https://api.ecodrix.com";function Ye(n="v1",e=ve){return`${e.replace(/\/+$/,"")}/${n}/api`}var W=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends W{constructor(t,r,s){super(t);a(this,"status");a(this,"code");this.name="APIError",this.status=r,this.code=s}},f=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},b=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var i=class{constructor(e){a(this,"client",e)}async post(e,t,r){try{let s=this.buildConfig(r);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let r=this.buildConfig(t);return(await this.client.get(e,r)).data}catch(r){this.handleError(r)}}async patch(e,t,r){try{let s=this.buildConfig(r);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,r){try{let s=this.buildConfig(r);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let r=this.buildConfig(t);return(await this.client.delete(e,r)).data}catch(r){this.handleError(r)}}buildConfig(e){if(!e)return;let t=y({},e);return e.idempotencyKey&&(t.headers=k(y({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,r,s;if(e.response){let o=e.response.status,p=((t=e.response.data)==null?void 0:t.message)||((r=e.response.data)==null?void 0:r.error)||"API Request Failed",g=(s=e.response.data)==null?void 0:s.code;switch(o){case 401:throw new f(p);case 403:throw new f(p);case 429:throw new b(p);default:throw new u(p,o,g)}}throw new u(e.message||"Network Error")}};var Ce=class extends i{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},H=class extends i{constructor(t){super(t);a(this,"notes");this.notes=new Ce(t)}async timeline(t,r){return this.get(`/product/erix/crm/leads/${t}/timeline`,{params:r})}async list(t,r){return this.get(`/product/erix/crm/leads/${t}/activities`,{params:y({},r)})}async log(t){return this.post(`/product/erix/crm/leads/${t.leadId}/activities`,t)}async logCall(t,r){return this.post(`/product/erix/crm/leads/${t}/calls`,r)}};var z=class extends i{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var G=class extends i{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,r){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,r?{fileUrl:r}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var Q=class extends i{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var Ie=["open","won","lost","archived"],Y=class extends i{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],r=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:Ie.map(o=>({label:`${o.charAt(0).toUpperCase()}${o.slice(1)}`,value:o}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...r,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let r=[];for(let s=0;s<e.length;s+=t){let p=e.slice(s,s+t).map(l=>this.create(l)),g=await Promise.allSettled(p);for(let l of g)if(l.status==="fulfilled")r.push(l.value);else throw l.reason}return r}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=y({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return Qe(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let s=yield new Ae(this.list(k(y({},e),{page:t}))),o=Array.isArray(s.data)?s.data:s||[];if(o.length===0){r=!1;break}for(let p of o)yield p;s.pagination&&t<s.pagination.pages||!s.pagination&&o.length>0?t++:r=!1}})}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,r={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:r})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async setFollowUp(e,t,r){return this.patch(`/product/erix/crm/leads/${e}`,{nextFollowUpAt:t,nextFollowUpNote:t&&r!=null?r:null})}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,r){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:r})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,r){return this.patch(`/product/erix/crm/notes/${t}`,r)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var J=class extends i{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var X=class extends i{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var s,o;let t=await this.retrieve(e),r=Array.isArray((s=t.data)==null?void 0:s.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:r.map(p=>({key:p._id,label:p.name,type:"string",required:!0,options:[{label:p.name,value:p._id}],group:"Stages",uiHints:{color:p.color||"#cbd5e1",probability:p.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var Z=class extends i{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var ee=class extends i{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){var t;return this.post("/platform/inbox/conversations",{address:e.phone,channel:(t=e.channel)!=null?t:"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var A=class extends i{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){var h,d,x;let r=(d=(h=t.fileName)!=null?h:e.name)!=null?d:"file",s=e.type||"application/octet-stream",o=await this.post("/infra/storage/files/upload-url",{folder:(x=t.folder)!=null?x:"inbox",filename:r,contentType:s}),{uploadUrl:p,key:g}=o.data,l=await fetch(p,{method:"PUT",headers:{"Content-Type":s},body:e});if(!l.ok)throw new Error(`upload failed (${l.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:g,sizeBytes:e.size}),{key:g,mimeType:s,fileName:r}}};var te=class extends i{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var ne=class extends i{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var re=class extends i{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var se=class extends i{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var ie=class extends i{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,r){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:r})}async addSigner(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,r)}async sign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,r!=null?r:{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,r)}};var ae=class extends i{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var oe=class extends i{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var ce=class extends i{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var pe=class extends i{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var le=class extends i{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let r=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(r,t):this.get(r)}async preview(e,t,r,s){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:r,onEmptyVariable:s})}async getVariableManifest(e){var o,p;let t=await this.retrieve(e),r=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],s=[];for(let g of r)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");s.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((p=t.data)==null?void 0:p.name)||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};var Je=F(require("axios"),1);var ge=class extends i{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let r=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:s,key:o}=r.data;await Je.default.put(s,e,{headers:{"Content-Type":t.contentType}});let p=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:o,sizeBytes:p})}};var ue=class extends i{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},de=class extends i{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var me=class extends i{async system(){return(await this.get("/health")).data}};var ye=class extends i{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var v=class extends i{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var C=class extends i{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){var s;let r=await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t});return(s=r==null?void 0:r.data)!=null?s:{entries:[],hasMore:!1}}async followups(e){var r,s;let t=await super.get(`/platform/tenants/persona/${e}/followups`);return(s=(r=t==null?void 0:t.data)==null?void 0:r.entries)!=null?s:[]}};var Se=class extends i{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},fe=class{constructor(e){a(this,"copilot");this.copilot=new Se(e)}};var Xe=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/markdown","text/csv","text/html","image/png","image/jpeg","image/webp"],I=class extends i{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",y({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",y({kind:"url"},e))}async addFile(e,t={}){var s,o;let r=await new A(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(o=(s=t.title)!=null?s:r.fileName)!=null?o:"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",y({query:e},t?{limit:t}:{}))}};var S=class extends i{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,r){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:r})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async agents(){return this.get("/product/flow/agents")}async updateAgent(e,t){return this.patch(`/product/flow/agents/${encodeURIComponent(e)}`,t)}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var he=class extends i{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var Ee=class extends i{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},$e=class extends i{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},Oe=class extends i{async listPublic(){return this.get("/platform/billing/plans/public")}},De=class extends i{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},Me=class extends i{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},Fe=class extends i{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},Te=class{constructor(e){a(this,"entitlements");a(this,"subscriptions");a(this,"plans");a(this,"checkout");a(this,"user");a(this,"credits");this.entitlements=new Ee(e),this.subscriptions=new $e(e),this.plans=new Oe(e),this.checkout=new De(e),this.user=new Me(e),this.credits=new Fe(e)}};var be=class extends i{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var xe=class extends i{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},we=class extends i{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async updateRole(e,t){return this.patch(`/platform/users/members/${e}`,{role:t})}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},ke=class extends i{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var B=class{constructor(e){a(this,"messages");a(this,"conversations");this.messages=new A(e),this.conversations=new ee(e)}},L=class{constructor(e){a(this,"leads");a(this,"pipelines");a(this,"activities");a(this,"analytics");a(this,"scoring");a(this,"payments");a(this,"chat");a(this,"events");a(this,"invoices");a(this,"checkout");a(this,"projects");a(this,"niche");a(this,"documents");a(this,"invoiceExport");a(this,"ai");this.leads=new Y(e),this.pipelines=new X(e),this.activities=new H(e),this.analytics=new z(e),this.scoring=new Z(e),this.payments=new J(e),this.chat=new B(e),this.events=new ne(e),this.invoices=new re(e),this.checkout=new te(e),this.projects=new ie(e),this.niche=new se(e),this.documents=new G(e),this.invoiceExport=new Q(e),this.ai=new S(e)}},E=class{constructor(e){a(this,"erix");this.erix=new L(e)}},q=class{constructor(e){a(this,"config");a(this,"templates");this.config=new pe(e),this.templates=new oe(e)}},_=class{constructor(e){a(this,"templates");this.templates=new le(e)}},N=class{constructor(e){a(this,"email");a(this,"whatsapp");a(this,"meet");a(this,"connections");this.email=new q(e),this.whatsapp=new _(e),this.meet=new ce(e),this.connections=new ae(e)}},V=class{constructor(e){a(this,"files");a(this,"folders");a(this,"media");this.files=new de(e),this.folders=new ue(e),this.media=new ge(e)}},$=class{constructor(e){a(this,"connect");a(this,"storage");this.connect=new N(e),this.storage=new V(e)}},U=class{constructor(e){a(this,"onboarding");a(this,"persona");this.onboarding=new v(e),this.persona=new C(e)}},K=class{constructor(e){a(this,"me");a(this,"members");a(this,"sessions");a(this,"notifications");this.me=new xe(e),this.members=new we(e),this.sessions=new ke(e),this.notifications=new ye(e)}},O=class{constructor(e){a(this,"auth");a(this,"users");a(this,"tenants");a(this,"billing");a(this,"support");a(this,"ai");a(this,"knowledge");a(this,"health");this.auth=new he(e),this.users=new K(e),this.tenants=new U(e),this.billing=new Te(e),this.support=new be(e),this.ai=new fe(e),this.knowledge=new I(e),this.health=new me(e)}};var D=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},Re=class{async constructEvent(e,t,r){if(!t)throw new D("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",r).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new D("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof D?o:new D(`Webhook payload parsing failed: ${o.message}`)}}};var Be=typeof process!="undefined"&&"3.1.1"||"2.0.0";var Ze,Le=(Ze=qe.default.default)!=null?Ze:qe.default,R=class{constructor(e){a(this,"client");a(this,"socket",null);a(this,"socketPromise",null);a(this,"socketQueue",[]);a(this,"clientCode");a(this,"apiVersion");a(this,"platform");a(this,"product");a(this,"infra");a(this,"webhooks");a(this,"lastSeq");a(this,"closed",!1);var d,x,w,P,m,Ne,Ve,Ue;let t=e.proxy;if(!e.apiKey&&!t)throw new f("API Key is required");this.clientCode=(d=e.clientCode)==null?void 0:d.toUpperCase(),this.apiVersion=(x=e.version)!=null?x:"v1";let r=(w=e.baseUrl)!=null?w:ve,s=Ye(this.apiVersion,(P=t==null?void 0:t.url)!=null?P:r),o=e.socketUrl||r,p=typeof window!="undefined"&&typeof window.document!="undefined",g=p?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",l=p?((m=globalThis.navigator)==null?void 0:m.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",h=k(y({},t?{}:{"x-api-key":e.apiKey,"x-client-code":((Ne=e.clientCode)==null?void 0:Ne.toUpperCase())||""}),{"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Be,runtime:g,os:l})});if(this.client=et.default.create({baseURL:s,headers:h,timeout:(Ve=e.timeout)!=null?Ve:3e4}),Le(this.client,{retries:3,retryDelay:Le.exponentialDelay,retryCondition:T=>{var j;return Le.isNetworkOrIdempotentRequestError(T)||((j=T.response)==null?void 0:j.status)===429},onRetry:(T,j,Ke)=>{var je,We;typeof process!="undefined"&&((je=process.env)==null?void 0:je.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(We=Ke.method)==null?void 0:We.toUpperCase()} ${Ke.url}. Reason: ${j.message}`)}}),this.platform=new O(this.client),this.product=new E(this.client),this.infra=new $(this.client),this.webhooks=new Re,t){if(t.ticket){let T=t.ticket;this.initSocket(o,async()=>({ticket:await T()}))}}else{let T={apiKey:e.apiKey,clientCode:((Ue=e.clientCode)==null?void 0:Ue.toUpperCase())||""};this.initSocket(o,async()=>T,{"x-api-key":T.apiKey,"x-client-code":T.clientCode})}if(p){let T={version:Be,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T}}initSocket(e,t,r){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{auth:o=>{t().then(p=>o(k(y({},p),{lastSeq:this.lastSeq})),()=>o({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:o,args:p}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",p[0]):o==="leaveRoom"?this.socket.emit("leave-room",p[0]):o==="on"?this.socket.on(p[0],p[1]):o==="off"?this.socket.off(p[0],p[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{var e;(e=this.socket)!=null&&e.active||setTimeout(()=>{var t;this.closed||(t=this.socket)==null||t.connect()},5e3)}),this.socket.onAny((...e)=>{var r,s;let t=(r=e.at(-1))==null?void 0:r.seq;typeof t=="number"&&t>((s=this.lastSeq)!=null?s:0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,r,s){var o,p,g;try{return(await this.client.request({method:e,url:t,data:r,params:s})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((p=l.response.data)==null?void 0:p.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var tt={401:f,403:f,429:b};function dt(n){var e,t,r;if(n.response){let s=n.response.status,o=((e=n.response.data)==null?void 0:e.message)||((t=n.response.data)==null?void 0:t.error)||"API Request Failed",p=(r=n.response.data)==null?void 0:r.code,g=tt[s]||u;throw g===f?new f(o):g===b?new b(o):new u(o,s,p)}throw new u(n.message||"Network Error")}function mt(n,e){return n instanceof e}function yt(n){return n instanceof f?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof b?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof u?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var _e={[f.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[b.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function ft(n){let e=n.constructor.name;return _e[e]||_e[u.name]}var ht=R;0&&(module.exports={APIError,APIResource,AiAgent,AuthenticationError,ConnectInfra,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,EmailConnect,ErixChat,ErixProduct,HTTP_STATUS_ERROR_MAP,InfraDomain,KNOWLEDGE_FILE_TYPES,Knowledge,LEAD_STATUS_VALUES,Onboarding,Persona,PlatformDomain,PlatformTenants,PlatformUsers,ProductDomain,RateLimitError,StorageInfra,WhatsAppConnect,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
@@ -463,6 +463,10 @@ interface Lead {
463
463
  };
464
464
  score?: number;
465
465
  lastContactedAt?: string;
466
+ /** When to get back to this contact (ISO), or null. */
467
+ nextFollowUpAt?: string | null;
468
+ /** Why — shown with the follow-up. */
469
+ nextFollowUpNote?: string | null;
466
470
  createdAt: string;
467
471
  updatedAt: string;
468
472
  metadata?: Record<string, unknown>;
@@ -707,6 +711,14 @@ declare class Leads extends APIResource {
707
711
  * ```
708
712
  */
709
713
  update<T = any>(leadId: string, params: Partial<CreateLeadParams>): Promise<T>;
714
+ /**
715
+ * Set the contact's next follow-up (replaces any earlier one), or clear it
716
+ * with `at: null`. When it comes due, `lead.follow_up_due` fires and the
717
+ * morning briefing counts it.
718
+ *
719
+ * @param at - ISO time with offset, e.g. "2026-10-20T15:00:00+05:30".
720
+ */
721
+ setFollowUp<T = any>(leadId: string, at: string | null, note?: string): Promise<T>;
710
722
  /**
711
723
  * Move a lead to a new stage in a pipeline.
712
724
  *
@@ -863,6 +875,8 @@ declare class Payments extends APIResource {
863
875
  currency?: string;
864
876
  description?: string;
865
877
  appointmentId?: string;
878
+ /** Your reference for this payment; a retry with the same id is counted once. */
879
+ orderId?: string;
866
880
  }): Promise<T>;
867
881
  }
868
882
 
@@ -3875,6 +3889,11 @@ interface AiAgentSettings {
3875
3889
  * AI Auto-Reply flow is set up (connected channels only).
3876
3890
  */
3877
3891
  autoReplyChannels?: string[];
3892
+ /**
3893
+ * Returned by `updateSettings` when the agent is on: channels that are
3894
+ * connected but not yet allowed for Flow, so the agent can't answer there.
3895
+ */
3896
+ needsFlowGrant?: string[];
3878
3897
  }
3879
3898
  /** An AI draft waiting for a person in the inbox (kept up to 7 days). */
3880
3899
  interface AiSuggestion {
@@ -3896,6 +3915,49 @@ interface AiSuggestion {
3896
3915
  actionApprovedAt?: string;
3897
3916
  generatedAt: string;
3898
3917
  }
3918
+ /** How much a module agent may do on its own. */
3919
+ type AgentAutonomy = "off" | "suggest" | "approve" | "act";
3920
+ /** One tool a module agent can be given. */
3921
+ interface ModuleAgentTool {
3922
+ id: string;
3923
+ label: string;
3924
+ description?: string;
3925
+ /** Changes data. */
3926
+ sideEffect: boolean;
3927
+ /** Money or a message to a customer: always waits for a person. */
3928
+ needsApproval: boolean;
3929
+ }
3930
+ /** Monthly caps per agent (safety limits, not prices). */
3931
+ interface AgentBudget {
3932
+ /** Model calls. */
3933
+ turns: number;
3934
+ /** Data-changing actions. */
3935
+ actions: number;
3936
+ tokens: number;
3937
+ }
3938
+ interface ModuleAgentSettings {
3939
+ autonomy: AgentAutonomy;
3940
+ /** Ids from the agent's `tools` that are switched on. */
3941
+ tools: string[];
3942
+ budget: AgentBudget;
3943
+ /** Kill switch: a running agent stops before its next model call. */
3944
+ paused: boolean;
3945
+ updatedBy: string | null;
3946
+ updatedAt: string | null;
3947
+ }
3948
+ /** A module agent (e.g. `erix.sales`, `connect.channels`) with this month's usage. */
3949
+ interface ModuleAgent {
3950
+ id: string;
3951
+ label: string;
3952
+ description: string;
3953
+ /** Every tool this agent can be given. */
3954
+ tools: ModuleAgentTool[];
3955
+ settings: ModuleAgentSettings;
3956
+ usage: AgentBudget;
3957
+ }
3958
+ type ModuleAgentPatch = Partial<Pick<ModuleAgentSettings, "autonomy" | "tools" | "paused">> & {
3959
+ budget?: Partial<AgentBudget>;
3960
+ };
3899
3961
  /** A Flow run held at an approval step. */
3900
3962
  interface PausedRun {
3901
3963
  id: string;
@@ -3905,6 +3967,12 @@ interface PausedRun {
3905
3967
  recordsHeld: number | null;
3906
3968
  startedAt: string | null;
3907
3969
  createdAt: string;
3970
+ /** Set when an AI agent step is held: what approving it runs. */
3971
+ pendingAction?: {
3972
+ action: string;
3973
+ label: string;
3974
+ input: Record<string, unknown>;
3975
+ };
3908
3976
  }
3909
3977
  /**
3910
3978
  * The AI agent: its settings and the drafts it leaves in the inbox. Drafts
@@ -3953,6 +4021,19 @@ declare class AiAgent extends APIResource {
3953
4021
  runs: PausedRun[];
3954
4022
  };
3955
4023
  }>;
4024
+ /**
4025
+ * The module agents with this workspace's settings and month's usage.
4026
+ * Released per workspace (`agents.v1`); a 404 means not available yet.
4027
+ */
4028
+ agents(): Promise<{
4029
+ success: boolean;
4030
+ data: ModuleAgent[];
4031
+ }>;
4032
+ /** Change an agent's autonomy, tools, budget or kill switch (workspace admins). */
4033
+ updateAgent(id: string, patch: ModuleAgentPatch): Promise<{
4034
+ success: boolean;
4035
+ data: ModuleAgentSettings;
4036
+ }>;
3956
4037
  /** Let a held run continue, or stop it. */
3957
4038
  decideRun(runId: string, decision: "approve" | "reject"): Promise<{
3958
4039
  success: boolean;
@@ -4289,6 +4370,11 @@ declare class Members extends APIResource {
4289
4370
  * Invite a new member to the current organization.
4290
4371
  */
4291
4372
  invite<T = any>(body: Record<string, unknown>): Promise<T>;
4373
+ /**
4374
+ * Change a member's role (`owner` | `admin` | `agent` | `viewer`).
4375
+ * Admins may switch agent ↔ viewer; admin and owner changes need the owner.
4376
+ */
4377
+ updateRole<T = any>(id: string, role: "owner" | "admin" | "agent" | "viewer"): Promise<T>;
4292
4378
  /**
4293
4379
  * Remove a member from the current organization.
4294
4380
  *
@@ -5102,4 +5188,4 @@ declare function getRetryConfig(error: any): {
5102
5188
  readonly reason: "Generic API errors may be transient and worth retrying";
5103
5189
  };
5104
5190
 
5105
- export { type AIPersona, APIError, APIResource, AiAgent, type AiAgentSettings, type AiAgentTool, type AiSuggestion, type AnswerFollowupBody, type AnswerOnboardingPayload, type AnswerOnboardingResponse, type ApplyCouponPayload, AuthenticationError, type BehaviorRules, type CheckboxConfig, type CheckoutAmountBreakdown, type CheckoutOrderResponse, type CheckoutProduct, type CheckoutSession, type ColorRule, type ColumnConfig, type CompleteOnboardingPayload, type CompleteOnboardingResponse, type ConfidenceResponse, ConnectInfra, type Conversation, type ListParams as ConversationListParams, type Correction, type CreateLeadParams, type CreateOrderPayload, type CreatePipelineParams, type CreateSessionPayload, type CrmView, type CurrencyConfig, type CurrencyValue, type CustomFieldFilter, type DateConfig, type DateTimeConfig, type DropdownConfig, ECODrIxAPI as ECODrIx, ECODrIxAPI, type ECODrIxAPIOptions, ERROR_RETRY_CONFIG, EcodrixError, type EditOnboardingPayload, type EditOnboardingResponse, type EmailConfig, EmailConnect, ErixChat, ErixProduct, type FieldConfig, type FieldDefinition, type FieldManifest, type FieldType, type FileConfig, type FilterOperator, type FilterRule, type FormulaConfig, type GlobalOnboardingPayload, HTTP_STATUS_ERROR_MAP, type ICP, type InboxChannel, InfraDomain, KNOWLEDGE_FILE_TYPES, Knowledge, type KnowledgePassage, type KnowledgeSource, LEAD_STATUS_VALUES, type LayoutType, type Lead, type LeadPattern, type LeadSource, type LeadStatus, type LearningMemory, type ListLeadsParams, type ManifestFieldType, type MappingField, type MappingPreviewResult, type MappingSources, type MappingValidationResult, type Message, type NichePack, type NichePackResearchConfig, type NichePackStatus, type NormalizedFieldValue, type NumberConfig, Onboarding, type OnboardingCohortRange, type OnboardingConfig, type OnboardingExperiment, type OnboardingExperimentStatus, type OnboardingExperimentVariant, type OnboardingMemoryMapping, type OnboardingOption, type OnboardingSession, type OnboardingSessionStatus, type OnboardingStateResponse, type OnboardingStep, type OnboardingStepType, type OutboundMedia, type OutreachEdit, type PaginatedResponse, type PausedRun, Persona, type PersonaFollowupQuestion, type PersonaFollowupsResponse, type PersonaIdentity, type PersonaTimelineEntry, type PersonaTimelineOptions, type PersonaTimelineResponse, type PhoneConfig, type Pipeline, type PipelineStage, type PipelineStageParams, PlatformDomain, PlatformTenants, PlatformUsers, ProductDomain, type ProgressConfig, RateLimitError, type RatingConfig, type ReinforceResponse, type ReinforcementEvent, type RelationConfig, type RelationValue, type RequestOptions, type ResourceManifest, type SendMessageParams, type SendTemplateParams, type ServiceConfig, type ServiceConfigGlobal, type ServiceConfigPerProduct, type SortRule, type StartOnboardingPayload, type StartOnboardingResponse, StorageInfra, type StoredFieldValue, type SuggestionEvent, type TagsConfig, type Template, type TemplateApiResponse, type TemplateBinding, type TemplateBindingSource, type TemplateComponent, type TemplateEmptyPolicy, type TemplateMapping, type TextConfig, type UpsertLeadParams, type UrlConfig, type VerifyPayload, type ViewConfig, type Vocabulary, WhatsAppConnect, type WorkspaceDashboardLayout, type WorkspaceDefaultAutomation, type WorkspaceDefaultField, type WorkspaceDefaultPipeline, type WorkspaceModuleConfig, type WorkspaceProfile, ECODrIxAPI as default, getErrorDetails, getRetryConfig, handleAPIError, isAPIError };
5191
+ export { type AIPersona, APIError, APIResource, type AgentAutonomy, type AgentBudget, AiAgent, type AiAgentSettings, type AiAgentTool, type AiSuggestion, type AnswerFollowupBody, type AnswerOnboardingPayload, type AnswerOnboardingResponse, type ApplyCouponPayload, AuthenticationError, type BehaviorRules, type CheckboxConfig, type CheckoutAmountBreakdown, type CheckoutOrderResponse, type CheckoutProduct, type CheckoutSession, type ColorRule, type ColumnConfig, type CompleteOnboardingPayload, type CompleteOnboardingResponse, type ConfidenceResponse, ConnectInfra, type Conversation, type ListParams as ConversationListParams, type Correction, type CreateLeadParams, type CreateOrderPayload, type CreatePipelineParams, type CreateSessionPayload, type CrmView, type CurrencyConfig, type CurrencyValue, type CustomFieldFilter, type DateConfig, type DateTimeConfig, type DropdownConfig, ECODrIxAPI as ECODrIx, ECODrIxAPI, type ECODrIxAPIOptions, ERROR_RETRY_CONFIG, EcodrixError, type EditOnboardingPayload, type EditOnboardingResponse, type EmailConfig, EmailConnect, ErixChat, ErixProduct, type FieldConfig, type FieldDefinition, type FieldManifest, type FieldType, type FileConfig, type FilterOperator, type FilterRule, type FormulaConfig, type GlobalOnboardingPayload, HTTP_STATUS_ERROR_MAP, type ICP, type InboxChannel, InfraDomain, KNOWLEDGE_FILE_TYPES, Knowledge, type KnowledgePassage, type KnowledgeSource, LEAD_STATUS_VALUES, type LayoutType, type Lead, type LeadPattern, type LeadSource, type LeadStatus, type LearningMemory, type ListLeadsParams, type ManifestFieldType, type MappingField, type MappingPreviewResult, type MappingSources, type MappingValidationResult, type Message, type ModuleAgent, type ModuleAgentPatch, type ModuleAgentSettings, type ModuleAgentTool, type NichePack, type NichePackResearchConfig, type NichePackStatus, type NormalizedFieldValue, type NumberConfig, Onboarding, type OnboardingCohortRange, type OnboardingConfig, type OnboardingExperiment, type OnboardingExperimentStatus, type OnboardingExperimentVariant, type OnboardingMemoryMapping, type OnboardingOption, type OnboardingSession, type OnboardingSessionStatus, type OnboardingStateResponse, type OnboardingStep, type OnboardingStepType, type OutboundMedia, type OutreachEdit, type PaginatedResponse, type PausedRun, Persona, type PersonaFollowupQuestion, type PersonaFollowupsResponse, type PersonaIdentity, type PersonaTimelineEntry, type PersonaTimelineOptions, type PersonaTimelineResponse, type PhoneConfig, type Pipeline, type PipelineStage, type PipelineStageParams, PlatformDomain, PlatformTenants, PlatformUsers, ProductDomain, type ProgressConfig, RateLimitError, type RatingConfig, type ReinforceResponse, type ReinforcementEvent, type RelationConfig, type RelationValue, type RequestOptions, type ResourceManifest, type SendMessageParams, type SendTemplateParams, type ServiceConfig, type ServiceConfigGlobal, type ServiceConfigPerProduct, type SortRule, type StartOnboardingPayload, type StartOnboardingResponse, StorageInfra, type StoredFieldValue, type SuggestionEvent, type TagsConfig, type Template, type TemplateApiResponse, type TemplateBinding, type TemplateBindingSource, type TemplateComponent, type TemplateEmptyPolicy, type TemplateMapping, type TextConfig, type UpsertLeadParams, type UrlConfig, type VerifyPayload, type ViewConfig, type Vocabulary, WhatsAppConnect, type WorkspaceDashboardLayout, type WorkspaceDefaultAutomation, type WorkspaceDefaultField, type WorkspaceDefaultPipeline, type WorkspaceModuleConfig, type WorkspaceProfile, ECODrIxAPI as default, getErrorDetails, getRetryConfig, handleAPIError, isAPIError };
@@ -1 +1 @@
1
- var ze=Object.defineProperty,Qe=Object.defineProperties;var Ge=Object.getOwnPropertyDescriptors;var Ve=Object.getOwnPropertySymbols;var Ye=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable;var Xe=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var be=(n,e,t)=>e in n?ze(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e)=>{for(var t in e||(e={}))Ye.call(e,t)&&be(n,t,e[t]);if(Ve)for(var t of Ve(e))Je.call(e,t)&&be(n,t,e[t]);return n},w=(n,e)=>Qe(n,Ge(e));var i=(n,e,t)=>be(n,typeof e!="symbol"?e+"":e,t);var we=function(n,e){this[0]=n,this[1]=e},Be=(n,e,t)=>{var r=(l,p,f,g)=>{try{var T=t[l](p),b=(p=T.value)instanceof we,R=T.done;Promise.resolve(b?p[0]:p).then(d=>b?r(l==="return"?l:"next",p[1]?{done:d.done,value:d.value}:d,f,g):f({value:d,done:R})).catch(d=>r("throw",d,f,g))}catch(d){g(d)}},a=(l,p,f,g)=>c[l]=T=>(p=new Promise((b,R,d)=>(d=()=>r(l,T,b,R),o?o.then(d):d())),g=()=>o===f&&(o=0),o=f=p.then(g,g),p),o,c={};return t=t.apply(n,e),c[Xe("asyncIterator")]=()=>c,a("next"),a("throw"),a("return"),c};import nt from"axios";import Ke from"axios-retry";var Re="https://api.ecodrix.com";function Fe(n="v1",e=Re){return`${e.replace(/\/+$/,"")}/${n}/api`}var ke=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends ke{constructor(t,r,a){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=r,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},x=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var s=class{constructor(e){i(this,"client",e)}async post(e,t,r){try{let a=this.buildConfig(r);return(await this.client.post(e,t,a)).data}catch(a){this.handleError(a)}}async get(e,t){try{let r=this.buildConfig(t);return(await this.client.get(e,r)).data}catch(r){this.handleError(r)}}async patch(e,t,r){try{let a=this.buildConfig(r);return(await this.client.patch(e,t,a)).data}catch(a){this.handleError(a)}}async put(e,t,r){try{let a=this.buildConfig(r);return(await this.client.put(e,t,a)).data}catch(a){this.handleError(a)}}async deleteRequest(e,t){try{let r=this.buildConfig(t);return(await this.client.delete(e,r)).data}catch(r){this.handleError(r)}}buildConfig(e){if(!e)return;let t=m({},e);return e.idempotencyKey&&(t.headers=w(m({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,r,a;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((r=e.response.data)==null?void 0:r.error)||"API Request Failed",l=(a=e.response.data)==null?void 0:a.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new x(c);default:throw new u(c,o,l)}}throw new u(e.message||"Network Error")}};var Pe=class extends s{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},M=class extends s{constructor(t){super(t);i(this,"notes");this.notes=new Pe(t)}async timeline(t,r){return this.get(`/product/erix/crm/leads/${t}/timeline`,{params:r})}async list(t,r){return this.get(`/product/erix/crm/leads/${t}/activities`,{params:m({},r)})}async log(t){return this.post(`/product/erix/crm/leads/${t.leadId}/activities`,t)}async logCall(t,r){return this.post(`/product/erix/crm/leads/${t}/calls`,r)}};var L=class extends s{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var q=class extends s{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,r){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,r?{fileUrl:r}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var _=class extends s{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var je=["open","won","lost","archived"],N=class extends s{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],r=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:je.map(o=>({label:`${o.charAt(0).toUpperCase()}${o.slice(1)}`,value:o}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],a=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...r,...a],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let r=[];for(let a=0;a<e.length;a+=t){let c=e.slice(a,a+t).map(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")r.push(p.value);else throw p.reason}return r}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=m({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return Be(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let a=yield new we(this.list(w(m({},e),{page:t}))),o=Array.isArray(a.data)?a.data:a||[];if(o.length===0){r=!1;break}for(let c of o)yield c;a.pagination&&t<a.pagination.pages||!a.pagination&&o.length>0?t++:r=!1}})}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,r={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:r})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,r){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:r})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,r){return this.patch(`/product/erix/crm/notes/${t}`,r)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var U=class extends s{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var V=class extends s{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var a,o;let t=await this.retrieve(e),r=Array.isArray((a=t.data)==null?void 0:a.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:r.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var B=class extends s{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var F=class extends s{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){var t;return this.post("/platform/inbox/conversations",{address:e.phone,channel:(t=e.channel)!=null?t:"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var k=class extends s{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){var f,g,T;let r=(g=(f=t.fileName)!=null?f:e.name)!=null?g:"file",a=e.type||"application/octet-stream",o=await this.post("/infra/storage/files/upload-url",{folder:(T=t.folder)!=null?T:"inbox",filename:r,contentType:a}),{uploadUrl:c,key:l}=o.data,p=await fetch(c,{method:"PUT",headers:{"Content-Type":a},body:e});if(!p.ok)throw new Error(`upload failed (${p.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:l,sizeBytes:e.size}),{key:l,mimeType:a,fileName:r}}};var j=class extends s{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var K=class extends s{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var H=class extends s{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var W=class extends s{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var z=class extends s{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,r){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:r})}async addSigner(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,r)}async sign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,r!=null?r:{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,r)}};var Q=class extends s{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var G=class extends s{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var Y=class extends s{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var J=class extends s{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var X=class extends s{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let r=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(r,t):this.get(r)}async preview(e,t,r,a){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:r,onEmptyVariable:a})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),r=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],a=[];for(let l of r)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let f of p){let g=f.replace(/{{|}}/g,"");a.push({key:`var_${g}`,label:`${l.type} Var {{${g}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:a,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import Ze from"axios";var Z=class extends s{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let r=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:a,key:o}=r.data;await Ze.put(a,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:o,sizeBytes:c})}};var ee=class extends s{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},te=class extends s{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var ne=class extends s{async system(){return(await this.get("/health")).data}};var re=class extends s{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var A=class extends s{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var I=class extends s{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){var a;let r=await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t});return(a=r==null?void 0:r.data)!=null?a:{entries:[],hasMore:!1}}async followups(e){var r,a;let t=await super.get(`/platform/tenants/persona/${e}/followups`);return(a=(r=t==null?void 0:t.data)==null?void 0:r.entries)!=null?a:[]}};var ve=class extends s{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},se=class{constructor(e){i(this,"copilot");this.copilot=new ve(e)}};var et=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/markdown","text/csv","text/html","image/png","image/jpeg","image/webp"],S=class extends s{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",m({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",m({kind:"url"},e))}async addFile(e,t={}){var a,o;let r=await new k(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(o=(a=t.title)!=null?a:r.fileName)!=null?o:"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",m({query:e},t?{limit:t}:{}))}};var C=class extends s{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,r){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:r})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var ie=class extends s{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var Ae=class extends s{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},Ie=class extends s{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},Se=class extends s{async listPublic(){return this.get("/platform/billing/plans/public")}},Ce=class extends s{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},Ee=class extends s{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},$e=class extends s{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},ae=class{constructor(e){i(this,"entitlements");i(this,"subscriptions");i(this,"plans");i(this,"checkout");i(this,"user");i(this,"credits");this.entitlements=new Ae(e),this.subscriptions=new Ie(e),this.plans=new Se(e),this.checkout=new Ce(e),this.user=new Ee(e),this.credits=new $e(e)}};var oe=class extends s{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var ce=class extends s{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},pe=class extends s{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},le=class extends s{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var ue=class{constructor(e){i(this,"messages");i(this,"conversations");this.messages=new k(e),this.conversations=new F(e)}},ge=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"scoring");i(this,"payments");i(this,"chat");i(this,"events");i(this,"invoices");i(this,"checkout");i(this,"projects");i(this,"niche");i(this,"documents");i(this,"invoiceExport");i(this,"ai");this.leads=new N(e),this.pipelines=new V(e),this.activities=new M(e),this.analytics=new L(e),this.scoring=new B(e),this.payments=new U(e),this.chat=new ue(e),this.events=new K(e),this.invoices=new H(e),this.checkout=new j(e),this.projects=new z(e),this.niche=new W(e),this.documents=new q(e),this.invoiceExport=new _(e),this.ai=new C(e)}},E=class{constructor(e){i(this,"erix");this.erix=new ge(e)}},de=class{constructor(e){i(this,"config");i(this,"templates");this.config=new J(e),this.templates=new G(e)}},me=class{constructor(e){i(this,"templates");this.templates=new X(e)}},ye=class{constructor(e){i(this,"email");i(this,"whatsapp");i(this,"meet");i(this,"connections");this.email=new de(e),this.whatsapp=new me(e),this.meet=new Y(e),this.connections=new Q(e)}},fe=class{constructor(e){i(this,"files");i(this,"folders");i(this,"media");this.files=new te(e),this.folders=new ee(e),this.media=new Z(e)}},$=class{constructor(e){i(this,"connect");i(this,"storage");this.connect=new ye(e),this.storage=new fe(e)}},he=class{constructor(e){i(this,"onboarding");i(this,"persona");this.onboarding=new A(e),this.persona=new I(e)}},Te=class{constructor(e){i(this,"me");i(this,"members");i(this,"sessions");i(this,"notifications");this.me=new ce(e),this.members=new pe(e),this.sessions=new le(e),this.notifications=new re(e)}},O=class{constructor(e){i(this,"auth");i(this,"users");i(this,"tenants");i(this,"billing");i(this,"support");i(this,"ai");i(this,"knowledge");i(this,"health");this.auth=new ie(e),this.users=new Te(e),this.tenants=new he(e),this.billing=new ae(e),this.support=new oe(e),this.ai=new se(e),this.knowledge=new S(e),this.health=new ne(e)}};var P=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},xe=class{async constructEvent(e,t,r){if(!t)throw new P("No webhook signature provided");let a=Array.isArray(t)?t[0]:t;a.startsWith("sha256=")&&(a=a.slice(7));try{let o=await import("crypto"),l=o.createHmac("sha256",r).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(a)))throw new P("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof P?o:new P(`Webhook payload parsing failed: ${o.message}`)}}};var Oe=typeof process!="undefined"&&"3.0.0"||"2.0.0";var He,De=(He=Ke.default)!=null?He:Ke,v=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"apiVersion");i(this,"platform");i(this,"product");i(this,"infra");i(this,"webhooks");i(this,"lastSeq");i(this,"closed",!1);var g,T,b,R,d,Me,Le,qe;let t=e.proxy;if(!e.apiKey&&!t)throw new y("API Key is required");this.clientCode=(g=e.clientCode)==null?void 0:g.toUpperCase(),this.apiVersion=(T=e.version)!=null?T:"v1";let r=(b=e.baseUrl)!=null?b:Re,a=Fe(this.apiVersion,(R=t==null?void 0:t.url)!=null?R:r),o=e.socketUrl||r,c=typeof window!="undefined"&&typeof window.document!="undefined",l=c?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",p=c?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",f=w(m({},t?{}:{"x-api-key":e.apiKey,"x-client-code":((Me=e.clientCode)==null?void 0:Me.toUpperCase())||""}),{"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Oe,runtime:l,os:p})});if(this.client=nt.create({baseURL:a,headers:f,timeout:(Le=e.timeout)!=null?Le:3e4}),De(this.client,{retries:3,retryDelay:De.exponentialDelay,retryCondition:h=>{var D;return De.isNetworkOrIdempotentRequestError(h)||((D=h.response)==null?void 0:D.status)===429},onRetry:(h,D,_e)=>{var Ne,Ue;typeof process!="undefined"&&((Ne=process.env)==null?void 0:Ne.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(Ue=_e.method)==null?void 0:Ue.toUpperCase()} ${_e.url}. Reason: ${D.message}`)}}),this.platform=new O(this.client),this.product=new E(this.client),this.infra=new $(this.client),this.webhooks=new xe,t){if(t.ticket){let h=t.ticket;this.initSocket(o,async()=>({ticket:await h()}))}}else{let h={apiKey:e.apiKey,clientCode:((qe=e.clientCode)==null?void 0:qe.toUpperCase())||""};this.initSocket(o,async()=>h,{"x-api-key":h.apiKey,"x-client-code":h.clientCode})}if(c){let h={version:Oe,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h}}initSocket(e,t,r){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:a})=>{this.socket=a(e,{auth:o=>{t().then(c=>o(w(m({},c),{lastSeq:this.lastSeq})),()=>o({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{var e;(e=this.socket)!=null&&e.active||setTimeout(()=>{var t;this.closed||(t=this.socket)==null||t.connect()},5e3)}),this.socket.onAny((...e)=>{var r,a;let t=(r=e.at(-1))==null?void 0:r.seq;typeof t=="number"&&t>((a=this.lastSeq)!=null?a:0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,r,a){var o,c,l;try{return(await this.client.request({method:e,url:t,data:r,params:a})).data}catch(p){throw p.response?new u(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new u(p.message||"Network Error")}}};var rt={401:y,403:y,429:x};function Cr(n){var e,t,r;if(n.response){let a=n.response.status,o=((e=n.response.data)==null?void 0:e.message)||((t=n.response.data)==null?void 0:t.error)||"API Request Failed",c=(r=n.response.data)==null?void 0:r.code,l=rt[a]||u;throw l===y?new y(o):l===x?new x(o):new u(o,a,c)}throw new u(n.message||"Network Error")}function Er(n,e){return n instanceof e}function $r(n){return n instanceof y?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof x?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof u?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var We={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[x.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Or(n){let e=n.constructor.name;return We[e]||We[u.name]}var Lr=v;export{u as APIError,s as APIResource,C as AiAgent,y as AuthenticationError,ye as ConnectInfra,v as ECODrIx,v as ECODrIxAPI,We as ERROR_RETRY_CONFIG,ke as EcodrixError,de as EmailConnect,ue as ErixChat,ge as ErixProduct,rt as HTTP_STATUS_ERROR_MAP,$ as InfraDomain,et as KNOWLEDGE_FILE_TYPES,S as Knowledge,je as LEAD_STATUS_VALUES,A as Onboarding,I as Persona,O as PlatformDomain,he as PlatformTenants,Te as PlatformUsers,E as ProductDomain,x as RateLimitError,fe as StorageInfra,me as WhatsAppConnect,Lr as default,$r as getErrorDetails,Or as getRetryConfig,Cr as handleAPIError,Er as isAPIError};
1
+ var ze=Object.defineProperty,Ge=Object.defineProperties;var Qe=Object.getOwnPropertyDescriptors;var Be=Object.getOwnPropertySymbols;var Ye=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable;var Xe=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var be=(n,e,t)=>e in n?ze(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e)=>{for(var t in e||(e={}))Ye.call(e,t)&&be(n,t,e[t]);if(Be)for(var t of Be(e))Je.call(e,t)&&be(n,t,e[t]);return n},w=(n,e)=>Ge(n,Qe(e));var i=(n,e,t)=>be(n,typeof e!="symbol"?e+"":e,t);var we=function(n,e){this[0]=n,this[1]=e},Ve=(n,e,t)=>{var r=(l,p,f,g)=>{try{var T=t[l](p),b=(p=T.value)instanceof we,R=T.done;Promise.resolve(b?p[0]:p).then(d=>b?r(l==="return"?l:"next",p[1]?{done:d.done,value:d.value}:d,f,g):f({value:d,done:R})).catch(d=>r("throw",d,f,g))}catch(d){g(d)}},a=(l,p,f,g)=>c[l]=T=>(p=new Promise((b,R,d)=>(d=()=>r(l,T,b,R),o?o.then(d):d())),g=()=>o===f&&(o=0),o=f=p.then(g,g),p),o,c={};return t=t.apply(n,e),c[Xe("asyncIterator")]=()=>c,a("next"),a("throw"),a("return"),c};import nt from"axios";import Ke from"axios-retry";var Re="https://api.ecodrix.com";function Fe(n="v1",e=Re){return`${e.replace(/\/+$/,"")}/${n}/api`}var Pe=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends Pe{constructor(t,r,a){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=r,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},x=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var s=class{constructor(e){i(this,"client",e)}async post(e,t,r){try{let a=this.buildConfig(r);return(await this.client.post(e,t,a)).data}catch(a){this.handleError(a)}}async get(e,t){try{let r=this.buildConfig(t);return(await this.client.get(e,r)).data}catch(r){this.handleError(r)}}async patch(e,t,r){try{let a=this.buildConfig(r);return(await this.client.patch(e,t,a)).data}catch(a){this.handleError(a)}}async put(e,t,r){try{let a=this.buildConfig(r);return(await this.client.put(e,t,a)).data}catch(a){this.handleError(a)}}async deleteRequest(e,t){try{let r=this.buildConfig(t);return(await this.client.delete(e,r)).data}catch(r){this.handleError(r)}}buildConfig(e){if(!e)return;let t=m({},e);return e.idempotencyKey&&(t.headers=w(m({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,r,a;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((r=e.response.data)==null?void 0:r.error)||"API Request Failed",l=(a=e.response.data)==null?void 0:a.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new x(c);default:throw new u(c,o,l)}}throw new u(e.message||"Network Error")}};var ke=class extends s{async list(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/product/erix/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/product/erix/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/product/erix/crm/notes/${e}`)}},D=class extends s{constructor(t){super(t);i(this,"notes");this.notes=new ke(t)}async timeline(t,r){return this.get(`/product/erix/crm/leads/${t}/timeline`,{params:r})}async list(t,r){return this.get(`/product/erix/crm/leads/${t}/activities`,{params:m({},r)})}async log(t){return this.post(`/product/erix/crm/leads/${t.leadId}/activities`,t)}async logCall(t,r){return this.post(`/product/erix/crm/leads/${t}/calls`,r)}};var L=class extends s{async overview(e){return this.get("/product/erix/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/product/erix/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/product/erix/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/product/erix/crm/analytics/sources",{params:e})}async team(e){return this.get("/product/erix/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/product/erix/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/product/erix/crm/analytics/scores")}async stageTime(e){return this.get("/product/erix/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/product/erix/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/product/erix/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/product/erix/crm/analytics/whatsapp",{params:e})}async revenue(){return this.get("/product/erix/crm/analytics/revenue")}async health(){return this.get("/product/erix/crm/analytics/health")}async payments(){return this.get("/product/erix/crm/analytics/payments")}async reviews(){return this.get("/product/erix/crm/analytics/reviews")}async retention(){return this.get("/product/erix/crm/analytics/retention")}};var q=class extends s{async getChecklist(e){return this.get(`/product/erix/crm/documents/checklist/${e}`)}async createChecklist(e,t){return this.post(`/product/erix/crm/documents/checklist/${e}`,{templateNiche:t})}async markReceived(e,t,r){return this.patch(`/product/erix/crm/documents/checklist/${e}/${t}`,r?{fileUrl:r}:{})}async sendReminder(e){return this.post(`/product/erix/crm/documents/checklist/${e}/remind`)}async listIncomplete(){return this.get("/product/erix/crm/documents/checklist/incomplete")}async listTemplates(){return this.get("/product/erix/crm/documents/templates")}};var _=class extends s{async csv(e){return this.get("/product/erix/commerce/invoices/export/csv",{params:e})}async tally(e){return this.get("/product/erix/commerce/invoices/export/tally",{params:e})}async zoho(e){return this.get("/product/erix/commerce/invoices/export/zoho",{params:e})}};var je=["open","won","lost","archived"],U=class extends s{async create(e){return this.post("/product/erix/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],r=[{key:"firstName",label:"First Name",type:"string",required:!0,group:"Basic Info"},{key:"lastName",label:"Last Name",type:"string",required:!1,group:"Basic Info"},{key:"phone",label:"Phone Number",type:"phone",required:!0,group:"Contact"},{key:"email",label:"Email Address",type:"email",required:!1,group:"Contact"},{key:"status",label:"Status",type:"select",required:!0,options:je.map(o=>({label:`${o.charAt(0).toUpperCase()}${o.slice(1)}`,value:o}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],a=t.map(o=>({key:`metadata.extra.${o.name}`,label:o.label||o.name,type:o.type||"string",required:!!o.required,options:o.options,group:"Custom Fields"}));return{name:"Lead",fields:[...r,...a],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/product/erix/crm/leads/upsert",e)}async createMany(e,t=50){let r=[];for(let a=0;a<e.length;a+=t){let c=e.slice(a,a+t).map(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")r.push(p.value);else throw p.reason}return r}async import(e){return this.post("/product/erix/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=m({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return Ve(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let a=yield new we(this.list(w(m({},e),{page:t}))),o=Array.isArray(a.data)?a.data:a||[];if(o.length===0){r=!1;break}for(let c of o)yield c;a.pagination&&t<a.pagination.pages||!a.pagination&&o.length>0?t++:r=!1}})}async retrieve(e){return this.get(`/product/erix/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/product/erix/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,r={}){return this.get(`/product/erix/crm/pipelines/${e}/stages/${t}/leads`,{params:r})}async retrieveByRef(e,t){return this.get(`/product/erix/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/product/erix/crm/leads/${e}`,t)}async setFollowUp(e,t,r){return this.patch(`/product/erix/crm/leads/${e}`,{nextFollowUpAt:t,nextFollowUpNote:t&&r!=null?r:null})}async move(e,t){return this.patch(`/product/erix/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,r){return this.post(`/product/erix/crm/leads/${e}/convert`,{outcome:t,reason:r})}async tags(e,t){return this.patch(`/product/erix/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/product/erix/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/product/erix/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/product/erix/crm/fields")}async notes(e){return this.get(`/product/erix/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/product/erix/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/product/erix/crm/leads/${e}/notes`,t)}async updateNote(e,t,r){return this.patch(`/product/erix/crm/notes/${t}`,r)}async deleteNote(e,t){return this.deleteRequest(`/product/erix/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/product/erix/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/product/erix/crm/leads",{data:{ids:e}})}async archive(e){return this.deleteRequest(`/product/erix/crm/leads/${e}`)}async profile(e){return this.get(`/product/erix/crm/leads/${e}/profile`)}async invoices(e){return this.get(`/product/erix/crm/leads/${e}/invoices`)}async projects(e){return this.get(`/product/erix/crm/leads/${e}/projects`)}async conversations(e){return this.get(`/product/erix/crm/leads/${e}/conversations`)}async meetings(e){return this.get(`/product/erix/crm/leads/${e}/meetings`)}async flowRuns(e){return this.get(`/product/erix/crm/leads/${e}/flow-runs`)}async merge(e,t){return this.post("/product/erix/crm/leads/merge",{primaryId:e,secondaryId:t})}};var N=class extends s{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var B=class extends s{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var a,o;let t=await this.retrieve(e),r=Array.isArray((a=t.data)==null?void 0:a.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:r.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/product/erix/crm/pipelines",e)}async retrieve(e){return this.get(`/product/erix/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/product/erix/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/product/erix/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/product/erix/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/product/erix/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/product/erix/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/product/erix/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/product/erix/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/product/erix/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/product/erix/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/product/erix/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/product/erix/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/product/erix/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var V=class extends s{async getConfig(){return this.get("/product/erix/crm/scoring")}async updateConfig(e){return this.patch("/product/erix/crm/scoring",e)}async recalculate(e){return this.post(`/product/erix/crm/scoring/${e}/recalculate`,{})}async preview(e){return this.get(`/product/erix/crm/scoring/preview/${e}`)}};var F=class extends s{async list(e){return this.get("/platform/inbox/conversations",{params:e})}async create(e){var t;return this.post("/platform/inbox/conversations",{address:e.phone,channel:(t=e.channel)!=null?t:"whatsapp",userName:e.name})}async linkLead(e,t){return this.patch(`/platform/inbox/conversations/${e}/lead`,{leadId:t})}async retrieve(e){return this.get(`/platform/inbox/conversations/${e}`)}async messages(e,t){return this.get(`/platform/inbox/conversations/${e}/messages`,{params:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/platform/inbox/conversations/${e}`)}async bulkDelete(e){return this.post("/platform/inbox/conversations/bulk-delete",{ids:e})}};var P=class extends s{async send(e){if(e.conversationId)return this.post(`/platform/inbox/conversations/${e.conversationId}/messages`,{text:e.text,media:e.media});if(!e.to)throw new Error("send: conversationId or to is required");if(e.media)throw new Error("send: media goes to an inbox thread (conversationId)");return this.post("/infra/connect/send/whatsapp",{phone:e.to,text:e.text})}async sendTemplate(e){return this.post("/infra/connect/send/whatsapp",{phone:e.to,templateName:e.templateName,language:e.language,variables:e.variables})}async star(e,t){return this.post(`/platform/inbox/messages/${e}/star`,{starred:t})}async markRead(e){return this.post(`/platform/inbox/conversations/${e}/read`,{})}async upload(e,t={}){var f,g,T;let r=(g=(f=t.fileName)!=null?f:e.name)!=null?g:"file",a=e.type||"application/octet-stream",o=await this.post("/infra/storage/files/upload-url",{folder:(T=t.folder)!=null?T:"inbox",filename:r,contentType:a}),{uploadUrl:c,key:l}=o.data,p=await fetch(c,{method:"PUT",headers:{"Content-Type":a},body:e});if(!p.ok)throw new Error(`upload failed (${p.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:l,sizeBytes:e.size}),{key:l,mimeType:a,fileName:r}}};var j=class extends s{async getProduct(e){return this.get(`/product/erix/commerce/checkout/products/${e}`)}async createSession(e){return this.post("/product/erix/commerce/checkout/session",e)}async applyCoupon(e){return this.post("/product/erix/commerce/checkout/coupon",e)}async verify(e){return this.post("/product/erix/commerce/checkout/verify",e)}async createOrder(e){return this.post("/product/erix/commerce/checkout/order",e)}};var K=class extends s{async trigger(e){return this.post("/product/erix/events/trigger",e)}async listCustomEvents(){return this.get("/product/flow/config/triggers")}async createCustomEvent(e){return this.post("/product/flow/config/triggers",e)}async deleteCustomEvent(e){return this.deleteRequest(`/product/flow/config/triggers/${e}`)}};var H=class extends s{async list(e){return this.get("/product/erix/commerce/invoices",{params:e})}async getInvoice(e){return this.get(`/product/erix/commerce/invoices/${e}`)}async create(e){return this.post("/product/erix/commerce/invoices",e)}async update(e,t){return this.patch(`/product/erix/commerce/invoices/${e}`,t)}async void(e){return this.post(`/product/erix/commerce/invoices/${e}/void`,{})}async sendViaWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${e}/send-whatsapp`,{})}async getSettings(){return this.get("/product/erix/commerce/settings")}async updateSettings(e){return this.put("/product/erix/commerce/settings",e)}};var W=class extends s{async workflowPacks(){return this.get("/product/erix/crm/niche/workflow-packs")}async workflowPackDetail(e){return this.get(`/product/erix/crm/niche/workflow-packs/${e}`)}async installWorkflowPack(e){return this.post(`/product/erix/crm/niche/workflow-packs/${e}/install`)}async templateSuggestions(){return this.get("/product/erix/crm/niche/template-suggestions")}};var z=class extends s{async list(e){return this.get(`/product/erix/commerce/projects/${e}/documents`)}async upload(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents`,t)}async toggleSignature(e,t,r){return this.patch(`/product/erix/commerce/projects/${e}/documents/${t}/signature`,{required:r})}async addSigner(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/signers`,r)}async sign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/sign`,r!=null?r:{})}async decline(e,t){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/decline`,{})}async stampSign(e,t,r){return this.post(`/product/erix/commerce/projects/${e}/documents/${t}/stamp-sign`,r)}};var G=class extends s{async providers(){return this.get("/infra/connect/providers")}async list(){return this.get("/infra/connect/connections")}async get_(e){return this.get(`/infra/connect/connections/${e}`)}async connect(e,t){return this.post(`/infra/connect/connections/${e}/connect`,t)}async configure(e,t){return this.put(`/infra/connect/connections/${e}/configure`,t)}async disconnect(e){return this.post(`/infra/connect/connections/${e}/disconnect`,{})}async reveal(e){return this.post(`/infra/connect/connections/${e}/reveal`,{})}async test(e){return this.post(`/infra/connect/connections/${e}/test`,{})}async setAccess(e,t){return this.put(`/infra/connect/connections/${e}/access`,t)}async googleConnectUrl(){return this.post("/infra/connect/google/connect-url",{})}async createPaymentLink(e){return this.post("/infra/connect/connections/payments/payment-link",e)}};var Q=class extends s{async sendTest(e){return this.post("/infra/connect/email/test",{to:e})}async listTemplates(e){return this.get("/infra/connect/email/templates",{params:e})}async getTemplate(e){return this.get(`/infra/connect/email/templates/${e}`)}async createTemplate(e){return this.post("/infra/connect/email/templates",e)}async updateTemplate(e,t){return this.put(`/infra/connect/email/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/infra/connect/email/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/infra/connect/email/templates/${e}/preview`,t)}};var Y=class extends s{async create(e){return this.post("/infra/connect/meet",e)}async list(e){return this.get("/infra/connect/meet",{params:e})}async retrieve(e){return this.get(`/infra/connect/meet/${e}`)}async update(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/infra/connect/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var J=class extends s{async getConfig(){return this.get("/infra/connect/email/config")}async initDomainVerification(e){return this.post("/infra/connect/email/config/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/infra/connect/email/config/ses/config",e)}async checkSesVerification(){return this.get("/infra/connect/email/config/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/infra/connect/email/config/ses/domain")}async sendTest(e){return this.post("/infra/connect/email/config/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/infra/connect/email/config/advanced",e)}async getHealth(){return this.get("/infra/connect/email/config/health")}async fixDmarc(){return this.post("/infra/connect/email/config/ses/fix-dmarc",{})}async listProviders(){return this.get("/infra/connect/email/config/providers")}};var X=class extends s{async list(e){return this.get("/infra/connect/whatsapp/templates",{params:e})}async sync(){return this.post("/infra/connect/whatsapp/templates/sync",{})}async retrieve(e){return this.get(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/infra/connect/whatsapp/templates",e)}async update(e,t){return this.put(`/infra/connect/whatsapp/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/infra/connect/whatsapp/templates/mapping/config")}async mappingSources(){return this.get("/infra/connect/whatsapp/templates/mapping/sources")}async collections(){return this.get("/infra/connect/whatsapp/templates/collections")}async collectionFields(e){return this.get(`/infra/connect/whatsapp/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e,t){let r=`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/validate`;return t?this.post(r,t):this.get(r)}async preview(e,t,r,a){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:r,onEmptyVariable:a})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),r=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],a=[];for(let l of r)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let f of p){let g=f.replace(/{{|}}/g,"");a.push({key:`var_${g}`,label:`${l.type} Var {{${g}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:a,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import Ze from"axios";var Z=class extends s{async getUsage(){return this.get("/infra/storage/files/usage")}async createFolder(e){return this.post("/infra/storage/files/folders",{name:e})}async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async aiDescribe(e){return this.post("/infra/storage/files/ai/describe",{key:e})}async upload(e,t){let r=await this.post("/infra/storage/files/upload-url",t),{uploadUrl:a,key:o}=r.data;await Ze.put(a,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:o,sizeBytes:c})}};var ee=class extends s{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},te=class extends s{async list(e,t){return this.get(`/infra/storage/files/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/infra/storage/files/upload-url",e)}async confirmUpload(e){return this.post("/infra/storage/files/confirm-upload",e)}async getDownloadUrl(e){return this.post("/infra/storage/files/download-url",{key:e})}async delete(e){return this.deleteRequest("/infra/storage/files/files",{params:{key:e}})}};var ne=class extends s{async system(){return(await this.get("/health")).data}};var re=class extends s{async listAlerts(e){return this.get("/platform/users/notifications",{params:e})}async dismissAlert(e){return this.patch(`/platform/users/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/platform/users/notifications/dismiss-all")}};var v=class extends s{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var I=class extends s{async get(e){return super.get(`/platform/tenants/persona/${e}`)}async reinforce(e){return this.post(`/platform/tenants/persona/${e.productId}/reinforce`,e)}async confidence(e){return super.get(`/platform/tenants/persona/${e}/confidence`,{params:{productId:e}})}async timeline(e,t){var a;let r=await super.get(`/platform/tenants/persona/${e}/timeline`,{params:t});return(a=r==null?void 0:r.data)!=null?a:{entries:[],hasMore:!1}}async followups(e){var r,a;let t=await super.get(`/platform/tenants/persona/${e}/followups`);return(a=(r=t==null?void 0:t.data)==null?void 0:r.entries)!=null?a:[]}};var Ae=class extends s{async chatSync(e){return this.post("/platform/ai/copilot/chat/sync",e)}async confirm(e){return this.post("/platform/ai/copilot/confirm",e)}async listSessions(){return this.get("/platform/ai/copilot/sessions")}async getSession(e){return this.get(`/platform/ai/copilot/sessions/${e}`)}async deleteSession(e){return this.deleteRequest(`/platform/ai/copilot/sessions/${e}`)}chatStreamUrl(){return"/platform/ai/copilot/chat"}},se=class{constructor(e){i(this,"copilot");this.copilot=new Ae(e)}};var et=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/markdown","text/csv","text/html","image/png","image/jpeg","image/webp"],S=class extends s{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",m({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",m({kind:"url"},e))}async addFile(e,t={}){var a,o;let r=await new P(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(o=(a=t.title)!=null?a:r.fileName)!=null?o:"Document"})}async remove(e){return this.deleteRequest(`/platform/knowledge/sources/${e}`)}async reindex(e){return this.post(`/platform/knowledge/sources/${e}/reindex`,{})}async search(e,t){return this.post("/platform/knowledge/search",m({query:e},t?{limit:t}:{}))}};var C=class extends s{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async suggestion(e){return this.get(`/product/erix/ai/suggestion/${e}`)}async approveAction(e){return this.post(`/product/erix/ai/suggestion/${e}/approve-action`,{})}async markSent(e,t,r){return this.post(`/product/erix/ai/suggestion/${e}/send`,{text:t,confidence:r})}async dismiss(e){return this.post(`/product/erix/ai/suggestion/${e}/dismiss`,{})}async approvals(){return this.get("/product/flow/approvals")}async agents(){return this.get("/product/flow/agents")}async updateAgent(e,t){return this.patch(`/product/flow/agents/${encodeURIComponent(e)}`,t)}async decideRun(e,t){return this.post(`/product/flow/runs/${e}/approve`,{decision:t})}};var ie=class extends s{async register(e){return this.post("/platform/auth/register",e)}async login(e){return this.post("/platform/auth/login",e)}async logout(e){return this.post("/platform/auth/logout",e)}async logoutAll(e){return this.post("/platform/auth/logout-all",e)}async validateSession(e){return this.post("/platform/auth/session/validate",e)}async listSessions(){return this.get("/platform/auth/sessions")}async revokeSession(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}async requestPasswordOtp(e){return this.post("/platform/auth/password/request-otp",e)}async setPassword(e){return this.post("/platform/auth/password/set",e)}async changePassword(e){return this.post("/platform/auth/password/change",e)}async forgotPassword(e){return this.post("/platform/auth/forgot",e)}async resetPassword(e){return this.post("/platform/auth/reset",e)}async linkOAuth(e){return this.post("/platform/auth/oauth-link",e)}async getInvitation(e){return this.get(`/platform/auth/invitations/${e}`)}async acceptInvitation(e,t){return this.post(`/platform/auth/invitations/${e}/accept`,t)}};var ve=class extends s{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},Ie=class extends s{async upgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/upgrade",e)}async downgrade(e){return this.post("/platform/billing/subscriptions/subscriptions/downgrade",e)}async cancel(e){return this.post("/platform/billing/subscriptions/subscriptions/cancel",e)}async purchaseAddon(e){return this.post("/platform/billing/subscriptions/addons/purchase",e)}async cancelAddon(e){return this.post("/platform/billing/subscriptions/addons/cancel",e)}},Se=class extends s{async listPublic(){return this.get("/platform/billing/plans/public")}},Ce=class extends s{async plans(){return this.get("/platform/billing/checkout/plans")}async subscribe(e){return this.post("/platform/billing/checkout/subscribe",e)}async verify(e){return this.post("/platform/billing/checkout/verify",e)}async cancel(e){return this.post("/platform/billing/checkout/cancel",e)}async status(){return this.get("/platform/billing/checkout/status")}async syncPlan(e){return this.post("/platform/billing/checkout/sync-plan",e)}},Ee=class extends s{async transactions(){return this.get("/platform/billing/user/transactions")}async subscription(){return this.get("/platform/billing/user/subscription")}async raiseDispute(e){return this.post("/platform/billing/user/dispute",e)}async disputes(){return this.get("/platform/billing/user/disputes")}},$e=class extends s{async balance(){return this.get("/platform/billing/credits/balance")}async transactions(){return this.get("/platform/billing/credits/transactions")}async packs(){return this.get("/platform/billing/credits/packs")}async topupOrder(e){return this.post("/platform/billing/credits/topup/order",e)}async verifyTopup(e){return this.post("/platform/billing/credits/topup/verify",e)}async setAutoTopup(e){return this.patch("/platform/billing/credits/auto-topup",e)}async setSpendCap(e){return this.patch("/platform/billing/credits/spend-cap",e)}},ae=class{constructor(e){i(this,"entitlements");i(this,"subscriptions");i(this,"plans");i(this,"checkout");i(this,"user");i(this,"credits");this.entitlements=new ve(e),this.subscriptions=new Ie(e),this.plans=new Se(e),this.checkout=new Ce(e),this.user=new Ee(e),this.credits=new $e(e)}};var oe=class extends s{async categories(){return this.get("/platform/support/categories")}async listTickets(e){return this.get("/platform/support/tickets",{params:e})}async createTicket(e){return this.post("/platform/support/tickets",e)}async getTicket(e){return this.get(`/platform/support/tickets/${e}`)}async reply(e,t){return this.post(`/platform/support/tickets/${e}/reply`,t)}async close(e){return this.patch(`/platform/support/tickets/${e}/close`,{})}};var ce=class extends s{async get(){return super.get("/platform/users/me")}async update(e){return this.patch("/platform/users/me",e)}async updateOrganization(e){return this.patch("/platform/users/me/organization",e)}async toggleModules(e){return this.post("/platform/users/me/modules",e)}async workspaces(){return super.get("/platform/users/me/workspaces")}async setActiveOrg(e){return this.post("/platform/users/me/active-org",e)}async dismissWorkspaceSetup(){return this.post("/platform/users/me/workspace/dismiss-setup",{})}},pe=class extends s{async list(){return this.get("/platform/users/members")}async invite(e){return this.post("/platform/users/members/invite",e)}async updateRole(e,t){return this.patch(`/platform/users/members/${e}`,{role:t})}async remove(e){return this.deleteRequest(`/platform/users/members/${e}`)}},le=class extends s{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var ue=class{constructor(e){i(this,"messages");i(this,"conversations");this.messages=new P(e),this.conversations=new F(e)}},ge=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"scoring");i(this,"payments");i(this,"chat");i(this,"events");i(this,"invoices");i(this,"checkout");i(this,"projects");i(this,"niche");i(this,"documents");i(this,"invoiceExport");i(this,"ai");this.leads=new U(e),this.pipelines=new B(e),this.activities=new D(e),this.analytics=new L(e),this.scoring=new V(e),this.payments=new N(e),this.chat=new ue(e),this.events=new K(e),this.invoices=new H(e),this.checkout=new j(e),this.projects=new z(e),this.niche=new W(e),this.documents=new q(e),this.invoiceExport=new _(e),this.ai=new C(e)}},E=class{constructor(e){i(this,"erix");this.erix=new ge(e)}},de=class{constructor(e){i(this,"config");i(this,"templates");this.config=new J(e),this.templates=new Q(e)}},me=class{constructor(e){i(this,"templates");this.templates=new X(e)}},ye=class{constructor(e){i(this,"email");i(this,"whatsapp");i(this,"meet");i(this,"connections");this.email=new de(e),this.whatsapp=new me(e),this.meet=new Y(e),this.connections=new G(e)}},fe=class{constructor(e){i(this,"files");i(this,"folders");i(this,"media");this.files=new te(e),this.folders=new ee(e),this.media=new Z(e)}},$=class{constructor(e){i(this,"connect");i(this,"storage");this.connect=new ye(e),this.storage=new fe(e)}},he=class{constructor(e){i(this,"onboarding");i(this,"persona");this.onboarding=new v(e),this.persona=new I(e)}},Te=class{constructor(e){i(this,"me");i(this,"members");i(this,"sessions");i(this,"notifications");this.me=new ce(e),this.members=new pe(e),this.sessions=new le(e),this.notifications=new re(e)}},O=class{constructor(e){i(this,"auth");i(this,"users");i(this,"tenants");i(this,"billing");i(this,"support");i(this,"ai");i(this,"knowledge");i(this,"health");this.auth=new ie(e),this.users=new Te(e),this.tenants=new he(e),this.billing=new ae(e),this.support=new oe(e),this.ai=new se(e),this.knowledge=new S(e),this.health=new ne(e)}};var k=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},xe=class{async constructEvent(e,t,r){if(!t)throw new k("No webhook signature provided");let a=Array.isArray(t)?t[0]:t;a.startsWith("sha256=")&&(a=a.slice(7));try{let o=await import("crypto"),l=o.createHmac("sha256",r).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(a)))throw new k("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof k?o:new k(`Webhook payload parsing failed: ${o.message}`)}}};var Oe=typeof process!="undefined"&&"3.1.1"||"2.0.0";var He,Me=(He=Ke.default)!=null?He:Ke,A=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"apiVersion");i(this,"platform");i(this,"product");i(this,"infra");i(this,"webhooks");i(this,"lastSeq");i(this,"closed",!1);var g,T,b,R,d,De,Le,qe;let t=e.proxy;if(!e.apiKey&&!t)throw new y("API Key is required");this.clientCode=(g=e.clientCode)==null?void 0:g.toUpperCase(),this.apiVersion=(T=e.version)!=null?T:"v1";let r=(b=e.baseUrl)!=null?b:Re,a=Fe(this.apiVersion,(R=t==null?void 0:t.url)!=null?R:r),o=e.socketUrl||r,c=typeof window!="undefined"&&typeof window.document!="undefined",l=c?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",p=c?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",f=w(m({},t?{}:{"x-api-key":e.apiKey,"x-client-code":((De=e.clientCode)==null?void 0:De.toUpperCase())||""}),{"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Oe,runtime:l,os:p})});if(this.client=nt.create({baseURL:a,headers:f,timeout:(Le=e.timeout)!=null?Le:3e4}),Me(this.client,{retries:3,retryDelay:Me.exponentialDelay,retryCondition:h=>{var M;return Me.isNetworkOrIdempotentRequestError(h)||((M=h.response)==null?void 0:M.status)===429},onRetry:(h,M,_e)=>{var Ue,Ne;typeof process!="undefined"&&((Ue=process.env)==null?void 0:Ue.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(Ne=_e.method)==null?void 0:Ne.toUpperCase()} ${_e.url}. Reason: ${M.message}`)}}),this.platform=new O(this.client),this.product=new E(this.client),this.infra=new $(this.client),this.webhooks=new xe,t){if(t.ticket){let h=t.ticket;this.initSocket(o,async()=>({ticket:await h()}))}}else{let h={apiKey:e.apiKey,clientCode:((qe=e.clientCode)==null?void 0:qe.toUpperCase())||""};this.initSocket(o,async()=>h,{"x-api-key":h.apiKey,"x-client-code":h.clientCode})}if(c){let h={version:Oe,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h}}initSocket(e,t,r){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:a})=>{this.socket=a(e,{auth:o=>{t().then(c=>o(w(m({},c),{lastSeq:this.lastSeq})),()=>o({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(){this.socket&&(this.socket.on("connect_error",()=>{var e;(e=this.socket)!=null&&e.active||setTimeout(()=>{var t;this.closed||(t=this.socket)==null||t.connect()},5e3)}),this.socket.onAny((...e)=>{var r,a;let t=(r=e.at(-1))==null?void 0:r.seq;typeof t=="number"&&t>((a=this.lastSeq)!=null?a:0)&&(this.lastSeq=t)}))}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.closed=!0,this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,r,a){var o,c,l;try{return(await this.client.request({method:e,url:t,data:r,params:a})).data}catch(p){throw p.response?new u(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new u(p.message||"Network Error")}}};var rt={401:y,403:y,429:x};function Cr(n){var e,t,r;if(n.response){let a=n.response.status,o=((e=n.response.data)==null?void 0:e.message)||((t=n.response.data)==null?void 0:t.error)||"API Request Failed",c=(r=n.response.data)==null?void 0:r.code,l=rt[a]||u;throw l===y?new y(o):l===x?new x(o):new u(o,a,c)}throw new u(n.message||"Network Error")}function Er(n,e){return n instanceof e}function $r(n){return n instanceof y?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof x?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof u?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var We={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[x.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Or(n){let e=n.constructor.name;return We[e]||We[u.name]}var Lr=A;export{u as APIError,s as APIResource,C as AiAgent,y as AuthenticationError,ye as ConnectInfra,A as ECODrIx,A as ECODrIxAPI,We as ERROR_RETRY_CONFIG,Pe as EcodrixError,de as EmailConnect,ue as ErixChat,ge as ErixProduct,rt as HTTP_STATUS_ERROR_MAP,$ as InfraDomain,et as KNOWLEDGE_FILE_TYPES,S as Knowledge,je as LEAD_STATUS_VALUES,v as Onboarding,I as Persona,O as PlatformDomain,he as PlatformTenants,Te as PlatformUsers,E as ProductDomain,x as RateLimitError,fe as StorageInfra,me as WhatsAppConnect,Lr as default,$r as getErrorDetails,Or as getRetryConfig,Cr as handleAPIError,Er as isAPIError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecodrix/erix-api",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "author": "ECODrIx Team <contact@ecodrix.com>",
5
5
  "license": "MIT",
6
6
  "description": "Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",