@ecodrix/erix-api 3.2.0 → 3.3.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/README.md +13 -3
- package/dist/cli.js +8 -8
- package/dist/ts/cjs/index.cjs +1 -1
- package/dist/ts/cjs/visitor.cjs +1 -1
- package/dist/ts/esm/{error-DuNpKP1d.d.ts → error-Bl2AN2QP.d.ts} +14 -1
- package/dist/ts/esm/index.d.ts +509 -64
- package/dist/ts/esm/index.js +1 -1
- package/dist/ts/esm/visitor.d.ts +20 -4
- package/dist/ts/esm/visitor.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Telegram, email, webchat), invoices and payment links, file storage, and live
|
|
|
10
10
|
events. Every call is scoped to the workspace your key belongs to.
|
|
11
11
|
|
|
12
12
|
- Developer guide: https://api.ecodrix.com/docs
|
|
13
|
-
- API
|
|
13
|
+
- API docs: https://api.ecodrix.com/docs
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -223,6 +223,7 @@ Live replies and typing (`/visitor` socket):
|
|
|
223
223
|
chat.connect({
|
|
224
224
|
onMessage: (message) => upsert(message), // `from`: visitor | ai | team | system
|
|
225
225
|
onTyping: ({ on, waiting }) => showTyping(on, waiting), // waiting: the team will reply
|
|
226
|
+
onStatus: ({ ids, status }) => markTicks(ids, status), // "read": the team opened the chat
|
|
226
227
|
onError: () => startPolling(), // live is down: poll messages()
|
|
227
228
|
onReconnect: () => {
|
|
228
229
|
stopPolling();
|
|
@@ -233,6 +234,16 @@ chat.connect({
|
|
|
233
234
|
chat.disconnect();
|
|
234
235
|
```
|
|
235
236
|
|
|
237
|
+
Ticks, as on WhatsApp. Each message has `status` (`sent` ✓, `delivered` ✓✓,
|
|
238
|
+
`read` ✓✓ seen): the visitor's own are `delivered` once stored and `read` once
|
|
239
|
+
the team opened the chat. Report the business's replies back, up to 50 ids a
|
|
240
|
+
call; ticks only move forward:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
await chat.receipts(replyIds, "delivered"); // the chat got them
|
|
244
|
+
await chat.receipts(replyIds, "read"); // open and on screen
|
|
245
|
+
```
|
|
246
|
+
|
|
236
247
|
| `err.code` | Meaning |
|
|
237
248
|
| -------------------- | ----------------------------------------------------------------- |
|
|
238
249
|
| `VALIDATION_ERROR` | Bad input. `err.field` names it, `err.message` is visitor copy |
|
|
@@ -651,8 +662,7 @@ for await (const lead of ecod.product.erix.leads.listAutoPaging<Lead>({ status:
|
|
|
651
662
|
version.
|
|
652
663
|
- A method marked **(3.2.0)** needs SDK 3.2.0 or later.
|
|
653
664
|
|
|
654
|
-
Guides: https://api.ecodrix.com/docs.
|
|
655
|
-
https://api.ecodrix.com/reference.
|
|
665
|
+
Guides and every endpoint: https://api.ecodrix.com/docs.
|
|
656
666
|
|
|
657
667
|
## License
|
|
658
668
|
|
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Ve from"repl";import{Command as Be}from"commander";import Fe from"dotenv";import o from"picocolors";import Ue from"axios";import Ee from"axios-retry";var ae="https://api.ecodrix.com";function Ce(r="v1",e=ae){return`${e.replace(/\/+$/,"")}/${r}/api`}var oe=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends oe{status;code;issues;field;constructor(e,t,n){super(e),this.name="APIError",this.status=t,this.code=n}},f=class extends m{constructor(e="Invalid API Key or Client Code",t="AUTH_FAILED",n=401){super(e,n,t),this.name="AuthenticationError"}},ce=class extends f{constructor(e="You don't have permission to do this.",t="FORBIDDEN"){super(e,t,403),this.name="PermissionError"}},le=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};function $e(r){if(!r?.response)return new m(r?.message||"Network Error");let{status:e,data:t}=r.response,n=t?.message||t?.error||"API Request Failed",s=t?.code??(typeof t?.error=="string"&&/^[A-Z][A-Z0-9_]*$/.test(t.error)?t.error:void 0);switch(e){case 401:return new f(n,s);case 403:return new ce(n,s);case 429:return new le(n);default:{let i=new m(n,e,s);return Array.isArray(t?.issues)&&(i.issues=t.issues),typeof t?.field=="string"&&(i.field=t.field),i}}}var a=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){throw $e(e)}};var pe=class extends a{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}`)}},x=class extends a{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 w=class extends a{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 k=class extends a{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 v=class extends a{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 Le=["open","won","lost","archived"],R=class extends a{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:Le.map(i=>({label:`${i.charAt(0).toUpperCase()}${i.slice(1)}`,value:i}))},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],s=t.map(i=>({key:`metadata.extra.${i.name}`,label:i.label||i.name,type:i.type||"string",required:!!i.required,options:i.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}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){n=!1;break}for(let c of i)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&i.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 export(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/export`)}async erase(e){return this.post(`/product/erix/crm/leads/${encodeURIComponent(e)}/erase`,{confirm:"ERASE"})}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 a{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var P=class extends a{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`,{name: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 I=class extends a{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 S=class extends a{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 a{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",i=await this.post("/infra/storage/files/upload-url",{folder:t.folder??"inbox",filename:n,contentType:s}),{uploadUrl:c,key:g}=i.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 C=class extends a{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 $=class extends a{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 E=class extends a{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)}async paymentLink(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payment-link`,{})}async recordPayment(e,t){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payments`,t)}async sendWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-whatsapp`,{})}async sendEmail(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-email`,{})}};var O=class extends a{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 D=class extends a{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 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 M=class extends a{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 configureWebchat(e){return this.configure("webchat",{method:"domain",config:e})}async webchatSettings(){return this.get("/infra/connect/connections/webchat/settings")}async removeWebchatDomain(e){return this.deleteRequest(`/infra/connect/connections/webchat/domains/${encodeURIComponent(e)}`)}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 a{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 L=class extends a{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 _=class extends a{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 q=class extends a{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 i of n)if(i.text){let c=i.text.match(/{{(\d+)}}/g);if(c)for(let g of c){let u=g.replace(/{{|}}/g,"");s.push({key:`var_${u}`,label:`${i.type} Var {{${u}}}`,type:"string",required:!0,group:i.type,description:`Variable placeholder in template ${i.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import _e from"axios";var U=class extends a{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:i}=n.data;await _e.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:i,sizeBytes:c})}};var V=class extends a{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},B=class extends a{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 F=class extends a{async system(){return(await this.get("/health")).data}};var K=class extends a{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 a{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var j=class extends a{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 ue=class extends a{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"}},H=class{copilot;constructor(e){this.copilot=new ue(e)}};var z=class extends a{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 addWebsite(e){return this.post("/platform/knowledge/sources",{type:"website",url:e.url})}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 Y=class extends a{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async outcomes(e={}){return this.get("/product/erix/ai/outcomes",{params:e})}async reviews(e){return this.get(`/product/erix/ai/reviews${e?`?status=${e}`:""}`)}async review(e,t,n){return this.post(`/product/erix/ai/reviews/${encodeURIComponent(e)}`,{verdict:t,...n?{note:n}:{}})}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,n){return this.post(`/product/flow/runs/${encodeURIComponent(e)}/approve`,{decision:t,...n&&{nodeId:n}})}};var G=class extends a{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 ge=class extends a{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},de=class extends a{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)}},me=class extends a{async listPublic(){return this.get("/platform/billing/plans/public")}},ye=class extends a{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)}},he=class extends a{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 a{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)}},Q=class{entitlements;subscriptions;plans;checkout;user;credits;constructor(e){this.entitlements=new ge(e),this.subscriptions=new de(e),this.plans=new me(e),this.checkout=new ye(e),this.user=new he(e),this.credits=new fe(e)}};var J=class extends a{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 X=class extends a{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",{})}},Z=class extends a{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}`)}},ee=class extends a{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var Te=class{messages;conversations;constructor(e){this.messages=new T(e),this.conversations=new S(e)}},be=class{leads;pipelines;activities;analytics;scoring;payments;chat;events;invoices;checkout;projects;niche;documents;invoiceExport;ai;constructor(e){this.leads=new R(e),this.pipelines=new P(e),this.activities=new x(e),this.analytics=new w(e),this.scoring=new I(e),this.payments=new A(e),this.chat=new Te(e),this.events=new $(e),this.invoices=new E(e),this.checkout=new C(e),this.projects=new D(e),this.niche=new O(e),this.documents=new k(e),this.invoiceExport=new v(e),this.ai=new Y(e)}},te=class{erix;constructor(e){this.erix=new be(e)}},xe=class{config;templates;constructor(e){this.config=new _(e),this.templates=new N(e)}},we=class{templates;constructor(e){this.templates=new q(e)}},ke=class{email;whatsapp;meet;connections;constructor(e){this.email=new xe(e),this.whatsapp=new we(e),this.meet=new L(e),this.connections=new M(e)}},ve=class{files;folders;media;constructor(e){this.files=new B(e),this.folders=new V(e),this.media=new U(e)}},ne=class{connect;storage;constructor(e){this.connect=new ke(e),this.storage=new ve(e)}},Re=class{onboarding;persona;constructor(e){this.onboarding=new W(e),this.persona=new j(e)}},Ae=class{me;members;sessions;notifications;constructor(e){this.me=new X(e),this.members=new Z(e),this.sessions=new ee(e),this.notifications=new K(e)}},re=class{auth;users;tenants;billing;support;ai;knowledge;health;constructor(e){this.auth=new G(e),this.users=new Ae(e),this.tenants=new Re(e),this.billing=new Q(e),this.support=new J(e),this.ai=new H(e),this.knowledge=new z(e),this.health=new F(e)}};var b=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},se=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 i=await import("crypto"),g=i.createHmac("sha256",n).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new b("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof b?i:new b(`Webhook payload parsing failed: ${i.message}`)}}};var Pe=typeof process<"u"&&"3.2.0"||"3.1.1";var Ie=Ee.default??Ee,ie=class{client;socket=null;startSocket=null;socketPromise=null;socketQueue=[];clientCode;apiVersion;platform;product;infra;webhooks;constructor(e){let t=e.proxy;if(!e.apiKey&&!t)throw new f("API Key is required");this.clientCode=e.clientCode?.toUpperCase(),this.apiVersion=e.version??"v1";let n=e.baseUrl??ae,s=Ce(this.apiVersion,t?.url??n),i=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",Me={...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=Ue.create({baseURL:s,headers:Me,timeout:e.timeout??3e4}),Ie(this.client,{retries:3,retryDelay:Ie.exponentialDelay,retryCondition:d=>Ie.isNetworkOrIdempotentRequestError(d)||d.response?.status===429,onRetry:(d,Ne,Se)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${d}/3): ${Se.method?.toUpperCase()} ${Se.url}. Reason: ${Ne.message}`)}}),this.platform=new re(this.client),this.product=new te(this.client),this.infra=new ne(this.client),this.webhooks=new se,t){if(t.ticket){let d=t.ticket;this.startSocket=()=>this.initSocket(i,async()=>({ticket:await d()}))}}else{let d={apiKey:e.apiKey,clientCode:e.clientCode?.toUpperCase()||""};this.startSocket=()=>this.initSocket(i,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:i=>{t().then(c=>i({...c,lastSeq:this.lastSeq}),()=>i({lastSeq:this.lastSeq}))},extraHeaders:n}),this.setupSocket();for(let{type:i,args:c}of this.socketQueue)i==="joinRoom"?this.socket.emit("join-room",c[0]):i==="leaveRoom"?this.socket.emit("leave-room",c[0]):i==="on"?this.socket.on(c[0],c[1]):i==="off"?this.socket.off(c[0],c[1]):i==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.closed||this.startSocket?.(),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.closed||this.startSocket?.(),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.socketPromise&&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(i){throw i.response?new m(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new m(i.message||"Network Error")}}};Fe.config();var Oe="3.2.0";var Ke="Official TypeScript SDK for the ERIX API by ECODrIx: CRM, Flow automations, one inbox across WhatsApp, Instagram and email, GST invoices and payments. Node and browser (proxy mode).",y=new Be;y.name("erix").description(Ke).version(Oe);function h(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 ie({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=h(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 We=y.command("whatsapp").description("WhatsApp Business API operations");We.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(),i=h(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${r}...`));let g=await i.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 De=y.command("crm").description("CRM and Lead management");De.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=h(t);try{let s=Number.parseInt(r.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};r.status&&(i.status=r.status),r.pipeline&&(i.pipelineId=r.pipeline),r.search&&(i.search=r.search);let c=await n.product.erix.leads.list(i),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))}});De.command("pipelines").description("List all CRM pipelines").action(async(r,e)=>{let t=e.parent.parent.opts(),n=h(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await n.product.erix.pipelines.list(),i=s.data||s||[];if(i.length===0){console.log(o.yellow("No pipelines found."));return}console.table(i.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 je=y.command("analytics").description("Business Intelligence Analytics");je.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=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${r.range}...`));let s=await n.product.erix.analytics.overview({range:r.range}),i=s.data||s;console.log(`
|
|
3
|
-
${
|
|
4
|
-
`)}catch(
|
|
5
|
-
Welcome to the Erix Interactive Shell`))),console.log(
|
|
6
|
-
`));let
|
|
7
|
-
Goodbye!`)),process.exit(0)})});
|
|
2
|
+
import je from"repl";import{Command as He}from"commander";import ze from"dotenv";import a from"picocolors";import We from"axios";import Ne from"axios-retry";var pe="https://api.ecodrix.com";function Me(s="v1",e=pe){return`${e.replace(/\/+$/,"")}/${s}/api`}var le=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},h=class extends le{status;code;issues;field;constructor(e,t,n){super(e),this.name="APIError",this.status=t,this.code=n}},x=class extends h{constructor(e="Invalid API Key or Client Code",t="AUTH_FAILED",n=401){super(e,n,t),this.name="AuthenticationError"}},ue=class extends x{constructor(e="You don't have permission to do this.",t="FORBIDDEN"){super(e,t,403),this.name="PermissionError"}},de=class extends h{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};function Le(s){if(!s?.response)return new h(s?.message||"Network Error");let{status:e,data:t}=s.response,n=t?.message||t?.error||"API Request Failed",r=t?.code??(typeof t?.error=="string"&&/^[A-Z][A-Z0-9_]*$/.test(t.error)?t.error:void 0);switch(e){case 401:return new x(n,r);case 403:return new ue(n,r);case 429:return new de(n);default:{let o=new h(n,e,r);return Array.isArray(t?.issues)&&(o.issues=t.issues),typeof t?.field=="string"&&(o.field=t.field),o}}}var i=class{constructor(e){this.client=e}client;async post(e,t,n){try{let r=this.buildConfig(n);return(await this.client.post(e,t,r)).data}catch(r){this.handleError(r)}}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 r=this.buildConfig(n);return(await this.client.patch(e,t,r)).data}catch(r){this.handleError(r)}}async put(e,t,n){try{let r=this.buildConfig(n);return(await this.client.put(e,t,r)).data}catch(r){this.handleError(r)}}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){throw Le(e)}};var ge=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}`)}},R=class extends i{notes;constructor(e){super(e),this.notes=new ge(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 v=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 P=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 A=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 Be=["open","won","lost","archived"],C=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:Be.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}],r=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:[...n,...r],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 r=0;r<e.length;r+=t){let c=e.slice(r,r+t).map(u=>this.create(u)),d=await Promise.allSettled(c);for(let u of d)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 r=await this.list({...e,page:t}),o=Array.isArray(r.data)?r.data:r||[];if(o.length===0){n=!1;break}for(let c of o)yield c;r.pagination&&t<r.pagination.pages||!r.pagination&&o.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 export(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/export`)}async erase(e){return this.post(`/product/erix/crm/leads/${encodeURIComponent(e)}/erase`,{confirm:"ERASE"})}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})}async duplicates(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/duplicates`)}};var I=class extends i{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var $=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(r=>({key:r._id,label:r.name,type:"string",required:!0,options:[{label:r.name,value:r._id}],group:"Stages",uiHints:{color:r.color||"#cbd5e1",probability:r.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`,{name: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 E=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 w=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",r=e.type||"application/octet-stream",o=await this.post("/infra/storage/files/upload-url",{folder:t.folder??"inbox",filename:n,contentType:r}),{uploadUrl:c,key:d}=o.data,u=await fetch(c,{method:"PUT",headers:{"Content-Type":r},body:e});if(!u.ok)throw new Error(`upload failed (${u.status})`);return await this.post("/infra/storage/files/confirm-upload",{key:d,sizeBytes:e.size}),{key:d,mimeType:r,fileName:n}}};var g="/product/erix/commerce/checkout",f="/product/erix/public/checkout",m=encodeURIComponent,me=class extends i{async getProduct(e,t){return this.get(`${f}/products/${m(t)}`,{params:{c:e}})}async viewSession(e,t){return this.get(`${f}/sessions/view`,{params:{c:e,t}})}async updateItems(e){let{sessionId:t,...n}=e;return this.post(`${f}/sessions/${m(t)}/items`,n)}async startSession(e){return this.post(`${f}/sessions`,e)}async applyCoupon(e){let{sessionId:t,...n}=e;return this.post(`${f}/sessions/${m(t)}/coupon`,n)}async verify(e){let{sessionId:t,...n}=e;return this.post(`${f}/sessions/${m(t)}/verify`,n)}async placeOrder(e){let{sessionId:t,...n}=e;return this.post(`${f}/sessions/${m(t)}/order`,n)}async verifyRazorpay(e){let{sessionId:t,orderId:n,...r}=e;return this.post(`${f}/sessions/${m(t)}/order/${m(n)}/razorpay`,r)}async orderStatus(e,t){return this.get(`${f}/orders/status`,{params:{c:e,t}})}async confirmCod(e,t){return this.post(`${f}/cod/confirm`,{clientCode:e,token:t})}},ye=class extends i{async create(e){return this.post(`${g}/sessions`,e)}},O=class extends i{buyer;sessions;constructor(e){super(e),this.buyer=new me(e),this.sessions=new ye(e)}async listProducts(){return this.get(`${g}/products`)}async createProduct(e){return this.post(`${g}/products`,e)}async updateProduct(e,t){return this.patch(`${g}/products/${m(e)}`,t)}async deleteProduct(e){return this.deleteRequest(`${g}/products/${m(e)}`)}async listCoupons(){return this.get(`${g}/coupons`)}async createCoupon(e){return this.post(`${g}/coupons`,e)}async updateCoupon(e,t){return this.patch(`${g}/coupons/${m(e)}`,t)}async deleteCoupon(e){return this.deleteRequest(`${g}/coupons/${m(e)}`)}async listOrders(e){return this.get(`${g}/orders`,{params:e})}async getOrder(e){return this.get(`${g}/orders/${m(e)}`)}async updateOrderStatus(e,t){return this.patch(`${g}/orders/${m(e)}/status`,t)}async getSettings(){return this.get(`${g}/settings`)}async updateSettings(e){return this.put(`${g}/settings`,e)}async createProductLink(e){return this.post(`${g}/links`,e)}};var D=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 M=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)}async paymentLink(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payment-link`,{})}async recordPayment(e,t){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payments`,t)}async sendWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-whatsapp`,{})}async sendEmail(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-email`,{})}};var L=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 N=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 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 q=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 configureWebchat(e){return this.configure("webchat",{method:"domain",config:e})}async webchatSettings(){return this.get("/infra/connect/connections/webchat/settings")}async removeWebchatDomain(e){return this.deleteRequest(`/infra/connect/connections/webchat/domains/${encodeURIComponent(e)}`)}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 _=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 U=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 V=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 B=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,r){return this.post(`/infra/connect/whatsapp/templates/${encodeURIComponent(e)}/preview`,{context:t,mappings:n,onEmptyVariable:r})}async getVariableManifest(e){let t=await this.retrieve(e),n=Array.isArray(t.data?.components)?t.data.components:[],r=[];for(let o of n)if(o.text){let c=o.text.match(/{{(\d+)}}/g);if(c)for(let d of c){let u=d.replace(/{{|}}/g,"");r.push({key:`var_${u}`,label:`${o.type} Var {{${u}}}`,type:"string",required:!0,group:o.type,description:`Variable placeholder in template ${o.type}`})}}return{name:`Template variables: ${t.data?.name||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};import Fe from"axios";var F=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:r,key:o}=n.data;await Fe.put(r,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 K=class extends i{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},W=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 j=class extends i{async system(){return(await this.get("/health")).data}};var H=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 z=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 Y=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 he=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"}},G=class{copilot;constructor(e){this.copilot=new he(e)}};var Q=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 addWebsite(e){return this.post("/platform/knowledge/sources",{type:"website",url:e.url})}async addFile(e,t={}){let n=await new w(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 J=class extends i{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async outcomes(e={}){return this.get("/product/erix/ai/outcomes",{params:e})}async reviews(e){return this.get(`/product/erix/ai/reviews${e?`?status=${e}`:""}`)}async review(e,t,n){return this.post(`/product/erix/ai/reviews/${encodeURIComponent(e)}`,{verdict:t,...n?{note:n}:{}})}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,n){return this.post(`/product/flow/runs/${encodeURIComponent(e)}/approve`,{decision:t,...n&&{nodeId:n}})}};var X=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 fe=class extends i{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},Te=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)}},be=class extends i{async listPublic(){return this.get("/platform/billing/plans/public")}},xe=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)}},we=class extends i{async transactions(){return this.get("/platform/billing/user/transactions")}async transactionInvoice(e){return this.get(`/platform/billing/user/transactions/${encodeURIComponent(e)}/invoice`)}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")}},ke=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)}},Z=class{entitlements;subscriptions;plans;checkout;user;credits;constructor(e){this.entitlements=new fe(e),this.subscriptions=new Te(e),this.plans=new be(e),this.checkout=new xe(e),this.user=new we(e),this.credits=new ke(e)}};var ee=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 te=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",{})}},ne=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}`)}},se=class extends i{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var Re=class{messages;conversations;constructor(e){this.messages=new w(e),this.conversations=new E(e)}},ve=class{leads;pipelines;activities;analytics;scoring;payments;chat;events;invoices;checkout;projects;niche;documents;invoiceExport;ai;constructor(e){this.leads=new C(e),this.pipelines=new $(e),this.activities=new R(e),this.analytics=new v(e),this.scoring=new S(e),this.payments=new I(e),this.chat=new Re(e),this.events=new D(e),this.invoices=new M(e),this.checkout=new O(e),this.projects=new N(e),this.niche=new L(e),this.documents=new P(e),this.invoiceExport=new A(e),this.ai=new J(e)}},re=class{erix;constructor(e){this.erix=new ve(e)}},Pe=class{config;templates;constructor(e){this.config=new V(e),this.templates=new _(e)}},Ae=class{templates;constructor(e){this.templates=new B(e)}},Ce=class{email;whatsapp;meet;connections;constructor(e){this.email=new Pe(e),this.whatsapp=new Ae(e),this.meet=new U(e),this.connections=new q(e)}},Ie=class{files;folders;media;constructor(e){this.files=new W(e),this.folders=new K(e),this.media=new F(e)}},ie=class{connect;storage;constructor(e){this.connect=new Ce(e),this.storage=new Ie(e)}},$e=class{onboarding;persona;constructor(e){this.onboarding=new z(e),this.persona=new Y(e)}},Se=class{me;members;sessions;notifications;constructor(e){this.me=new te(e),this.members=new ne(e),this.sessions=new se(e),this.notifications=new H(e)}},oe=class{auth;users;tenants;billing;support;ai;knowledge;health;constructor(e){this.auth=new X(e),this.users=new Se(e),this.tenants=new $e(e),this.billing=new Z(e),this.support=new ee(e),this.ai=new G(e),this.knowledge=new Q(e),this.health=new j(e)}};var k=class extends h{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},ae=class{async constructEvent(e,t,n){if(!t)throw new k("No webhook signature provided");let r=Array.isArray(t)?t[0]:t;r.startsWith("sha256=")&&(r=r.slice(7));try{let o=await import("crypto"),d=o.createHmac("sha256",n).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(d),Buffer.from(r)))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 Ee=typeof process<"u"&&"3.3.1"||"3.1.1";var Oe=Ne.default??Ne,ce=class{client;socket=null;startSocket=null;socketPromise=null;socketQueue=[];clientCode;apiVersion;platform;product;infra;webhooks;constructor(e){let t=e.proxy;if(!e.apiKey&&!t)throw new x("API Key is required");this.clientCode=e.clientCode?.toUpperCase(),this.apiVersion=e.version??"v1";let n=e.baseUrl??pe,r=Me(this.apiVersion,t?.url??n),o=e.socketUrl||n,c=typeof window<"u"&&typeof window.document<"u",d=c?"browser":typeof process<"u"?`node ${process.version}`:"unknown",u=c?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",Ue={...t?{}:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""},"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:Ee,runtime:d,os:u})};if(this.client=We.create({baseURL:r,headers:Ue,timeout:e.timeout??3e4}),Oe(this.client,{retries:3,retryDelay:Oe.exponentialDelay,retryCondition:y=>Oe.isNetworkOrIdempotentRequestError(y)||y.response?.status===429,onRetry:(y,Ve,De)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${y}/3): ${De.method?.toUpperCase()} ${De.url}. Reason: ${Ve.message}`)}}),this.platform=new oe(this.client),this.product=new re(this.client),this.infra=new ie(this.client),this.webhooks=new ae,t){if(t.ticket){let y=t.ticket;this.startSocket=()=>this.initSocket(o,async()=>({ticket:await y()}))}}else{let y={apiKey:e.apiKey,clientCode:e.clientCode?.toUpperCase()||""};this.startSocket=()=>this.initSocket(o,async()=>y,{"x-api-key":y.apiKey,"x-client-code":y.clientCode})}if(c){let y={version:Ee,clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=y}}initSocket(e,t,n){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{auth:o=>{t().then(c=>o({...c,lastSeq:this.lastSeq}),()=>o({lastSeq:this.lastSeq}))},extraHeaders:n}),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.closed||this.startSocket?.(),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.closed||this.startSocket?.(),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.socketPromise&&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,r){try{return(await this.client.request({method:e,url:t,data:n,params:r})).data}catch(o){throw o.response?new h(o.response.data?.message||o.response.data?.error||"Raw Execution Failed",o.response.status,o.response.data?.code):new h(o.message||"Network Error")}}};ze.config();var qe="3.3.1";var Ye="Official TypeScript SDK for the ERIX API by ECODrIx: CRM, Flow automations, one inbox across WhatsApp, Instagram and email, GST invoices and payments. Node and browser (proxy mode).",T=new He;T.name("erix").description(Ye).version(qe);function b(s){let e=s.key||process.env.ECOD_API_KEY,t=s.client||process.env.ECOD_CLIENT_CODE;return e||(console.error(a.red("Error: API Key is missing.")),console.log(a.yellow("Set ECOD_API_KEY environment variable or use --key <key>")),process.exit(1)),new ce({apiKey:e,clientCode:t,baseUrl:s.baseUrl||process.env.ECOD_BASE_URL})}T.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");T.command("whoami").description("Verify current authentication and tenant status").action(async(s,e)=>{let t=e.parent.opts(),n=b(t);console.log(a.cyan("Checking connection to ECODrIx Platform..."));try{let r=await n.request("GET","/api/saas/me/profile");console.log(a.green("\u2714 Authenticated successfully!")),console.log(`${a.bold("User ID:")} ${r.id}`),console.log(`${a.bold("Organisation:")} ${r.organisation?.name||"N/A"}`),t.client&&console.log(`${a.bold("Tenant Code:")} ${a.magenta(t.client)}`)}catch(r){console.error(a.red("\u2716 Authentication failed")),console.error(a.dim(r.message)),process.exit(1)}});var Ge=T.command("whatsapp").description("WhatsApp Business API operations");Ge.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(s,e,t,n)=>{let r=n.parent.parent.opts(),o=b(r);try{let c=JSON.parse(t.vars);console.log(a.cyan(`Sending template '${e}' to ${s}...`));let d=await o.product.erix.chat.messages.sendTemplate({to:s,templateName:e,language:"en_US",variables:c});console.log(a.green("\u2714 Message sent successfully!")),console.log(a.dim(`ID: ${d?.id||"N/A"}`))}catch(c){console.error(a.red("\u2716 Failed to send message")),console.error(a.dim(c.message))}});var _e=T.command("crm").description("CRM and Lead management");_e.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(s,e)=>{let t=e.parent.parent.opts(),n=b(t);try{let r=Number.parseInt(s.limit);console.log(a.cyan(`Fetching last ${r} leads...`));let o={limit:r};s.status&&(o.status=s.status),s.pipeline&&(o.pipelineId=s.pipeline),s.search&&(o.search=s.search);let c=await n.product.erix.leads.list(o),d=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(d.length===0){console.log(a.yellow("No leads found."));return}console.table(d.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(r){console.error(a.red("\u2716 Failed to fetch leads")),console.error(a.dim(r.message))}});_e.command("pipelines").description("List all CRM pipelines").action(async(s,e)=>{let t=e.parent.parent.opts(),n=b(t);try{console.log(a.cyan("Fetching pipelines..."));let r=await n.product.erix.pipelines.list(),o=r.data||r||[];if(o.length===0){console.log(a.yellow("No pipelines found."));return}console.table(o.map(c=>({ID:c.id||c._id,Name:c.name,Default:c.isDefault?"Yes":"No",Stages:c.stages?.length||0})))}catch(r){console.error(a.red("\u2716 Failed to fetch pipelines")),console.error(a.dim(r.message))}});var Qe=T.command("analytics").description("Business Intelligence Analytics");Qe.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(s,e)=>{let t=e.parent.parent.opts(),n=b(t);try{console.log(a.cyan(`Fetching overview metrics for last ${s.range}...`));let r=await n.product.erix.analytics.overview({range:s.range}),o=r.data||r;console.log(`
|
|
3
|
+
${a.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${a.green(o.totalLeads||0)}`),console.log(`Open Value: ${a.yellow(`$${(o.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${a.green(`$${(o.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${a.blue(o.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${a.magenta(`${(o.conversionRate||0).toFixed(2)}%`)}
|
|
4
|
+
`)}catch(r){console.error(a.red("\u2716 Failed to fetch analytics overview")),console.error(a.dim(r.message))}});var Je=T.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(s,e,t,n,r)=>{let o=r.parent.parent.opts(),c=b(o);try{await c.webhooks.constructEvent(s,e,t),console.log(a.green("\u2714 Signature is VALID"))}catch(d){console.error(a.red("\u2716 Error during verification")),console.error(a.dim(d.message))}});T.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(s,e)=>{let t=e.parent.opts(),n=b(t);console.log(a.magenta(a.bold(`
|
|
5
|
+
Welcome to the Erix Interactive Shell`))),console.log(a.dim(`SDK Version: ${qe}`)),console.log(a.dim(`The 'ecod' client is pre-initialized and ready.
|
|
6
|
+
`));let r=je.start({prompt:a.cyan("erix > "),useColors:!0});r.context.ecod=n,r.context.platform=n.platform,r.context.product=n.product,r.context.infra=n.infra,r.on("exit",()=>{console.log(a.yellow(`
|
|
7
|
+
Goodbye!`)),process.exit(0)})});T.command("completion").description("Generate Bash auto-completion script").action(()=>{console.log(`
|
|
8
8
|
# Erix Bash Completion
|
|
9
9
|
_erix_completions() {
|
|
10
10
|
local cur opts
|
|
@@ -34,5 +34,5 @@ _erix_completions() {
|
|
|
34
34
|
esac
|
|
35
35
|
}
|
|
36
36
|
complete -F _erix_completions erix
|
|
37
|
-
`.trim()),console.error(
|
|
38
|
-
# To enable, run: eval "$(erix completion)"`)),console.error(
|
|
37
|
+
`.trim()),console.error(a.yellow(`
|
|
38
|
+
# To enable, run: eval "$(erix completion)"`)),console.error(a.dim("# Or add it to your ~/.bashrc: erix completion >> ~/.bashrc"))});T.parse();
|
package/dist/ts/cjs/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var rt=Object.create;var B=Object.defineProperty,st=Object.defineProperties,it=Object.getOwnPropertyDescriptor,ot=Object.getOwnPropertyDescriptors,at=Object.getOwnPropertyNames,Ge=Object.getOwnPropertySymbols,ct=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable;var lt=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var ve=(n,e,t)=>e in n?B(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,g=(n,e)=>{for(var t in e||(e={}))Qe.call(e,t)&&ve(n,t,e[t]);if(Ge)for(var t of Ge(e))pt.call(e,t)&&ve(n,t,e[t]);return n},R=(n,e)=>st(n,ot(e));var ut=(n,e)=>{for(var t in e)B(n,t,{get:e[t],enumerable:!0})},Ye=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of at(e))!Qe.call(n,s)&&s!==t&&B(n,s,{get:()=>e[s],enumerable:!(r=it(e,s))||r.enumerable});return n};var L=(n,e,t)=>(t=n!=null?rt(ct(n)):{},Ye(e||!n||!n.__esModule?B(t,"default",{value:n,enumerable:!0}):t,n)),gt=n=>Ye(B({},"__esModule",{value:!0}),n);var i=(n,e,t)=>ve(n,typeof e!="symbol"?e+"":e,t);var Ce=function(n,e){this[0]=n,this[1]=e},Je=(n,e,t)=>{var r=(u,l,f,d)=>{try{var b=t[u](l),k=(l=b.value)instanceof Ce,P=b.done;Promise.resolve(k?l[0]:l).then(y=>k?r(u==="return"?u:"next",l[1]?{done:y.done,value:y.value}:y,f,d):f({value:y,done:P})).catch(y=>r("throw",y,f,d))}catch(y){d(y)}},s=(u,l,f,d)=>p[u]=b=>(l=new Promise((k,P,y)=>(y=()=>r(u,b,k,P),a?a.then(y):y())),d=()=>a===f&&(a=0),a=f=l.then(d,d),l),a,p={};return t=t.apply(n,e),p[lt("asyncIterator")]=()=>p,s("next"),s("throw"),s("return"),p};var xt={};ut(xt,{APIError:()=>m,APIResource:()=>o,AiAgent:()=>$,AuthenticationError:()=>T,ConnectInfra:()=>W,ECODrIx:()=>A,ECODrIxAPI:()=>A,ERROR_RETRY_CONFIG:()=>Ve,EcodrixError:()=>G,EmailConnect:()=>V,ErixChat:()=>_,ErixProduct:()=>U,HTTP_STATUS_ERROR_MAP:()=>mt,InfraDomain:()=>D,KNOWLEDGE_FILE_TYPES:()=>et,Knowledge:()=>E,LEAD_STATUS_VALUES:()=>Ee,Onboarding:()=>I,PermissionError:()=>v,Persona:()=>S,PlatformDomain:()=>M,PlatformTenants:()=>j,PlatformUsers:()=>H,ProductDomain:()=>O,RateLimitError:()=>x,StorageInfra:()=>K,WebhookSignatureError:()=>w,Webhooks:()=>F,WhatsAppConnect:()=>N,default:()=>bt,getErrorDetails:()=>ht,getRetryConfig:()=>Tt,handleAPIError:()=>yt,isAPIError:()=>ft,toAPIError:()=>q});module.exports=gt(xt);var nt=L(require("axios"),1),Ue=L(require("axios-retry"),1);var Ie="https://api.ecodrix.com";function Xe(n="v1",e=Ie){return`${e.replace(/\/+$/,"")}/${n}/api`}var G=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends G{constructor(t,r,s){super(t);i(this,"status");i(this,"code");i(this,"issues");i(this,"field");this.name="APIError",this.status=r,this.code=s}},T=class extends m{constructor(e="Invalid API Key or Client Code",t="AUTH_FAILED",r=401){super(e,r,t),this.name="AuthenticationError"}},v=class extends T{constructor(e="You don't have permission to do this.",t="FORBIDDEN"){super(e,t,403),this.name="PermissionError"}},x=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};function q(n){var a;if(!(n!=null&&n.response))return new m((n==null?void 0:n.message)||"Network Error");let{status:e,data:t}=n.response,r=(t==null?void 0:t.message)||(t==null?void 0:t.error)||"API Request Failed",s=(a=t==null?void 0:t.code)!=null?a:typeof(t==null?void 0:t.error)=="string"&&/^[A-Z][A-Z0-9_]*$/.test(t.error)?t.error:void 0;switch(e){case 401:return new T(r,s);case 403:return new v(r,s);case 429:return new x(r);default:{let p=new m(r,e,s);return Array.isArray(t==null?void 0:t.issues)&&(p.issues=t.issues),typeof(t==null?void 0:t.field)=="string"&&(p.field=t.field),p}}}var o=class{constructor(e){i(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=g({},e);return e.idempotencyKey&&(t.headers=R(g({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){throw q(e)}};var Se=class extends o{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}`)}},Q=class extends o{constructor(t){super(t);i(this,"notes");this.notes=new Se(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:g({},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 Y=class extends o{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 J=class extends o{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 X=class extends o{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 Ee=["open","won","lost","archived"],Z=class extends o{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:Ee.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:[...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)),u=await Promise.allSettled(p);for(let l of u)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=g({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return Je(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let s=yield new Ce(this.list(R(g({},e),{page:t}))),a=Array.isArray(s.data)?s.data:s||[];if(a.length===0){r=!1;break}for(let p of a)yield p;s.pagination&&t<s.pagination.pages||!s.pagination&&a.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 export(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/export`)}async erase(e){return this.post(`/product/erix/crm/leads/${encodeURIComponent(e)}/erase`,{confirm:"ERASE"})}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 ee=class extends o{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var te=class extends o{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var s,a;let t=await this.retrieve(e),r=Array.isArray((s=t.data)==null?void 0:s.stages)?t.data.stages:[];return{name:`Pipeline: ${((a=t.data)==null?void 0:a.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`,{name: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 ne=class extends o{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 re=class extends o{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 C=class extends o{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,d,b;let r=(d=(f=t.fileName)!=null?f:e.name)!=null?d:"file",s=e.type||"application/octet-stream",a=await this.post("/infra/storage/files/upload-url",{folder:(b=t.folder)!=null?b:"inbox",filename:r,contentType:s}),{uploadUrl:p,key:u}=a.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:u,sizeBytes:e.size}),{key:u,mimeType:s,fileName:r}}};var se=class extends o{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 ie=class extends o{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 oe=class extends o{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)}async paymentLink(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payment-link`,{})}async recordPayment(e,t){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payments`,t)}async sendWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-whatsapp`,{})}async sendEmail(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-email`,{})}};var ae=class extends o{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 ce=class extends o{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 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 pe=class extends o{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 configureWebchat(e){return this.configure("webchat",{method:"domain",config:e})}async webchatSettings(){return this.get("/infra/connect/connections/webchat/settings")}async removeWebchatDomain(e){return this.deleteRequest(`/infra/connect/connections/webchat/domains/${encodeURIComponent(e)}`)}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 le=class extends o{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 ue=class extends o{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 ge=class extends o{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 de=class extends o{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 a,p;let t=await this.retrieve(e),r=Array.isArray((a=t.data)==null?void 0:a.components)?t.data.components:[],s=[];for(let u of r)if(u.text){let l=u.text.match(/{{(\d+)}}/g);if(l)for(let f of l){let d=f.replace(/{{|}}/g,"");s.push({key:`var_${d}`,label:`${u.type} Var {{${d}}}`,type:"string",required:!0,group:u.type,description:`Variable placeholder in template ${u.type}`})}}return{name:`Template variables: ${((p=t.data)==null?void 0:p.name)||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};var Ze=L(require("axios"),1);var me=class extends o{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:a}=r.data;await Ze.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:a,sizeBytes:p})}};var ye=class extends o{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},fe=class extends o{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 he=class extends o{async system(){return(await this.get("/health")).data}};var Te=class extends o{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 I=class extends o{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var S=class extends o{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 $e=class extends o{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"}},be=class{constructor(e){i(this,"copilot");this.copilot=new $e(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"],E=class extends o{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",g({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",g({kind:"url"},e))}async addWebsite(e){return this.post("/platform/knowledge/sources",{type:"website",url:e.url})}async addFile(e,t={}){var s,a;let r=await new C(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(a=(s=t.title)!=null?s:r.fileName)!=null?a:"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",g({query:e},t?{limit:t}:{}))}};var $=class extends o{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async outcomes(e={}){return this.get("/product/erix/ai/outcomes",{params:e})}async reviews(e){return this.get(`/product/erix/ai/reviews${e?`?status=${e}`:""}`)}async review(e,t,r){return this.post(`/product/erix/ai/reviews/${encodeURIComponent(e)}`,g({verdict:t},r?{note:r}:{}))}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,r){return this.post(`/product/flow/runs/${encodeURIComponent(e)}/approve`,g({decision:t},r&&{nodeId:r}))}};var xe=class extends o{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 Oe=class extends o{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},De=class extends o{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)}},Me=class extends o{async listPublic(){return this.get("/platform/billing/plans/public")}},Fe=class extends o{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)}},Be=class extends o{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")}},Le=class extends o{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)}},we=class{constructor(e){i(this,"entitlements");i(this,"subscriptions");i(this,"plans");i(this,"checkout");i(this,"user");i(this,"credits");this.entitlements=new Oe(e),this.subscriptions=new De(e),this.plans=new Me(e),this.checkout=new Fe(e),this.user=new Be(e),this.credits=new Le(e)}};var ke=class extends o{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 Re=class extends o{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",{})}},Ae=class extends o{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}`)}},Pe=class extends o{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var _=class{constructor(e){i(this,"messages");i(this,"conversations");this.messages=new C(e),this.conversations=new re(e)}},U=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 Z(e),this.pipelines=new te(e),this.activities=new Q(e),this.analytics=new Y(e),this.scoring=new ne(e),this.payments=new ee(e),this.chat=new _(e),this.events=new ie(e),this.invoices=new oe(e),this.checkout=new se(e),this.projects=new ce(e),this.niche=new ae(e),this.documents=new J(e),this.invoiceExport=new X(e),this.ai=new $(e)}},O=class{constructor(e){i(this,"erix");this.erix=new U(e)}},V=class{constructor(e){i(this,"config");i(this,"templates");this.config=new ge(e),this.templates=new le(e)}},N=class{constructor(e){i(this,"templates");this.templates=new de(e)}},W=class{constructor(e){i(this,"email");i(this,"whatsapp");i(this,"meet");i(this,"connections");this.email=new V(e),this.whatsapp=new N(e),this.meet=new ue(e),this.connections=new pe(e)}},K=class{constructor(e){i(this,"files");i(this,"folders");i(this,"media");this.files=new fe(e),this.folders=new ye(e),this.media=new me(e)}},D=class{constructor(e){i(this,"connect");i(this,"storage");this.connect=new W(e),this.storage=new K(e)}},j=class{constructor(e){i(this,"onboarding");i(this,"persona");this.onboarding=new I(e),this.persona=new S(e)}},H=class{constructor(e){i(this,"me");i(this,"members");i(this,"sessions");i(this,"notifications");this.me=new Re(e),this.members=new Ae(e),this.sessions=new Pe(e),this.notifications=new Te(e)}},M=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 xe(e),this.users=new H(e),this.tenants=new j(e),this.billing=new we(e),this.support=new ke(e),this.ai=new be(e),this.knowledge=new E(e),this.health=new he(e)}};var w=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},F=class{async constructEvent(e,t,r){if(!t)throw new w("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"),u=a.createHmac("sha256",r).update(e).digest("hex");if(!a.timingSafeEqual(Buffer.from(u),Buffer.from(s)))throw new w("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(a){throw a instanceof w?a:new w(`Webhook payload parsing failed: ${a.message}`)}}};var qe=typeof process!="undefined"&&"3.2.0"||"3.1.1";var tt,_e=(tt=Ue.default.default)!=null?tt:Ue.default,A=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"startSocket",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 d,b,k,P,y,Ne,We,Ke;let t=e.proxy;if(!e.apiKey&&!t)throw new T("API Key is required");this.clientCode=(d=e.clientCode)==null?void 0:d.toUpperCase(),this.apiVersion=(b=e.version)!=null?b:"v1";let r=(k=e.baseUrl)!=null?k:Ie,s=Xe(this.apiVersion,(P=t==null?void 0:t.url)!=null?P:r),a=e.socketUrl||r,p=typeof window!="undefined"&&typeof window.document!="undefined",u=p?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",l=p?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",f=R(g({},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:qe,runtime:u,os:l})});if(this.client=nt.default.create({baseURL:s,headers:f,timeout:(We=e.timeout)!=null?We:3e4}),_e(this.client,{retries:3,retryDelay:_e.exponentialDelay,retryCondition:h=>{var z;return _e.isNetworkOrIdempotentRequestError(h)||((z=h.response)==null?void 0:z.status)===429},onRetry:(h,z,je)=>{var He,ze;typeof process!="undefined"&&((He=process.env)==null?void 0:He.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(ze=je.method)==null?void 0:ze.toUpperCase()} ${je.url}. Reason: ${z.message}`)}}),this.platform=new M(this.client),this.product=new O(this.client),this.infra=new D(this.client),this.webhooks=new F,t){if(t.ticket){let h=t.ticket;this.startSocket=()=>this.initSocket(a,async()=>({ticket:await h()}))}}else{let h={apiKey:e.apiKey,clientCode:((Ke=e.clientCode)==null?void 0:Ke.toUpperCase())||""};this.startSocket=()=>this.initSocket(a,async()=>h,{"x-api-key":h.apiKey,"x-client-code":h.clientCode})}if(p){let h={version:qe,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:s})=>{this.socket=s(e,{auth:a=>{t().then(p=>a(R(g({},p),{lastSeq:this.lastSeq})),()=>a({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:a,args:p}of this.socketQueue)a==="joinRoom"?this.socket.emit("join-room",p[0]):a==="leaveRoom"?this.socket.emit("leave-room",p[0]):a==="on"?this.socket.on(p[0],p[1]):a==="off"?this.socket.off(p[0],p[1]):a==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){var t;this.closed||(t=this.startSocket)==null||t.call(this),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){var r;return this.closed||(r=this.startSocket)==null||r.call(this),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.socketPromise&&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 a,p,u;try{return(await this.client.request({method:e,url:t,data:r,params:s})).data}catch(l){throw l.response?new m(((a=l.response.data)==null?void 0:a.message)||((p=l.response.data)==null?void 0:p.error)||"Raw Execution Failed",l.response.status,(u=l.response.data)==null?void 0:u.code):new m(l.message||"Network Error")}}};var mt={401:T,403:v,429:x};function yt(n){throw q(n)}function ft(n,e){return n instanceof e}function ht(n){return n instanceof T?{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 m?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var Ve={[T.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"},[m.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Tt(n){let e=n.constructor.name;return Ve[e]||Ve[m.name]}var bt=A;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,PermissionError,Persona,PlatformDomain,PlatformTenants,PlatformUsers,ProductDomain,RateLimitError,StorageInfra,WebhookSignatureError,Webhooks,WhatsAppConnect,getErrorDetails,getRetryConfig,handleAPIError,isAPIError,toAPIError});
|
|
1
|
+
"use strict";var pt=Object.create;var N=Object.defineProperty,lt=Object.defineProperties,gt=Object.getOwnPropertyDescriptor,dt=Object.getOwnPropertyDescriptors,mt=Object.getOwnPropertyNames,X=Object.getOwnPropertySymbols,yt=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var ft=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var Oe=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,g=(n,e)=>{for(var t in e||(e={}))Ee.call(e,t)&&Oe(n,t,e[t]);if(X)for(var t of X(e))nt.call(e,t)&&Oe(n,t,e[t]);return n},A=(n,e)=>lt(n,dt(e));var S=(n,e)=>{var t={};for(var r in n)Ee.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&X)for(var r of X(n))e.indexOf(r)<0&&nt.call(n,r)&&(t[r]=n[r]);return t};var ht=(n,e)=>{for(var t in e)N(n,t,{get:e[t],enumerable:!0})},rt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mt(e))!Ee.call(n,s)&&s!==t&&N(n,s,{get:()=>e[s],enumerable:!(r=gt(e,s))||r.enumerable});return n};var V=(n,e,t)=>(t=n!=null?pt(yt(n)):{},rt(e||!n||!n.__esModule?N(t,"default",{value:n,enumerable:!0}):t,n)),bt=n=>rt(N({},"__esModule",{value:!0}),n);var i=(n,e,t)=>Oe(n,typeof e!="symbol"?e+"":e,t);var De=function(n,e){this[0]=n,this[1]=e},st=(n,e,t)=>{var r=(l,p,h,d)=>{try{var k=t[l](p),P=(p=k.value)instanceof De,I=k.done;Promise.resolve(P?p[0]:p).then(y=>P?r(l==="return"?l:"next",p[1]?{done:y.done,value:y.value}:y,h,d):h({value:y,done:I})).catch(y=>r("throw",y,h,d))}catch(y){d(y)}},s=(l,p,h,d)=>u[l]=k=>(p=new Promise((P,I,y)=>(y=()=>r(l,k,P,I),a?a.then(y):y())),d=()=>a===h&&(a=0),a=h=p.then(d,d),p),a,u={};return t=t.apply(n,e),u[ft("asyncIterator")]=()=>u,s("next"),s("throw"),s("return"),u};var At={};ht(At,{APIError:()=>m,APIResource:()=>o,AiAgent:()=>L,AuthenticationError:()=>x,ConnectInfra:()=>H,ECODrIx:()=>v,ECODrIxAPI:()=>v,ERROR_RETRY_CONFIG:()=>Qe,EcodrixError:()=>Z,EmailConnect:()=>j,ErixChat:()=>W,ErixProduct:()=>K,HTTP_STATUS_ERROR_MAP:()=>xt,InfraDomain:()=>B,KNOWLEDGE_FILE_TYPES:()=>at,Knowledge:()=>M,LEAD_STATUS_VALUES:()=>Fe,Onboarding:()=>E,PermissionError:()=>$,Persona:()=>D,PlatformDomain:()=>U,PlatformTenants:()=>Q,PlatformUsers:()=>Y,ProductDomain:()=>F,RateLimitError:()=>C,StorageInfra:()=>G,WebhookSignatureError:()=>R,Webhooks:()=>q,WhatsAppConnect:()=>z,default:()=>Pt,getErrorDetails:()=>Ct,getRetryConfig:()=>Rt,handleAPIError:()=>kt,isAPIError:()=>wt,toAPIError:()=>_});module.exports=bt(At);var ut=V(require("axios"),1),Ge=V(require("axios-retry"),1);var Me="https://api.ecodrix.com";function it(n="v1",e=Me){return`${e.replace(/\/+$/,"")}/${n}/api`}var Z=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},m=class extends Z{constructor(t,r,s){super(t);i(this,"status");i(this,"code");i(this,"issues");i(this,"field");this.name="APIError",this.status=r,this.code=s}},x=class extends m{constructor(e="Invalid API Key or Client Code",t="AUTH_FAILED",r=401){super(e,r,t),this.name="AuthenticationError"}},$=class extends x{constructor(e="You don't have permission to do this.",t="FORBIDDEN"){super(e,t,403),this.name="PermissionError"}},C=class extends m{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};function _(n){var a;if(!(n!=null&&n.response))return new m((n==null?void 0:n.message)||"Network Error");let{status:e,data:t}=n.response,r=(t==null?void 0:t.message)||(t==null?void 0:t.error)||"API Request Failed",s=(a=t==null?void 0:t.code)!=null?a:typeof(t==null?void 0:t.error)=="string"&&/^[A-Z][A-Z0-9_]*$/.test(t.error)?t.error:void 0;switch(e){case 401:return new x(r,s);case 403:return new $(r,s);case 429:return new C(r);default:{let u=new m(r,e,s);return Array.isArray(t==null?void 0:t.issues)&&(u.issues=t.issues),typeof(t==null?void 0:t.field)=="string"&&(u.field=t.field),u}}}var o=class{constructor(e){i(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=g({},e);return e.idempotencyKey&&(t.headers=A(g({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){throw _(e)}};var Le=class extends o{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}`)}},ee=class extends o{constructor(t){super(t);i(this,"notes");this.notes=new Le(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:g({},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 te=class extends o{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 ne=class extends o{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 re=class extends o{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 Fe=["open","won","lost","archived"],se=class extends o{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:Fe.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:[...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 u=e.slice(s,s+t).map(p=>this.create(p)),l=await Promise.allSettled(u);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=g({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/product/erix/crm/leads",{params:t})}listAutoPaging(e){return st(this,null,function*(){let t=(e==null?void 0:e.page)||1,r=!0;for(;r;){let s=yield new De(this.list(A(g({},e),{page:t}))),a=Array.isArray(s.data)?s.data:s||[];if(a.length===0){r=!1;break}for(let u of a)yield u;s.pagination&&t<s.pagination.pages||!s.pagination&&a.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 export(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/export`)}async erase(e){return this.post(`/product/erix/crm/leads/${encodeURIComponent(e)}/erase`,{confirm:"ERASE"})}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})}async duplicates(e){return this.get(`/product/erix/crm/leads/${encodeURIComponent(e)}/duplicates`)}};var ie=class extends o{async capture(e){return this.post("/product/erix/crm/payments/capture",e)}};var oe=class extends o{async list(){return this.get("/product/erix/crm/pipelines")}async getStageManifest(e){var s,a;let t=await this.retrieve(e),r=Array.isArray((s=t.data)==null?void 0:s.stages)?t.data.stages:[];return{name:`Pipeline: ${((a=t.data)==null?void 0:a.name)||e}`,fields:r.map(u=>({key:u._id,label:u.name,type:"string",required:!0,options:[{label:u.name,value:u._id}],group:"Stages",uiHints:{color:u.color||"#cbd5e1",probability:u.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`,{name: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 ae=class extends o{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 ce=class extends o{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 O=class extends o{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,k;let r=(d=(h=t.fileName)!=null?h:e.name)!=null?d:"file",s=e.type||"application/octet-stream",a=await this.post("/infra/storage/files/upload-url",{folder:(k=t.folder)!=null?k:"inbox",filename:r,contentType:s}),{uploadUrl:u,key:l}=a.data,p=await fetch(u,{method:"PUT",headers:{"Content-Type":s},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:s,fileName:r}}};var f="/product/erix/commerce/checkout",w="/product/erix/public/checkout",b=encodeURIComponent,Be=class extends o{async getProduct(e,t){return this.get(`${w}/products/${b(t)}`,{params:{c:e}})}async viewSession(e,t){return this.get(`${w}/sessions/view`,{params:{c:e,t}})}async updateItems(e){let s=e,{sessionId:t}=s,r=S(s,["sessionId"]);return this.post(`${w}/sessions/${b(t)}/items`,r)}async startSession(e){return this.post(`${w}/sessions`,e)}async applyCoupon(e){let s=e,{sessionId:t}=s,r=S(s,["sessionId"]);return this.post(`${w}/sessions/${b(t)}/coupon`,r)}async verify(e){let s=e,{sessionId:t}=s,r=S(s,["sessionId"]);return this.post(`${w}/sessions/${b(t)}/verify`,r)}async placeOrder(e){let s=e,{sessionId:t}=s,r=S(s,["sessionId"]);return this.post(`${w}/sessions/${b(t)}/order`,r)}async verifyRazorpay(e){let a=e,{sessionId:t,orderId:r}=a,s=S(a,["sessionId","orderId"]);return this.post(`${w}/sessions/${b(t)}/order/${b(r)}/razorpay`,s)}async orderStatus(e,t){return this.get(`${w}/orders/status`,{params:{c:e,t}})}async confirmCod(e,t){return this.post(`${w}/cod/confirm`,{clientCode:e,token:t})}},Ue=class extends o{async create(e){return this.post(`${f}/sessions`,e)}},ue=class extends o{constructor(t){super(t);i(this,"buyer");i(this,"sessions");this.buyer=new Be(t),this.sessions=new Ue(t)}async listProducts(){return this.get(`${f}/products`)}async createProduct(t){return this.post(`${f}/products`,t)}async updateProduct(t,r){return this.patch(`${f}/products/${b(t)}`,r)}async deleteProduct(t){return this.deleteRequest(`${f}/products/${b(t)}`)}async listCoupons(){return this.get(`${f}/coupons`)}async createCoupon(t){return this.post(`${f}/coupons`,t)}async updateCoupon(t,r){return this.patch(`${f}/coupons/${b(t)}`,r)}async deleteCoupon(t){return this.deleteRequest(`${f}/coupons/${b(t)}`)}async listOrders(t){return this.get(`${f}/orders`,{params:t})}async getOrder(t){return this.get(`${f}/orders/${b(t)}`)}async updateOrderStatus(t,r){return this.patch(`${f}/orders/${b(t)}/status`,r)}async getSettings(){return this.get(`${f}/settings`)}async updateSettings(t){return this.put(`${f}/settings`,t)}async createProductLink(t){return this.post(`${f}/links`,t)}};var pe=class extends o{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 le=class extends o{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)}async paymentLink(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payment-link`,{})}async recordPayment(e,t){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/payments`,t)}async sendWhatsApp(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-whatsapp`,{})}async sendEmail(e){return this.post(`/product/erix/commerce/invoices/${encodeURIComponent(e)}/send-email`,{})}};var ge=class extends o{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 de=class extends o{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 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 me=class extends o{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 configureWebchat(e){return this.configure("webchat",{method:"domain",config:e})}async webchatSettings(){return this.get("/infra/connect/connections/webchat/settings")}async removeWebchatDomain(e){return this.deleteRequest(`/infra/connect/connections/webchat/domains/${encodeURIComponent(e)}`)}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 ye=class extends o{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 fe=class extends o{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 he=class extends o{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 be=class extends o{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 a,u;let t=await this.retrieve(e),r=Array.isArray((a=t.data)==null?void 0:a.components)?t.data.components:[],s=[];for(let l of r)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let h of p){let d=h.replace(/{{|}}/g,"");s.push({key:`var_${d}`,label:`${l.type} Var {{${d}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((u=t.data)==null?void 0:u.name)||e}`,fields:s,uiHints:{icon:"Variables",primaryColor:"#059669"}}}};var ot=V(require("axios"),1);var Te=class extends o{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:a}=r.data;await ot.default.put(s,e,{headers:{"Content-Type":t.contentType}});let u=e.size||e.byteLength||0;return this.post("/infra/storage/files/confirm-upload",{key:a,sizeBytes:u})}};var xe=class extends o{async create(e){return this.post("/infra/storage/files/folders",{name:e})}},ke=class extends o{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 we=class extends o{async system(){return(await this.get("/health")).data}};var Ce=class extends o{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 E=class extends o{async global(e){return this.post("/platform/tenants/onboarding/global",e)}async complete(e){return this.post("/platform/tenants/onboarding/complete",e)}};var D=class extends o{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 qe=class extends o{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"}},Re=class{constructor(e){i(this,"copilot");this.copilot=new qe(e)}};var at=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain","text/markdown","text/csv","text/html","image/png","image/jpeg","image/webp"],M=class extends o{async list(){return this.get("/platform/knowledge/sources")}async addText(e){return this.post("/platform/knowledge/sources",g({kind:"text"},e))}async addUrl(e){return this.post("/platform/knowledge/sources",g({kind:"url"},e))}async addWebsite(e){return this.post("/platform/knowledge/sources",{type:"website",url:e.url})}async addFile(e,t={}){var s,a;let r=await new O(this.client).upload(e,{folder:"knowledge"});return this.post("/platform/knowledge/sources",{kind:"file",key:r.key,mimeType:r.mimeType,title:(a=(s=t.title)!=null?s:r.fileName)!=null?a:"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",g({query:e},t?{limit:t}:{}))}};var L=class extends o{async settings(){return this.get("/product/erix/ai/settings")}async updateSettings(e){return this.patch("/product/erix/ai/settings",e)}async outcomes(e={}){return this.get("/product/erix/ai/outcomes",{params:e})}async reviews(e){return this.get(`/product/erix/ai/reviews${e?`?status=${e}`:""}`)}async review(e,t,r){return this.post(`/product/erix/ai/reviews/${encodeURIComponent(e)}`,g({verdict:t},r?{note:r}:{}))}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,r){return this.post(`/product/flow/runs/${encodeURIComponent(e)}/approve`,g({decision:t},r&&{nodeId:r}))}};var Pe=class extends o{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 Ne=class extends o{async get(){return super.get("/platform/billing/entitlements/entitlements")}async usage(){return super.get("/platform/billing/entitlements/usage")}},Ve=class extends o{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)}},_e=class extends o{async listPublic(){return this.get("/platform/billing/plans/public")}},We=class extends o{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)}},Ke=class extends o{async transactions(){return this.get("/platform/billing/user/transactions")}async transactionInvoice(e){return this.get(`/platform/billing/user/transactions/${encodeURIComponent(e)}/invoice`)}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")}},je=class extends o{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 Ne(e),this.subscriptions=new Ve(e),this.plans=new _e(e),this.checkout=new We(e),this.user=new Ke(e),this.credits=new je(e)}};var ve=class extends o{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 Ie=class extends o{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",{})}},Se=class extends o{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}`)}},$e=class extends o{async list(){return this.get("/platform/auth/sessions")}async revoke(e){return this.deleteRequest(`/platform/auth/sessions/${e}`)}};var W=class{constructor(e){i(this,"messages");i(this,"conversations");this.messages=new O(e),this.conversations=new ce(e)}},K=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 se(e),this.pipelines=new oe(e),this.activities=new ee(e),this.analytics=new te(e),this.scoring=new ae(e),this.payments=new ie(e),this.chat=new W(e),this.events=new pe(e),this.invoices=new le(e),this.checkout=new ue(e),this.projects=new de(e),this.niche=new ge(e),this.documents=new ne(e),this.invoiceExport=new re(e),this.ai=new L(e)}},F=class{constructor(e){i(this,"erix");this.erix=new K(e)}},j=class{constructor(e){i(this,"config");i(this,"templates");this.config=new he(e),this.templates=new ye(e)}},z=class{constructor(e){i(this,"templates");this.templates=new be(e)}},H=class{constructor(e){i(this,"email");i(this,"whatsapp");i(this,"meet");i(this,"connections");this.email=new j(e),this.whatsapp=new z(e),this.meet=new fe(e),this.connections=new me(e)}},G=class{constructor(e){i(this,"files");i(this,"folders");i(this,"media");this.files=new ke(e),this.folders=new xe(e),this.media=new Te(e)}},B=class{constructor(e){i(this,"connect");i(this,"storage");this.connect=new H(e),this.storage=new G(e)}},Q=class{constructor(e){i(this,"onboarding");i(this,"persona");this.onboarding=new E(e),this.persona=new D(e)}},Y=class{constructor(e){i(this,"me");i(this,"members");i(this,"sessions");i(this,"notifications");this.me=new Ie(e),this.members=new Se(e),this.sessions=new $e(e),this.notifications=new Ce(e)}},U=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 Pe(e),this.users=new Y(e),this.tenants=new Q(e),this.billing=new Ae(e),this.support=new ve(e),this.ai=new Re(e),this.knowledge=new M(e),this.health=new we(e)}};var R=class extends m{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},q=class{async constructEvent(e,t,r){if(!t)throw new R("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"),l=a.createHmac("sha256",r).update(e).digest("hex");if(!a.timingSafeEqual(Buffer.from(l),Buffer.from(s)))throw new R("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(a){throw a instanceof R?a:new R(`Webhook payload parsing failed: ${a.message}`)}}};var ze=typeof process!="undefined"&&"3.3.1"||"3.1.1";var ct,He=(ct=Ge.default.default)!=null?ct:Ge.default,v=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"startSocket",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 d,k,P,I,y,Ye,Je,Xe;let t=e.proxy;if(!e.apiKey&&!t)throw new x("API Key is required");this.clientCode=(d=e.clientCode)==null?void 0:d.toUpperCase(),this.apiVersion=(k=e.version)!=null?k:"v1";let r=(P=e.baseUrl)!=null?P:Me,s=it(this.apiVersion,(I=t==null?void 0:t.url)!=null?I:r),a=e.socketUrl||r,u=typeof window!="undefined"&&typeof window.document!="undefined",l=u?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",p=u?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",h=A(g({},t?{}:{"x-api-key":e.apiKey,"x-client-code":((Ye=e.clientCode)==null?void 0:Ye.toUpperCase())||""}),{"Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:ze,runtime:l,os:p})});if(this.client=ut.default.create({baseURL:s,headers:h,timeout:(Je=e.timeout)!=null?Je:3e4}),He(this.client,{retries:3,retryDelay:He.exponentialDelay,retryCondition:T=>{var J;return He.isNetworkOrIdempotentRequestError(T)||((J=T.response)==null?void 0:J.status)===429},onRetry:(T,J,Ze)=>{var et,tt;typeof process!="undefined"&&((et=process.env)==null?void 0:et.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(tt=Ze.method)==null?void 0:tt.toUpperCase()} ${Ze.url}. Reason: ${J.message}`)}}),this.platform=new U(this.client),this.product=new F(this.client),this.infra=new B(this.client),this.webhooks=new q,t){if(t.ticket){let T=t.ticket;this.startSocket=()=>this.initSocket(a,async()=>({ticket:await T()}))}}else{let T={apiKey:e.apiKey,clientCode:((Xe=e.clientCode)==null?void 0:Xe.toUpperCase())||""};this.startSocket=()=>this.initSocket(a,async()=>T,{"x-api-key":T.apiKey,"x-client-code":T.clientCode})}if(u){let T={version:ze,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:a=>{t().then(u=>a(A(g({},u),{lastSeq:this.lastSeq})),()=>a({lastSeq:this.lastSeq}))},extraHeaders:r}),this.setupSocket();for(let{type:a,args:u}of this.socketQueue)a==="joinRoom"?this.socket.emit("join-room",u[0]):a==="leaveRoom"?this.socket.emit("leave-room",u[0]):a==="on"?this.socket.on(u[0],u[1]):a==="off"?this.socket.off(u[0],u[1]):a==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){var t;this.closed||(t=this.startSocket)==null||t.call(this),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){var r;return this.closed||(r=this.startSocket)==null||r.call(this),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.socketPromise&&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 a,u,l;try{return(await this.client.request({method:e,url:t,data:r,params:s})).data}catch(p){throw p.response?new m(((a=p.response.data)==null?void 0:a.message)||((u=p.response.data)==null?void 0:u.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new m(p.message||"Network Error")}}};var xt={401:x,403:$,429:C};function kt(n){throw _(n)}function wt(n,e){return n instanceof e}function Ct(n){return n instanceof x?{message:n.message,status:n.status,code:n.code,type:"AuthenticationError"}:n instanceof C?{message:n.message,status:n.status,code:n.code,type:"RateLimitError"}:n instanceof m?{message:n.message,status:n.status,code:n.code,type:"APIError"}:{message:n.message||"Unknown error",type:"UnknownError"}}var Qe={[x.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[C.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[m.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Rt(n){let e=n.constructor.name;return Qe[e]||Qe[m.name]}var Pt=v;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,PermissionError,Persona,PlatformDomain,PlatformTenants,PlatformUsers,ProductDomain,RateLimitError,StorageInfra,WebhookSignatureError,Webhooks,WhatsAppConnect,getErrorDetails,getRetryConfig,handleAPIError,isAPIError,toAPIError});
|