@ecodrix/erix-api 1.3.9 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/ts/cjs/index.cjs +1 -1
- package/dist/ts/esm/index.d.ts +45 -8
- package/dist/ts/esm/index.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import he from"repl";import{Command as Te}from"commander";import fe from"dotenv";import o from"picocolors";import de from"axios";import ce from"axios-retry";var z=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends z{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){this.client=e}client;async post(e,t,a){try{let s=this.buildConfig(a);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let s=this.buildConfig(a);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,a){try{let s=this.buildConfig(a);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){if(e.response){let t=e.response.status,a=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new y(a);case 403:throw new y(a);case 429:throw new f(a);default:throw new u(a,t,s)}}throw new u(e.message||"Network Error")}};var b=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var v=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var P=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var X=class extends r{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},x=class extends r{notes;constructor(e){super(e),this.notes=new X(e)}async timeline(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/api/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/api/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/api/crm/leads/${e}/calls`,t)}};var w=class extends r{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var C=class extends r{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var $=class extends r{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var R=class extends r{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{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:[...a,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let s=0;s<e.length;s+=t){let c=e.slice(s,s+t).map(g=>this.create(g)),m=await Promise.allSettled(c);for(let g of m)if(g.status==="fulfilled")a.push(g.value);else throw g.reason}return a}async import(e){return this.post("/api/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("/api/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,a=!0;for(;a;){let s=await this.list({...e,page:t}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){a=!1;break}for(let c of i)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&i.length>0?t++:a=!1}}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var k=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var A=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:a.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("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var I=class extends r{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var S=class extends r{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var E=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new R(e),this.pipelines=new A(e),this.activities=new x(e),this.analytics=new w(e),this.automations=new $(e),this.sequences=new S(e),this.scoring=new I(e),this.payments=new k(e),this.automationDashboard=new C(e)}};var D=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var L=class extends r{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var q=class extends r{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var O=class extends r{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var Z=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},ee=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},te=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},M=class extends r{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new Z(e),this.campaigns=new ee(e),this.whatsapp=new te(e)}};import ue from"axios";var N=class extends r{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:i}=a.data;await ue.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:c})}};var U=class extends r{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var _=class extends r{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var F=class extends r{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var se=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getSecrets(e){return this.get(`/api/clients/${e}/secrets`)}async updateSecrets(e,t){return this.post(`/api/clients/${e}/secrets`,t)}async replaceSecrets(e,t){return this.put(`/api/clients/${e}/secrets`,t)}async patchSecrets(e,t){return this.patch(`/api/clients/${e}/secrets`,t)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},ae=class extends r{async list(){return this.get("/api/services/blogs")}},ne=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},B=class extends r{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new se(e),this.blogs=new ae(e),this.globalLeads=new ne(e)}};var re=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},K=class extends r{email;constructor(e){super(e),this.email=new re(e)}};var ie=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},oe=class extends r{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},V=class extends r{folders;files;constructor(e){super(e),this.folders=new ie(e),this.files=new oe(e)}async usage(){return this.get("/api/saas/storage/usage")}};var T=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},H=class{async constructEvent(e,t,a){if(!t)throw new T("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"),m=i.createHmac("sha256",a).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(m),Buffer.from(s)))throw new T("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof T?i:new T(`Webhook payload parsing failed: ${i.message}`)}}};var W=class extends r{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var j=class extends r{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var Q=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",{...e,templateLanguage:e.language||e.templateLanguage||"en_US"})}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var J=class extends r{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let i of a)if(i.text){let c=i.text.match(/{{(\d+)}}/g);if(c)for(let m of c){let g=m.replace(/{{|}}/g,"");s.push({key:`var_${g}`,label:`${i.type} Var {{${g}}}`,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"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var Y=class extends r{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new Q(e),this.conversations=new j(e),this.broadcasts=new W(e),this.templates=new J(e)}async upload(e,t){let a=new FormData;return a.append("file",e,t),this.post("/api/saas/chat/upload",a,{headers:typeof a.getHeaders=="function"?a.getHeaders():void 0})}async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}};var ye="https://api.ecodrix.com",G=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;agency;services;settings;cors;checkout;constructor(e){if(!e.apiKey)throw new y("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??ye,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",c=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",m={"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:i,os:c})};if(e.coreApiKey&&(m["x-core-api-key"]=e.coreApiKey),this.client=de.create({baseURL:t,headers:m}),ce(this.client,{retries:3,retryDelay:ce.exponentialDelay,retryCondition:g=>ce.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,me,pe)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${pe.method?.toUpperCase()} ${pe.url}. Reason: ${me.message}`)}}),this.whatsapp=new Y(this.client),this.crm=new E(this.client),this.media=new N(this.client),this.meet=new U(this.client),this.notifications=new _(this.client),this.email=new D(this.client),this.logs=new O(this.client),this.events=new L(this.client),this.webhooks=new H,this.storage=new V(this.client),this.marketing=new M(this.client),this.health=new q(this.client),this.queue=new F(this.client),this.agency=new b(this.client),this.services=new B(this.client),this.settings=new K(this.client),this.cors=new P(this.client),this.checkout=new v(this.client),this.initSocket(a,e.apiKey,e.clientCode),s){let g={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=g,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{extraHeaders:{"x-api-key":t,"x-client-code":a?.toUpperCase()||""}}),this.setupSocket(a);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.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(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,s){try{return(await this.client.request({method:e,url:t,data:a,params:s})).data}catch(i){throw i.response?new u(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new u(i.message||"Network Error")}}};fe.config();var le="1.3.9";var be="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new Te;d.name("erix").description(be).version(le);function h(n){let e=n.key||process.env.ECOD_API_KEY,t=n.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 G({apiKey:e,clientCode:t,baseUrl:n.baseUrl||process.env.ECOD_BASE_URL})}d.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");d.command("whoami").description("Verify current authentication and tenant status").action(async(n,e)=>{let t=e.parent.opts(),a=h(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await a.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 ve=d.command("whatsapp").description("WhatsApp Business API operations");ve.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(n,e,t,a)=>{let s=a.parent.parent.opts(),i=h(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let m=await i.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${m?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var ge=d.command("crm").description("CRM and Lead management");ge.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(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};n.status&&(i.status=n.status),n.pipeline&&(i.pipelineId=n.pipeline),n.search&&(i.search=n.search);let c=await a.crm.leads.list(i),m=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(m.length===0){console.log(o.yellow("No leads found."));return}console.table(m.map(g=>({ID:g.id||g._id,Name:`${g.firstName} ${g.lastName||""}`.trim(),Phone:g.phone,Status:g.status,Score:g.score||0,Created:new Date(g.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});ge.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.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 Pe=d.command("analytics").description("Business Intelligence Analytics");Pe.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),i=s.data||s;console.log(`
|
|
2
|
+
import he from"repl";import{Command as Te}from"commander";import fe from"dotenv";import o from"picocolors";import de from"axios";import ce from"axios-retry";var z=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends z{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){this.client=e}client;async post(e,t,a){try{let s=this.buildConfig(a);return(await this.client.post(e,t,s)).data}catch(s){this.handleError(s)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let s=this.buildConfig(a);return(await this.client.patch(e,t,s)).data}catch(s){this.handleError(s)}}async put(e,t,a){try{let s=this.buildConfig(a);return(await this.client.put(e,t,s)).data}catch(s){this.handleError(s)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t={...e};return e.idempotencyKey&&(t.headers={...t.headers,"Idempotency-Key":e.idempotencyKey}),t}handleError(e){if(e.response){let t=e.response.status,a=e.response.data?.message||e.response.data?.error||"API Request Failed",s=e.response.data?.code;switch(t){case 401:throw new y(a);case 403:throw new y(a);case 429:throw new f(a);default:throw new u(a,t,s)}}throw new u(e.message||"Network Error")}};var b=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var v=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var P=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var X=class extends r{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},x=class extends r{notes;constructor(e){super(e),this.notes=new X(e)}async timeline(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async list(e,t){return this.get(`/api/crm/leads/${e}/activities`,{params:{...t}})}async log(e){return this.post(`/api/crm/leads/${e.leadId}/activities`,e)}async logCall(e,t){return this.post(`/api/crm/leads/${e}/calls`,t)}};var w=class extends r{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var C=class extends r{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var $=class extends r{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var R=class extends r{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{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:[...a,...s],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let s=0;s<e.length;s+=t){let c=e.slice(s,s+t).map(g=>this.create(g)),m=await Promise.allSettled(c);for(let g of m)if(g.status==="fulfilled")a.push(g.value);else throw g.reason}return a}async import(e){return this.post("/api/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("/api/crm/leads",{params:t})}async*listAutoPaging(e){let t=e?.page||1,a=!0;for(;a;){let s=await this.list({...e,page:t}),i=Array.isArray(s.data)?s.data:s||[];if(i.length===0){a=!1;break}for(let c of i)yield c;s.pagination&&t<s.pagination.pages||!s.pagination&&i.length>0?t++:a=!1}}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var k=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var A=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.stages)?t.data.stages:[];return{name:`Pipeline: ${t.data?.name||e}`,fields:a.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("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var I=class extends r{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var S=class extends r{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var E=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new R(e),this.pipelines=new A(e),this.activities=new x(e),this.analytics=new w(e),this.automations=new $(e),this.sequences=new S(e),this.scoring=new I(e),this.payments=new k(e),this.automationDashboard=new C(e)}};var D=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var L=class extends r{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var q=class extends r{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var O=class extends r{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var Z=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},ee=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},te=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},M=class extends r{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new Z(e),this.campaigns=new ee(e),this.whatsapp=new te(e)}};import ue from"axios";var N=class extends r{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:s,key:i}=a.data;await ue.put(s,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:i,sizeBytes:c})}};var U=class extends r{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var _=class extends r{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var F=class extends r{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var se=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},ae=class extends r{async list(){return this.get("/api/services/blogs")}},ne=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},B=class extends r{clients;blogs;globalLeads;constructor(e){super(e),this.clients=new se(e),this.blogs=new ae(e),this.globalLeads=new ne(e)}};var re=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},K=class extends r{email;constructor(e){super(e),this.email=new re(e)}};var ie=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},oe=class extends r{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},V=class extends r{folders;files;constructor(e){super(e),this.folders=new ie(e),this.files=new oe(e)}async usage(){return this.get("/api/saas/storage/usage")}};var T=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},H=class{async constructEvent(e,t,a){if(!t)throw new T("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"),m=i.createHmac("sha256",a).update(e).digest("hex");if(!i.timingSafeEqual(Buffer.from(m),Buffer.from(s)))throw new T("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(i){throw i instanceof T?i:new T(`Webhook payload parsing failed: ${i.message}`)}}};var W=class extends r{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var j=class extends r{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var Q=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",{...e,templateLanguage:e.language||e.templateLanguage||"en_US"})}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var J=class extends r{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){let t=await this.retrieve(e),a=Array.isArray(t.data?.components)?t.data.components:[],s=[];for(let i of a)if(i.text){let c=i.text.match(/{{(\d+)}}/g);if(c)for(let m of c){let g=m.replace(/{{|}}/g,"");s.push({key:`var_${g}`,label:`${i.type} Var {{${g}}}`,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"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var Y=class extends r{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new Q(e),this.conversations=new j(e),this.broadcasts=new W(e),this.templates=new J(e)}async upload(e,t){let a=new FormData;return a.append("file",e,t),this.post("/api/saas/chat/upload",a,{headers:typeof a.getHeaders=="function"?a.getHeaders():void 0})}async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}};var ye="https://api.ecodrix.com",G=class{client;socket=null;socketPromise=null;socketQueue=[];clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;agency;services;settings;cors;checkout;constructor(e){if(!e.apiKey)throw new y("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??ye,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",i=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",c=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown",m={"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:i,os:c})};if(e.coreApiKey&&(m["x-core-api-key"]=e.coreApiKey),this.client=de.create({baseURL:t,headers:m}),ce(this.client,{retries:3,retryDelay:ce.exponentialDelay,retryCondition:g=>ce.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,me,pe)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${pe.method?.toUpperCase()} ${pe.url}. Reason: ${me.message}`)}}),this.whatsapp=new Y(this.client),this.crm=new E(this.client),this.media=new N(this.client),this.meet=new U(this.client),this.notifications=new _(this.client),this.email=new D(this.client),this.logs=new O(this.client),this.events=new L(this.client),this.webhooks=new H,this.storage=new V(this.client),this.marketing=new M(this.client),this.health=new q(this.client),this.queue=new F(this.client),this.agency=new b(this.client),this.services=new B(this.client),this.settings=new K(this.client),this.cors=new P(this.client),this.checkout=new v(this.client),this.initSocket(a,e.apiKey,e.clientCode),s){let g={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=g,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:s})=>{this.socket=s(e,{extraHeaders:{"x-api-key":t,"x-client-code":a?.toUpperCase()||""}}),this.setupSocket(a);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.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(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,s){try{return(await this.client.request({method:e,url:t,data:a,params:s})).data}catch(i){throw i.response?new u(i.response.data?.message||i.response.data?.error||"Raw Execution Failed",i.response.status,i.response.data?.code):new u(i.message||"Network Error")}}};fe.config();var le="1.4.0";var be="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new Te;d.name("erix").description(be).version(le);function h(n){let e=n.key||process.env.ECOD_API_KEY,t=n.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 G({apiKey:e,clientCode:t,baseUrl:n.baseUrl||process.env.ECOD_BASE_URL})}d.option("-k, --key <key>","ECODrIx API Key").option("-c, --client <code...","Tenant Client Code").option("--base-url <url>","API Base URL override");d.command("whoami").description("Verify current authentication and tenant status").action(async(n,e)=>{let t=e.parent.opts(),a=h(t);console.log(o.cyan("Checking connection to ECODrIx Platform..."));try{let s=await a.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 ve=d.command("whatsapp").description("WhatsApp Business API operations");ve.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(n,e,t,a)=>{let s=a.parent.parent.opts(),i=h(s);try{let c=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let m=await i.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:c});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${m?.id||"N/A"}`))}catch(c){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(c.message))}});var ge=d.command("crm").description("CRM and Lead management");ge.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(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let i={limit:s};n.status&&(i.status=n.status),n.pipeline&&(i.pipelineId=n.pipeline),n.search&&(i.search=n.search);let c=await a.crm.leads.list(i),m=Array.isArray(c.data)?c.data:Array.isArray(c)?c:[];if(m.length===0){console.log(o.yellow("No leads found."));return}console.table(m.map(g=>({ID:g.id||g._id,Name:`${g.firstName} ${g.lastName||""}`.trim(),Phone:g.phone,Status:g.status,Score:g.score||0,Created:new Date(g.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});ge.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.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 Pe=d.command("analytics").description("Business Intelligence Analytics");Pe.command("overview").description("Get high-level CRM KPIs").option("-r, --range <range>","Date range (e.g., 24h, 7d, 30d, 365d)","30d").action(async(n,e)=>{let t=e.parent.parent.opts(),a=h(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),i=s.data||s;console.log(`
|
|
3
3
|
${o.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${o.green(i.totalLeads||0)}`),console.log(`Open Value: ${o.yellow(`$${(i.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${o.green(`$${(i.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${o.blue(i.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${o.magenta(`${(i.conversionRate||0).toFixed(2)}%`)}
|
|
4
4
|
`)}catch(s){console.error(o.red("\u2716 Failed to fetch analytics overview")),console.error(o.dim(s.message))}});var xe=d.command("webhooks").description("Webhook utility tools");xe.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(n,e,t,a,s)=>{let i=s.parent.parent.opts(),c=h(i);try{await c.webhooks.constructEvent(n,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(m){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(m.message))}});d.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(n,e)=>{let t=e.parent.opts(),a=h(t);console.log(o.magenta(o.bold(`
|
|
5
5
|
Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${le}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
|
package/dist/ts/cjs/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ie=Object.create;var k=Object.defineProperty,$e=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertyNames,Pe=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var Me=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var ie=(s,e,t)=>e in s?k(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,b=(s,e)=>{for(var t in e||(e={}))ve.call(e,t)&&ie(s,t,e[t]);if(Pe)for(var t of Pe(e))De.call(e,t)&&ie(s,t,e[t]);return s},w=(s,e)=>$e(s,Ee(e));var Ue=(s,e)=>{for(var t in e)k(s,t,{get:e[t],enumerable:!0})},we=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qe(e))!ve.call(s,n)&&n!==t&&k(s,n,{get:()=>e[n],enumerable:!(a=Se(e,n))||a.enumerable});return s};var C=(s,e,t)=>(t=s!=null?Ie(Le(s)):{},we(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s)),Oe=s=>we(k({},"__esModule",{value:!0}),s);var i=(s,e,t)=>ie(s,typeof e!="symbol"?e+"":e,t);var oe=function(s,e){this[0]=s,this[1]=e},Re=(s,e,t)=>{var a=(g,l,h,d)=>{try{var P=t[g](l),T=(l=P.value)instanceof oe,x=P.done;Promise.resolve(T?l[0]:l).then(m=>T?a(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:x})).catch(m=>a("throw",m,h,d))}catch(m){d(m)}},n=(g,l,h,d)=>c[g]=P=>(l=new Promise((T,x,m)=>(m=()=>a(g,P,T,x),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,c={};return t=t.apply(s,e),c[Me("asyncIterator")]=()=>c,n("next"),n("throw"),n("return"),c};var Ke={};Ue(Ke,{APIError:()=>u,AuthenticationError:()=>y,ECODrIx:()=>v,ECODrIxAPI:()=>v,ERROR_RETRY_CONFIG:()=>fe,EcodrixError:()=>A,HTTP_STATUS_ERROR_MAP:()=>Ae,RateLimitError:()=>f,default:()=>je,getErrorDetails:()=>Be,getRetryConfig:()=>He,handleAPIError:()=>_e,isAPIError:()=>Fe});module.exports=Oe(Ke);var Ce=C(require("axios"),1),re=C(require("axios-retry"),1);var A=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends A{constructor(t,a,n){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=n}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let n=this.buildConfig(a);return(await this.client.post(e,t,n)).data}catch(n){this.handleError(n)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let n=this.buildConfig(a);return(await this.client.patch(e,t,n)).data}catch(n){this.handleError(n)}}async put(e,t,a){try{let n=this.buildConfig(a);return(await this.client.put(e,t,n)).data}catch(n){this.handleError(n)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t=b({},e);return e.idempotencyKey&&(t.headers=w(b({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,n;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",g=(n=e.response.data)==null?void 0:n.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new f(c);default:throw new u(c,o,g)}}throw new u(e.message||"Network Error")}};var I=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var $=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var S=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ce=class extends r{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},E=class extends r{constructor(t){super(t);i(this,"notes");this.notes=new ce(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:b({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var q=class extends r{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var L=class extends r{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var D=class extends r{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var M=class extends r{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],n=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:[...a,...n],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let n=0;n<e.length;n+=t){let c=e.slice(n,n+t).map(l=>this.create(l)),g=await Promise.allSettled(c);for(let l of g)if(l.status==="fulfilled")a.push(l.value);else throw l.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=b({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return Re(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let n=yield new oe(this.list(w(b({},e),{page:t}))),o=Array.isArray(n.data)?n.data:n||[];if(o.length===0){a=!1;break}for(let c of o)yield c;n.pagination&&t<n.pagination.pages||!n.pagination&&o.length>0?t++:a=!1}})}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var U=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var O=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var n,o;let t=await this.retrieve(e),a=Array.isArray((n=t.data)==null?void 0:n.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var N=class extends r{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var _=class extends r{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var F=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new M(e),this.pipelines=new O(e),this.activities=new E(e),this.analytics=new q(e),this.automations=new D(e),this.sequences=new _(e),this.scoring=new N(e),this.payments=new U(e),this.automationDashboard=new L(e)}};var B=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var H=class extends r{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var j=class extends r{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var K=class extends r{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var pe=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},le=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},ge=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},V=class extends r{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new pe(t),this.campaigns=new le(t),this.whatsapp=new ge(t)}};var ke=C(require("axios"),1);var Q=class extends r{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:n,key:o}=a.data;await ke.default.put(n,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var J=class extends r{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var W=class extends r{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var z=class extends r{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var ue=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getSecrets(e){return this.get(`/api/clients/${e}/secrets`)}async updateSecrets(e,t){return this.post(`/api/clients/${e}/secrets`,t)}async replaceSecrets(e,t){return this.put(`/api/clients/${e}/secrets`,t)}async patchSecrets(e,t){return this.patch(`/api/clients/${e}/secrets`,t)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},me=class extends r{async list(){return this.get("/api/services/blogs")}},ye=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},G=class extends r{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ue(t),this.blogs=new me(t),this.globalLeads=new ye(t)}};var de=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},X=class extends r{constructor(t){super(t);i(this,"email");this.email=new de(t)}};var he=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Te=class extends r{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},Y=class extends r{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new he(t),this.files=new Te(t)}async usage(){return this.get("/api/saas/storage/usage")}};var R=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},Z=class{async constructEvent(e,t,a){if(!t)throw new R("No webhook signature provided");let n=Array.isArray(t)?t[0]:t;n.startsWith("sha256=")&&(n=n.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(n)))throw new R("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof R?o:new R(`Webhook payload parsing failed: ${o.message}`)}}};var ee=class extends r{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var te=class extends r{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var se=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",w(b({},e),{templateLanguage:e.language||e.templateLanguage||"en_US"}))}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var ae=class extends r{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],n=[];for(let g of a)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");n.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:n,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ne=class extends r{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new se(t),this.conversations=new te(t),this.broadcasts=new ee(t),this.templates=new ae(t)}async upload(t,a){let n=new FormData;return n.append("file",t,a),this.post("/api/saas/chat/upload",n,{headers:typeof n.getHeaders=="function"?n.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var Ne="https://api.ecodrix.com",v=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var l,h,d,P;if(!e.apiKey)throw new y("API Key is required");this.clientCode=(l=e.clientCode)==null?void 0:l.toUpperCase();let t=(h=e.baseUrl)!=null?h:Ne,a=e.socketUrl||t,n=typeof window!="undefined"&&typeof window.document!="undefined",o=n?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=n?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",g={"x-api-key":e.apiKey,"x-client-code":((P=e.clientCode)==null?void 0:P.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(g["x-core-api-key"]=e.coreApiKey),this.client=Ce.default.create({baseURL:t,headers:g}),(0,re.default)(this.client,{retries:3,retryDelay:re.default.exponentialDelay,retryCondition:T=>{var x;return re.default.isNetworkOrIdempotentRequestError(T)||((x=T.response)==null?void 0:x.status)===429},onRetry:(T,x,m)=>{var be,xe;typeof process!="undefined"&&((be=process.env)==null?void 0:be.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(xe=m.method)==null?void 0:xe.toUpperCase()} ${m.url}. Reason: ${x.message}`)}}),this.whatsapp=new ne(this.client),this.crm=new F(this.client),this.media=new Q(this.client),this.meet=new J(this.client),this.notifications=new W(this.client),this.email=new B(this.client),this.logs=new K(this.client),this.events=new H(this.client),this.webhooks=new Z,this.storage=new Y(this.client),this.marketing=new V(this.client),this.health=new j(this.client),this.queue=new z(this.client),this.agency=new I(this.client),this.services=new G(this.client),this.settings=new X(this.client),this.cors=new S(this.client),this.checkout=new $(this.client),this.initSocket(a,e.apiKey,e.clientCode),n){let T={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:n})=>{this.socket=n(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,n){var o,c,g;try{return(await this.client.request({method:e,url:t,data:a,params:n})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((c=l.response.data)==null?void 0:c.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var Ae={401:y,403:y,429:f};function _e(s){var e,t,a;if(s.response){let n=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,g=Ae[n]||u;throw g===y?new y(o):g===f?new f(o):new u(o,n,c)}throw new u(s.message||"Network Error")}function Fe(s,e){return s instanceof e}function Be(s){return s instanceof y?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof u?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var fe={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function He(s){let e=s.constructor.name;return fe[e]||fe[u.name]}var je=v;0&&(module.exports={APIError,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,HTTP_STATUS_ERROR_MAP,RateLimitError,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
|
|
1
|
+
"use strict";var $e=Object.create;var k=Object.defineProperty,Ie=Object.defineProperties,Ee=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertyNames,Pe=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var Me=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var ie=(s,e,t)=>e in s?k(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,b=(s,e)=>{for(var t in e||(e={}))ve.call(e,t)&&ie(s,t,e[t]);if(Pe)for(var t of Pe(e))De.call(e,t)&&ie(s,t,e[t]);return s},w=(s,e)=>Ie(s,Se(e));var Ue=(s,e)=>{for(var t in e)k(s,t,{get:e[t],enumerable:!0})},we=(s,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qe(e))!ve.call(s,n)&&n!==t&&k(s,n,{get:()=>e[n],enumerable:!(a=Ee(e,n))||a.enumerable});return s};var C=(s,e,t)=>(t=s!=null?$e(Le(s)):{},we(e||!s||!s.__esModule?k(t,"default",{value:s,enumerable:!0}):t,s)),Oe=s=>we(k({},"__esModule",{value:!0}),s);var i=(s,e,t)=>ie(s,typeof e!="symbol"?e+"":e,t);var oe=function(s,e){this[0]=s,this[1]=e},Re=(s,e,t)=>{var a=(g,l,h,d)=>{try{var P=t[g](l),T=(l=P.value)instanceof oe,x=P.done;Promise.resolve(T?l[0]:l).then(m=>T?a(g==="return"?g:"next",l[1]?{done:m.done,value:m.value}:m,h,d):h({value:m,done:x})).catch(m=>a("throw",m,h,d))}catch(m){d(m)}},n=(g,l,h,d)=>c[g]=P=>(l=new Promise((T,x,m)=>(m=()=>a(g,P,T,x),o?o.then(m):m())),d=()=>o===h&&(o=0),o=h=l.then(d,d),l),o,c={};return t=t.apply(s,e),c[Me("asyncIterator")]=()=>c,n("next"),n("throw"),n("return"),c};var Ke={};Ue(Ke,{APIError:()=>u,AuthenticationError:()=>y,ECODrIx:()=>v,ECODrIxAPI:()=>v,ERROR_RETRY_CONFIG:()=>fe,EcodrixError:()=>A,HTTP_STATUS_ERROR_MAP:()=>Ae,RateLimitError:()=>f,default:()=>je,getErrorDetails:()=>Be,getRetryConfig:()=>He,handleAPIError:()=>_e,isAPIError:()=>Fe});module.exports=Oe(Ke);var Ce=C(require("axios"),1),re=C(require("axios-retry"),1);var A=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends A{constructor(t,a,n){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=n}},y=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends u{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var r=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let n=this.buildConfig(a);return(await this.client.post(e,t,n)).data}catch(n){this.handleError(n)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let n=this.buildConfig(a);return(await this.client.patch(e,t,n)).data}catch(n){this.handleError(n)}}async put(e,t,a){try{let n=this.buildConfig(a);return(await this.client.put(e,t,n)).data}catch(n){this.handleError(n)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t=b({},e);return e.idempotencyKey&&(t.headers=w(b({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,n;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",g=(n=e.response.data)==null?void 0:n.code;switch(o){case 401:throw new y(c);case 403:throw new y(c);case 429:throw new f(c);default:throw new u(c,o,g)}}throw new u(e.message||"Network Error")}};var $=class extends r{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var I=class extends r{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var E=class extends r{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ce=class extends r{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},S=class extends r{constructor(t){super(t);i(this,"notes");this.notes=new ce(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:b({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var q=class extends r{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var L=class extends r{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var D=class extends r{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var M=class extends r{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{key:"value",label:"Lead Value",type:"currency",required:!1},{key:"source",label:"Source",type:"string",required:!1}],n=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:[...a,...n],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let n=0;n<e.length;n+=t){let c=e.slice(n,n+t).map(l=>this.create(l)),g=await Promise.allSettled(c);for(let l of g)if(l.status==="fulfilled")a.push(l.value);else throw l.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=b({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return Re(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let n=yield new oe(this.list(w(b({},e),{page:t}))),o=Array.isArray(n.data)?n.data:n||[];if(o.length===0){a=!1;break}for(let c of o)yield c;n.pagination&&t<n.pagination.pages||!n.pagination&&o.length>0?t++:a=!1}})}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var U=class extends r{async capture(e){return this.post("/api/crm/payments/capture",e)}};var O=class extends r{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var n,o;let t=await this.retrieve(e),a=Array.isArray((n=t.data)==null?void 0:n.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var N=class extends r{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var _=class extends r{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var F=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new M(e),this.pipelines=new O(e),this.activities=new S(e),this.analytics=new q(e),this.automations=new D(e),this.sequences=new _(e),this.scoring=new N(e),this.payments=new U(e),this.automationDashboard=new L(e)}};var B=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var H=class extends r{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var j=class extends r{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var K=class extends r{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var pe=class extends r{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},le=class extends r{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},ge=class extends r{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},V=class extends r{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new pe(t),this.campaigns=new le(t),this.whatsapp=new ge(t)}};var ke=C(require("axios"),1);var Q=class extends r{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:n,key:o}=a.data;await ke.default.put(n,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var J=class extends r{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var W=class extends r{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var z=class extends r{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var ue=class extends r{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},me=class extends r{async list(){return this.get("/api/services/blogs")}},ye=class extends r{async add(e){return this.post("/api/services/add-lead",e)}},G=class extends r{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ue(t),this.blogs=new me(t),this.globalLeads=new ye(t)}};var de=class extends r{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},X=class extends r{constructor(t){super(t);i(this,"email");this.email=new de(t)}};var he=class extends r{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Te=class extends r{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},Y=class extends r{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new he(t),this.files=new Te(t)}async usage(){return this.get("/api/saas/storage/usage")}};var R=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},Z=class{async constructEvent(e,t,a){if(!t)throw new R("No webhook signature provided");let n=Array.isArray(t)?t[0]:t;n.startsWith("sha256=")&&(n=n.slice(7));try{let o=await import("crypto"),g=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(g),Buffer.from(n)))throw new R("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof R?o:new R(`Webhook payload parsing failed: ${o.message}`)}}};var ee=class extends r{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var te=class extends r{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var se=class extends r{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",w(b({},e),{templateLanguage:e.language||e.templateLanguage||"en_US"}))}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var ae=class extends r{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],n=[];for(let g of a)if(g.text){let l=g.text.match(/{{(\d+)}}/g);if(l)for(let h of l){let d=h.replace(/{{|}}/g,"");n.push({key:`var_${d}`,label:`${g.type} Var {{${d}}}`,type:"string",required:!0,group:g.type,description:`Variable placeholder in template ${g.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:n,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ne=class extends r{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new se(t),this.conversations=new te(t),this.broadcasts=new ee(t),this.templates=new ae(t)}async upload(t,a){let n=new FormData;return n.append("file",t,a),this.post("/api/saas/chat/upload",n,{headers:typeof n.getHeaders=="function"?n.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var Ne="https://api.ecodrix.com",v=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var l,h,d,P;if(!e.apiKey)throw new y("API Key is required");this.clientCode=(l=e.clientCode)==null?void 0:l.toUpperCase();let t=(h=e.baseUrl)!=null?h:Ne,a=e.socketUrl||t,n=typeof window!="undefined"&&typeof window.document!="undefined",o=n?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=n?((d=globalThis.navigator)==null?void 0:d.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",g={"x-api-key":e.apiKey,"x-client-code":((P=e.clientCode)==null?void 0:P.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(g["x-core-api-key"]=e.coreApiKey),this.client=Ce.default.create({baseURL:t,headers:g}),(0,re.default)(this.client,{retries:3,retryDelay:re.default.exponentialDelay,retryCondition:T=>{var x;return re.default.isNetworkOrIdempotentRequestError(T)||((x=T.response)==null?void 0:x.status)===429},onRetry:(T,x,m)=>{var be,xe;typeof process!="undefined"&&((be=process.env)==null?void 0:be.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${T}/3): ${(xe=m.method)==null?void 0:xe.toUpperCase()} ${m.url}. Reason: ${x.message}`)}}),this.whatsapp=new ne(this.client),this.crm=new F(this.client),this.media=new Q(this.client),this.meet=new J(this.client),this.notifications=new W(this.client),this.email=new B(this.client),this.logs=new K(this.client),this.events=new H(this.client),this.webhooks=new Z,this.storage=new Y(this.client),this.marketing=new V(this.client),this.health=new j(this.client),this.queue=new z(this.client),this.agency=new $(this.client),this.services=new G(this.client),this.settings=new X(this.client),this.cors=new E(this.client),this.checkout=new I(this.client),this.initSocket(a,e.apiKey,e.clientCode),n){let T={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=T,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:n})=>{this.socket=n(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,n){var o,c,g;try{return(await this.client.request({method:e,url:t,data:a,params:n})).data}catch(l){throw l.response?new u(((o=l.response.data)==null?void 0:o.message)||((c=l.response.data)==null?void 0:c.error)||"Raw Execution Failed",l.response.status,(g=l.response.data)==null?void 0:g.code):new u(l.message||"Network Error")}}};var Ae={401:y,403:y,429:f};function _e(s){var e,t,a;if(s.response){let n=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,g=Ae[n]||u;throw g===y?new y(o):g===f?new f(o):new u(o,n,c)}throw new u(s.message||"Network Error")}function Fe(s,e){return s instanceof e}function Be(s){return s instanceof y?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof u?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var fe={[y.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[u.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function He(s){let e=s.constructor.name;return fe[e]||fe[u.name]}var je=v;0&&(module.exports={APIError,AuthenticationError,ECODrIx,ECODrIxAPI,ERROR_RETRY_CONFIG,EcodrixError,HTTP_STATUS_ERROR_MAP,RateLimitError,getErrorDetails,getRetryConfig,handleAPIError,isAPIError});
|
package/dist/ts/esm/index.d.ts
CHANGED
|
@@ -1986,6 +1986,23 @@ declare class Media extends APIResource {
|
|
|
1986
1986
|
* ```
|
|
1987
1987
|
*/
|
|
1988
1988
|
getDownloadUrl(key: string): Promise<unknown>;
|
|
1989
|
+
/**
|
|
1990
|
+
* AI media description (Gemini vision) — generates alt text, SEO title,
|
|
1991
|
+
* description, tags, and dominant colors for an image asset. The ECODrIx
|
|
1992
|
+
* equivalent of ImageKit / Cloudinary auto-tagging.
|
|
1993
|
+
*
|
|
1994
|
+
* Plan-gated behind `cloud_storage.aiTagging`; only works for images.
|
|
1995
|
+
*
|
|
1996
|
+
* @param key - The full storage key of an image file.
|
|
1997
|
+
* @returns `{ altText, title, description, tags[], dominantColors[] }`.
|
|
1998
|
+
*
|
|
1999
|
+
* @example
|
|
2000
|
+
* ```typescript
|
|
2001
|
+
* const { data } = await ecod.media.aiDescribe("website/hero.jpg");
|
|
2002
|
+
* // data.tags → ["office", "team", "modern"]
|
|
2003
|
+
* ```
|
|
2004
|
+
*/
|
|
2005
|
+
aiDescribe<T = any>(key: string): Promise<T>;
|
|
1989
2006
|
/**
|
|
1990
2007
|
* **Elite Upload Helper** — uploads a file to Cloudflare R2 in a single call.
|
|
1991
2008
|
*
|
|
@@ -2433,21 +2450,41 @@ declare class Clients extends APIResource {
|
|
|
2433
2450
|
*/
|
|
2434
2451
|
updateConfig<T = any>(clientCode: string, payload: any): Promise<T>;
|
|
2435
2452
|
/**
|
|
2436
|
-
*
|
|
2453
|
+
* List a client's ERIX-Connect connections (masked status + per-module
|
|
2454
|
+
* grants). Replaces the legacy `getSecrets` — credentials are never returned
|
|
2455
|
+
* in plaintext.
|
|
2437
2456
|
*/
|
|
2438
|
-
|
|
2457
|
+
getConnections<T = any>(clientCode: string): Promise<T>;
|
|
2439
2458
|
/**
|
|
2440
|
-
*
|
|
2459
|
+
* List the ERIX-Connect provider registry (cards + methods + field metadata).
|
|
2441
2460
|
*/
|
|
2442
|
-
|
|
2461
|
+
getConnectProviders<T = any>(clientCode: string): Promise<T>;
|
|
2443
2462
|
/**
|
|
2444
|
-
*
|
|
2463
|
+
* Connect a provider for a client via a chosen method.
|
|
2445
2464
|
*/
|
|
2446
|
-
|
|
2465
|
+
connectProvider<T = any>(clientCode: string, providerId: string, payload: {
|
|
2466
|
+
method: string;
|
|
2467
|
+
config: Record<string, unknown>;
|
|
2468
|
+
}): Promise<T>;
|
|
2469
|
+
/**
|
|
2470
|
+
* Update an already-connected provider's configuration.
|
|
2471
|
+
*/
|
|
2472
|
+
configureProvider<T = any>(clientCode: string, providerId: string, payload: {
|
|
2473
|
+
method: string;
|
|
2474
|
+
config: Record<string, unknown>;
|
|
2475
|
+
}): Promise<T>;
|
|
2447
2476
|
/**
|
|
2448
|
-
*
|
|
2477
|
+
* Disconnect a provider for a client.
|
|
2449
2478
|
*/
|
|
2450
|
-
|
|
2479
|
+
disconnectProvider<T = any>(clientCode: string, providerId: string): Promise<T>;
|
|
2480
|
+
/**
|
|
2481
|
+
* Toggle a per-module access grant (crm | flow | laie) for a client's
|
|
2482
|
+
* connector.
|
|
2483
|
+
*/
|
|
2484
|
+
setConnectionAccess<T = any>(clientCode: string, providerId: string, payload: {
|
|
2485
|
+
module: "crm" | "flow" | "laie";
|
|
2486
|
+
enabled: boolean;
|
|
2487
|
+
}): Promise<T>;
|
|
2451
2488
|
/**
|
|
2452
2489
|
* Retrieve Data Source connection metadata.
|
|
2453
2490
|
*/
|
package/dist/ts/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var xe=Object.defineProperty,Pe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var Te=Object.getOwnPropertySymbols;var we=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var ke=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var te=(s,e,t)=>e in s?xe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,T=(s,e)=>{for(var t in e||(e={}))we.call(e,t)&&te(s,t,e[t]);if(Te)for(var t of Te(e))Re.call(e,t)&&te(s,t,e[t]);return s},P=(s,e)=>Pe(s,ve(e));var i=(s,e,t)=>te(s,typeof e!="symbol"?e+"":e,t);var se=function(s,e){this[0]=s,this[1]=e},fe=(s,e,t)=>{var n=(l,p,d,y)=>{try{var x=t[l](p),h=(p=x.value)instanceof se,b=x.done;Promise.resolve(h?p[0]:p).then(u=>h?n(l==="return"?l:"next",p[1]?{done:u.done,value:u.value}:u,d,y):d({value:u,done:b})).catch(u=>n("throw",u,d,y))}catch(u){y(u)}},r=(l,p,d,y)=>c[l]=x=>(p=new Promise((h,b,u)=>(u=()=>n(l,x,h,b),o?o.then(u):u())),y=()=>o===d&&(o=0),o=d=p.then(y,y),p),o,c={};return t=t.apply(s,e),c[ke("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};import Ae from"axios";import ye from"axios-retry";var ae=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},g=class extends ae{constructor(t,n,r){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=n,this.code=r}},m=class extends g{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends g{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var a=class{constructor(e){i(this,"client",e)}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=T({},e);return e.idempotencyKey&&(t.headers=P(T({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,n,r;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((n=e.response.data)==null?void 0:n.error)||"API Request Failed",l=(r=e.response.data)==null?void 0:r.code;switch(o){case 401:throw new m(c);case 403:throw new m(c);case 429:throw new f(c);default:throw new g(c,o,l)}}throw new g(e.message||"Network Error")}};var R=class extends a{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var k=class extends a{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var C=class extends a{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ne=class extends a{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},A=class extends a{constructor(t){super(t);i(this,"notes");this.notes=new ne(t)}async timeline(t,n){return this.get(`/api/crm/leads/${t}/timeline`,{params:n})}async list(t,n){return this.get(`/api/crm/leads/${t}/activities`,{params:T({},n)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,n){return this.post(`/api/crm/leads/${t}/calls`,n)}};var $=class extends a{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var I=class extends a{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var E=class extends a{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,n){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:n})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var S=class extends a{async create(e){return this.post("/api/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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{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("/api/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(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")n.push(p.value);else throw p.reason}return n}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=T({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return fe(this,null,function*(){let t=(e==null?void 0:e.page)||1,n=!0;for(;n;){let r=yield new se(this.list(P(T({},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(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,n={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:n})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,n){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:n})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,n){return this.patch(`/api/crm/notes/${t}`,n)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var L=class extends a{async capture(e){return this.post("/api/crm/payments/capture",e)}};var q=class extends a{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var r,o;let t=await this.retrieve(e),n=Array.isArray((r=t.data)==null?void 0:r.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:n.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var D=class extends a{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var U=class extends a{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var M=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new S(e),this.pipelines=new q(e),this.activities=new A(e),this.analytics=new $(e),this.automations=new E(e),this.sequences=new U(e),this.scoring=new D(e),this.payments=new L(e),this.automationDashboard=new I(e)}};var O=class extends a{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var N=class extends a{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var _=class extends a{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var B=class extends a{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var re=class extends a{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},ie=class extends a{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},oe=class extends a{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},H=class extends a{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new re(t),this.campaigns=new ie(t),this.whatsapp=new oe(t)}};import Ce from"axios";var F=class extends a{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async upload(e,t){let n=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:r,key:o}=n.data;await Ce.put(r,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var j=class extends a{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var K=class extends a{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var V=class extends a{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var ce=class extends a{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getSecrets(e){return this.get(`/api/clients/${e}/secrets`)}async updateSecrets(e,t){return this.post(`/api/clients/${e}/secrets`,t)}async replaceSecrets(e,t){return this.put(`/api/clients/${e}/secrets`,t)}async patchSecrets(e,t){return this.patch(`/api/clients/${e}/secrets`,t)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},pe=class extends a{async list(){return this.get("/api/services/blogs")}},le=class extends a{async add(e){return this.post("/api/services/add-lead",e)}},Q=class extends a{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ce(t),this.blogs=new pe(t),this.globalLeads=new le(t)}};var ge=class extends a{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},J=class extends a{constructor(t){super(t);i(this,"email");this.email=new ge(t)}};var ue=class extends a{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},me=class extends a{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},W=class extends a{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new ue(t),this.files=new me(t)}async usage(){return this.get("/api/saas/storage/usage")}};var v=class extends g{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},G=class{async constructEvent(e,t,n){if(!t)throw new v("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"),l=o.createHmac("sha256",n).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(r)))throw new v("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof v?o:new v(`Webhook payload parsing failed: ${o.message}`)}}};var z=class extends a{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var X=class extends a{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,n){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:n})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var Y=class extends a{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",P(T({},e),{templateLanguage:e.language||e.templateLanguage||"en_US"}))}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var Z=class extends a{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),n=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],r=[];for(let l of n)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let d of p){let y=d.replace(/{{|}}/g,"");r.push({key:`var_${y}`,label:`${l.type} Var {{${y}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ee=class extends a{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new Y(t),this.conversations=new X(t),this.broadcasts=new z(t),this.templates=new Z(t)}async upload(t,n){let r=new FormData;return r.append("file",t,n),this.post("/api/saas/chat/upload",r,{headers:typeof r.getHeaders=="function"?r.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var $e="https://api.ecodrix.com",w=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var p,d,y,x;if(!e.apiKey)throw new m("API Key is required");this.clientCode=(p=e.clientCode)==null?void 0:p.toUpperCase();let t=(d=e.baseUrl)!=null?d:$e,n=e.socketUrl||t,r=typeof window!="undefined"&&typeof window.document!="undefined",o=r?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=r?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",l={"x-api-key":e.apiKey,"x-client-code":((x=e.clientCode)==null?void 0:x.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(l["x-core-api-key"]=e.coreApiKey),this.client=Ae.create({baseURL:t,headers:l}),ye(this.client,{retries:3,retryDelay:ye.exponentialDelay,retryCondition:h=>{var b;return ye.isNetworkOrIdempotentRequestError(h)||((b=h.response)==null?void 0:b.status)===429},onRetry:(h,b,u)=>{var de,he;typeof process!="undefined"&&((de=process.env)==null?void 0:de.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(he=u.method)==null?void 0:he.toUpperCase()} ${u.url}. Reason: ${b.message}`)}}),this.whatsapp=new ee(this.client),this.crm=new M(this.client),this.media=new F(this.client),this.meet=new j(this.client),this.notifications=new K(this.client),this.email=new O(this.client),this.logs=new B(this.client),this.events=new N(this.client),this.webhooks=new G,this.storage=new W(this.client),this.marketing=new H(this.client),this.health=new _(this.client),this.queue=new V(this.client),this.agency=new R(this.client),this.services=new Q(this.client),this.settings=new J(this.client),this.cors=new C(this.client),this.checkout=new k(this.client),this.initSocket(n,e.apiKey,e.clientCode),r){let h={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,n){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{extraHeaders:{"x-api-key":t,"x-client-code":(n==null?void 0:n.toUpperCase())||""}}),this.setupSocket(n);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,n,r){var o,c,l;try{return(await this.client.request({method:e,url:t,data:n,params:r})).data}catch(p){throw p.response?new g(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new g(p.message||"Network Error")}}};var Ie={401:m,403:m,429:f};function Os(s){var e,t,n;if(s.response){let r=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(n=s.response.data)==null?void 0:n.code,l=Ie[r]||g;throw l===m?new m(o):l===f?new f(o):new g(o,r,c)}throw new g(s.message||"Network Error")}function Ns(s,e){return s instanceof e}function _s(s){return s instanceof m?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof g?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var be={[m.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[g.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Bs(s){let e=s.constructor.name;return be[e]||be[g.name]}var js=w;export{g as APIError,m as AuthenticationError,w as ECODrIx,w as ECODrIxAPI,be as ERROR_RETRY_CONFIG,ae as EcodrixError,Ie as HTTP_STATUS_ERROR_MAP,f as RateLimitError,js as default,_s as getErrorDetails,Bs as getRetryConfig,Os as handleAPIError,Ns as isAPIError};
|
|
1
|
+
var xe=Object.defineProperty,Pe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var Te=Object.getOwnPropertySymbols;var we=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var ke=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var te=(s,e,t)=>e in s?xe(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,T=(s,e)=>{for(var t in e||(e={}))we.call(e,t)&&te(s,t,e[t]);if(Te)for(var t of Te(e))Re.call(e,t)&&te(s,t,e[t]);return s},P=(s,e)=>Pe(s,ve(e));var i=(s,e,t)=>te(s,typeof e!="symbol"?e+"":e,t);var se=function(s,e){this[0]=s,this[1]=e},fe=(s,e,t)=>{var a=(l,p,d,y)=>{try{var x=t[l](p),h=(p=x.value)instanceof se,b=x.done;Promise.resolve(h?p[0]:p).then(u=>h?a(l==="return"?l:"next",p[1]?{done:u.done,value:u.value}:u,d,y):d({value:u,done:b})).catch(u=>a("throw",u,d,y))}catch(u){y(u)}},r=(l,p,d,y)=>c[l]=x=>(p=new Promise((h,b,u)=>(u=()=>a(l,x,h,b),o?o.then(u):u())),y=()=>o===d&&(o=0),o=d=p.then(y,y),p),o,c={};return t=t.apply(s,e),c[ke("asyncIterator")]=()=>c,r("next"),r("throw"),r("return"),c};import Ae from"axios";import ye from"axios-retry";var ae=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},g=class extends ae{constructor(t,a,r){super(t);i(this,"status");i(this,"code");this.name="APIError",this.status=a,this.code=r}},m=class extends g{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}},f=class extends g{constructor(e="Too many requests. Please slow down."){super(e,429,"RATE_LIMIT_EXCEEDED"),this.name="RateLimitError"}};var n=class{constructor(e){i(this,"client",e)}async post(e,t,a){try{let r=this.buildConfig(a);return(await this.client.post(e,t,r)).data}catch(r){this.handleError(r)}}async get(e,t){try{let a=this.buildConfig(t);return(await this.client.get(e,a)).data}catch(a){this.handleError(a)}}async patch(e,t,a){try{let r=this.buildConfig(a);return(await this.client.patch(e,t,r)).data}catch(r){this.handleError(r)}}async put(e,t,a){try{let r=this.buildConfig(a);return(await this.client.put(e,t,r)).data}catch(r){this.handleError(r)}}async deleteRequest(e,t){try{let a=this.buildConfig(t);return(await this.client.delete(e,a)).data}catch(a){this.handleError(a)}}buildConfig(e){if(!e)return;let t=T({},e);return e.idempotencyKey&&(t.headers=P(T({},t.headers),{"Idempotency-Key":e.idempotencyKey})),t}handleError(e){var t,a,r;if(e.response){let o=e.response.status,c=((t=e.response.data)==null?void 0:t.message)||((a=e.response.data)==null?void 0:a.error)||"API Request Failed",l=(r=e.response.data)==null?void 0:r.code;switch(o){case 401:throw new m(c);case 403:throw new m(c);case 429:throw new f(c);default:throw new g(c,o,l)}}throw new g(e.message||"Network Error")}};var R=class extends n{async listBlueprints(){return this.get("/api/agency/blueprints")}async createBlueprint(e){return this.post("/api/agency/blueprints",e)}async deployBlueprint(e){return this.post("/api/agency/blueprints/deploy",e)}async getPortfolioStats(e){return this.get(`/api/agency/portfolio/${e}/stats`)}async getPortfolioHealth(e){return this.get(`/api/agency/portfolio/${e}/health`)}async getUsage(e){return this.get(`/api/agency/usage/${e}`)}async listStaff(e){return this.get(`/api/agency/staff/${e}`)}async createStaff(e){return this.post("/api/agency/staff",e)}};var k=class extends n{async getProduct(e){return this.get(`/api/v1/checkout/products/${e}`)}async createSession(e){return this.post("/api/v1/checkout/session",e)}async applyCoupon(e){return this.post("/api/v1/checkout/coupon",e)}async verify(e){return this.post("/api/v1/checkout/verify",e)}async createOrder(e){return this.post("/api/v1/checkout/order",e)}};var C=class extends n{async list(){return this.get("/api/saas/cors")}async create(e){return this.post("/api/saas/cors",e)}async update(e,t){return this.patch(`/api/saas/cors/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/cors/${e}`)}};var ne=class extends n{async list(e){return this.get(`/api/crm/leads/${e}/notes`)}async create(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async update(e,t){return this.patch(`/api/crm/notes/${e}`,{content:t})}async pin(e,t=!0){return this.patch(`/api/crm/notes/${e}/pin`,{isPinned:t})}async delete(e){return this.deleteRequest(`/api/crm/notes/${e}`)}},A=class extends n{constructor(t){super(t);i(this,"notes");this.notes=new ne(t)}async timeline(t,a){return this.get(`/api/crm/leads/${t}/timeline`,{params:a})}async list(t,a){return this.get(`/api/crm/leads/${t}/activities`,{params:T({},a)})}async log(t){return this.post(`/api/crm/leads/${t.leadId}/activities`,t)}async logCall(t,a){return this.post(`/api/crm/leads/${t}/calls`,a)}};var $=class extends n{async overview(e){return this.get("/api/crm/analytics/overview",{params:e})}async funnel(e){return this.get("/api/crm/analytics/funnel",{params:{pipelineId:e}})}async forecast(e){return this.get("/api/crm/analytics/forecast",{params:{pipelineId:e}})}async sources(e){return this.get("/api/crm/analytics/sources",{params:e})}async team(e){return this.get("/api/crm/analytics/team",{params:e})}async heatmap(e){return this.get("/api/crm/analytics/heatmap",{params:e})}async scores(){return this.get("/api/crm/analytics/scores")}async stageTime(e){return this.get("/api/crm/analytics/stage-time",{params:{pipelineId:e}})}async tiered(e){return this.get("/api/crm/analytics/tiered",{params:e})}async summary(e){return this.get("/api/crm/analytics/summary",{params:e})}async whatsapp(e){return this.get("/api/crm/analytics/whatsapp",{params:e})}};var I=class extends n{async stats(){return this.get("/api/crm/automation/stats")}async logs(e){return this.get("/api/crm/automation/logs",{params:e})}async retryFailedEvent(e){return this.post(`/api/crm/automation/logs/${e}/retry`,{})}};var E=class extends n{async list(){return this.get("/api/crm/automations")}async create(e){return this.post("/api/crm/automations",e)}async update(e,t){return this.patch(`/api/crm/automations/${e}`,t)}async toggle(e){return this.patch(`/api/crm/automations/${e}/toggle`)}async delete(e){return this.deleteRequest(`/api/crm/automations/${e}`)}async bulkDelete(e){return this.post("/api/crm/automations/bulk-delete",{ids:e})}async test(e,t){return this.post(`/api/crm/automations/${e}/test`,{leadId:t})}async getAvailableEvents(){return this.post("/api/crm/automations/events",{})}async enrollments(e,t){return this.get(`/api/crm/automations/${e}/enrollments`,{params:t})}async getEnrollment(e){return this.get(`/api/crm/automations/enrollments/${e}`)}async pauseEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/pause`,{})}async resumeEnrollment(e,t){return this.post(`/api/crm/automations/${e}/enrollments/${t}/resume`,{})}async runs(e){return this.get(`/api/crm/automations/${e}/runs`)}async getRun(e){return this.get(`/api/crm/automations/runs/${e}`)}async resumeRun(e){return this.post(`/api/crm/automations/runs/${e}/resume`,{})}async abortRun(e){return this.post(`/api/crm/automations/runs/${e}/abort`,{})}async webhookEvent(e,t,a){return this.post("/api/crm/automations/webhook-event",{ruleId:e,eventName:t,payload:a})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}};var S=class extends n{async create(e){return this.post("/api/crm/leads",e)}async describe(){let e=await this.fields(),t=Array.isArray(e.data)?e.data:[],a=[{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:[{label:"New",value:"new"},{label:"Contacted",value:"contacted"},{label:"Qualified",value:"qualified"},{label:"Won",value:"won"},{label:"Lost",value:"lost"}]},{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:[...a,...r],uiHints:{icon:"User",primaryColor:"#3b82f6",defaultSort:{field:"createdAt",direction:"desc"},summaryFields:["firstName","lastName","phone","status"]}}}async upsert(e){return this.post("/api/crm/leads/upsert",e)}async createMany(e,t=50){let a=[];for(let r=0;r<e.length;r+=t){let c=e.slice(r,r+t).map(p=>this.create(p)),l=await Promise.allSettled(c);for(let p of l)if(p.status==="fulfilled")a.push(p.value);else throw p.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads:e})}async bulkUpsert(e){return this.import(e)}async list(e){let t=T({},e);return Array.isArray(t.tags)&&(t.tags=t.tags.join(",")),this.get("/api/crm/leads",{params:t})}listAutoPaging(e){return fe(this,null,function*(){let t=(e==null?void 0:e.page)||1,a=!0;for(;a;){let r=yield new se(this.list(P(T({},e),{page:t}))),o=Array.isArray(r.data)?r.data:r||[];if(o.length===0){a=!1;break}for(let c of o)yield c;r.pagination&&t<r.pagination.pages||!r.pagination&&o.length>0?t++:a=!1}})}async retrieve(e){return this.get(`/api/crm/leads/${e}`)}async retrieveByPhone(e){return this.get(`/api/crm/leads/phone/${encodeURIComponent(e)}`)}async byStage(e,t,a={}){return this.get(`/api/crm/pipelines/${e}/stages/${t}/leads`,{params:a})}async retrieveByRef(e,t){return this.get(`/api/crm/leads/ref/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async update(e,t){return this.patch(`/api/crm/leads/${e}`,t)}async move(e,t){return this.patch(`/api/crm/leads/${e}/move`,{stageId:t})}async convert(e,t,a){return this.post(`/api/crm/leads/${e}/convert`,{outcome:t,reason:a})}async tags(e,t){return this.patch(`/api/crm/leads/${e}/tags`,t)}async recalculateScore(e){return this.post(`/api/crm/leads/${e}/score`,{})}async updateMetadata(e,t){return this.patch(`/api/crm/leads/${e}/metadata`,t)}async fields(){return this.get("/api/crm/leads/fields")}async notes(e){return this.get(`/api/crm/leads/${e}/notes`)}async activities(e,t){return this.get(`/api/crm/leads/${e}/timeline`,{params:t})}async createNote(e,t){return this.post(`/api/crm/leads/${e}/notes`,t)}async updateNote(e,t,a){return this.patch(`/api/crm/notes/${t}`,a)}async deleteNote(e,t){return this.deleteRequest(`/api/crm/notes/${t}`)}async delete(e){return this.deleteRequest(`/api/crm/leads/${e}`)}async bulkArchive(e){return this.patch("/api/crm/leads/bulk-archive",{ids:e})}async bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}async archive(e){return this.patch(`/api/crm/leads/${e}/archive`,{})}};var L=class extends n{async capture(e){return this.post("/api/crm/payments/capture",e)}};var q=class extends n{async list(){return this.get("/api/crm/pipelines")}async getStageManifest(e){var r,o;let t=await this.retrieve(e),a=Array.isArray((r=t.data)==null?void 0:r.stages)?t.data.stages:[];return{name:`Pipeline: ${((o=t.data)==null?void 0:o.name)||e}`,fields:a.map(c=>({key:c._id,label:c.name,type:"string",required:!0,options:[{label:c.name,value:c._id}],group:"Stages",uiHints:{color:c.color||"#cbd5e1",probability:c.probability}})),uiHints:{icon:"Columns",primaryColor:"#6366f1"}}}async create(e){return this.post("/api/crm/pipelines",e)}async retrieve(e){return this.get(`/api/crm/pipelines/${e}`)}async update(e,t){return this.patch(`/api/crm/pipelines/${e}`,t)}async setDefault(e){return this.patch(`/api/crm/pipelines/${e}/default`,{})}async duplicate(e,t){return this.post(`/api/crm/pipelines/${e}/duplicate`,{newName:t})}async archive(e){return this.patch(`/api/crm/pipelines/${e}/archive`,{})}async delete(e){return this.deleteRequest(`/api/crm/pipelines/${e}`)}async checkInUse(e){return this.get(`/api/crm/pipelines/${e}/in-use`)}async board(e){return this.get(`/api/crm/pipelines/${e}/board`)}async forecast(e){return this.get(`/api/crm/pipelines/${e}/forecast`)}async addStage(e,t){return this.post(`/api/crm/pipelines/${e}/stages`,t)}async reorderStages(e,t){return this.patch(`/api/crm/pipelines/${e}/stages/reorder`,{order:t})}async updateStage(e,t){return this.patch(`/api/crm/stages/${e}`,t)}async deleteStage(e,t){return this.deleteRequest(`/api/crm/stages/${e}`,{data:t?{moveLeadsToStageId:t}:void 0})}};var D=class extends n{async getConfig(){return this.get("/api/crm/scoring")}async updateConfig(e){return this.patch("/api/crm/scoring",e)}async recalculate(e){return this.post(`/api/crm/scoring/${e}/recalculate`,{})}};var U=class extends n{async enroll(e){return this.post("/api/crm/sequences/enroll",e)}async unenroll(e){return this.deleteRequest(`/api/crm/sequences/unenroll/${e}`)}async listForLead(e){return this.get(`/api/crm/sequences/lead/${e}`)}};var M=class{constructor(e){i(this,"leads");i(this,"pipelines");i(this,"activities");i(this,"analytics");i(this,"automations");i(this,"sequences");i(this,"scoring");i(this,"payments");i(this,"automationDashboard");this.leads=new S(e),this.pipelines=new q(e),this.activities=new A(e),this.analytics=new $(e),this.automations=new E(e),this.sequences=new U(e),this.scoring=new D(e),this.payments=new L(e),this.automationDashboard=new I(e)}};var O=class extends n{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/marketing/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/marketing/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/marketing/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/marketing/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/marketing/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/marketing/mail/templates/${e}/preview`,t)}};var N=class extends n{async list(){return this.get("/api/saas/events")}async assign(e){return this.post("/api/saas/events/assign",e)}async unassign(e){return this.post("/api/saas/events/unassign",{name:e})}async unassignBulk(e){return this.post("/api/saas/events/unassign/bulk",{names:e})}async trigger(e){return this.post("/api/saas/workflows/trigger",e)}async listCustomEvents(){return this.get("/api/saas/crm/custom-events")}async createCustomEvent(e){return this.post("/api/saas/crm/custom-events",e)}async deleteCustomEvent(e){return this.deleteRequest(`/api/saas/crm/custom-events/${e}`)}async emit(e){return this.post("/api/crm/events/emit",e)}};var _=class extends n{async system(){return(await this.get("/api/saas/health")).data}async clientHealth(){return(await this.get("/api/saas/health/client")).data}async getDiagnosticReport(){return this.clientHealth()}async jobStatus(e){return(await this.get(`/api/saas/jobs/status/${e}`)).data}};var B=class extends n{async listEventLogs(e){return this.get("/api/saas/events/logs",{params:e})}async getEventLog(e){return this.get(`/api/saas/events/logs/${e}`)}async listCallbackLogs(e){return this.get("/api/saas/callbacks/logs",{params:e})}async getStats(){return this.get("/api/saas/events/stats")}};var re=class extends n{async sendCampaign(e){return this.post("/api/saas/marketing/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/marketing/emails/test",{to:e})}},ie=class extends n{async list(e){return this.get("/api/saas/marketing/emails/campaigns",{params:e})}async stats(e){return this.get(`/api/saas/marketing/emails/campaigns/${e}/analytics`)}},oe=class extends n{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},H=class extends n{constructor(t){super(t);i(this,"emails");i(this,"campaigns");i(this,"whatsapp");this.emails=new re(t),this.campaigns=new ie(t),this.whatsapp=new oe(t)}};import Ce from"axios";var F=class extends n{async getUsage(){return this.get("/api/saas/storage/usage")}async createFolder(e){return this.post("/api/saas/storage/folders",{name:e})}async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async aiDescribe(e){return this.post("/api/saas/storage/ai/describe",{key:e})}async upload(e,t){let a=await this.post("/api/saas/storage/upload-url",t),{uploadUrl:r,key:o}=a.data;await Ce.put(r,e,{headers:{"Content-Type":t.contentType}});let c=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:o,sizeBytes:c})}};var j=class extends n{async create(e){return this.post("/api/saas/meet",e)}async list(e){return this.get("/api/saas/meet",{params:e})}async retrieve(e){return this.get(`/api/saas/meet/${e}`)}async update(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async reschedule(e,t){return this.patch(`/api/saas/meet/${e}`,t)}async delete(e){return this.update(e,{status:"cancelled"})}};var K=class extends n{async listLogs(e){return this.get("/api/saas/events/logs",{params:e})}async retrieveLog(e){return this.get(`/api/saas/events/logs/${e}`)}async getStats(e){return this.get("/api/saas/events/stats",{params:e})}async listCallbacks(e){return this.get("/api/saas/callbacks/logs",{params:e})}async listAlerts(e){return this.get("/api/crm/notifications",{params:e})}async dismissAlert(e){return this.patch(`/api/crm/notifications/${e}/dismiss`)}async clearAllAlerts(){return this.deleteRequest("/api/crm/notifications/clear-all")}async retryAction(e){return this.post(`/api/crm/notifications/${e}/retry`,{})}};var V=class extends n{async listFailed(){return this.get("/api/saas/admin/queue/failed")}async getStats(){return this.get("/api/saas/admin/queue/stats")}async retryJob(e){return this.post(`/api/saas/admin/queue/${e}/retry`,{})}async deleteJob(e){return this.deleteRequest(`/api/saas/admin/queue/${e}`)}};var ce=class extends n{async list(){return this.get("/api/clients")}async getCountAndGenerateCode(){return this.get("/api/clients/count")}async retrieve(e){return this.get(`/api/clients/${e}`)}async getApiKey(e){return this.get(`/api/clients/${e}/api-key`)}async rotateApiKey(e){return this.post(`/api/clients/${e}/api-key`,{})}async create(e){return this.post("/api/clients",e)}async getConfig(e){return this.get(`/api/clients/${e}/config`)}async updateConfig(e,t){return this.patch(`/api/clients/${e}/config`,t)}async getConnections(e){return this.get(`/api/clients/${e}/connections`)}async getConnectProviders(e){return this.get(`/api/clients/${e}/connections/providers`)}async connectProvider(e,t,a){return this.post(`/api/clients/${e}/connections/${t}/connect`,a)}async configureProvider(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/configure`,a)}async disconnectProvider(e,t){return this.post(`/api/clients/${e}/connections/${t}/disconnect`,{})}async setConnectionAccess(e,t,a){return this.put(`/api/clients/${e}/connections/${t}/access`,a)}async getDataSource(e){return this.get(`/api/clients/${e}/datasource`)}async manageDataSource(e,t){return this.post(`/api/clients/${e}/datasource`,t)}async updateIdentity(e,t){return this.patch(`/api/clients/${e}/identity`,t)}async googleReauth(e,t={}){return this.post(`/api/clients/${e}/google/reauth`,t)}async delete(e){return this.deleteRequest(`/api/clients/${e}`)}},pe=class extends n{async list(){return this.get("/api/services/blogs")}},le=class extends n{async add(e){return this.post("/api/services/add-lead",e)}},Q=class extends n{constructor(t){super(t);i(this,"clients");i(this,"blogs");i(this,"globalLeads");this.clients=new ce(t),this.blogs=new pe(t),this.globalLeads=new le(t)}};var ge=class extends n{async getConfig(){return this.get("/api/settings/email")}async switchProvider(e){return this.post("/api/settings/email/provider",{provider:e})}async saveSmtp(e){return this.post("/api/settings/email/smtp",e)}async initDomainVerification(e){return this.post("/api/settings/email/ses/domain",{domain:e})}async saveEmailConfig(e){return this.post("/api/settings/email/ses/config",e)}async checkSesVerification(){return this.get("/api/settings/email/ses/verify")}async removeSesIdentity(){return this.deleteRequest("/api/settings/email/ses/domain")}async sendTest(e){return this.post("/api/settings/email/test",{toEmail:e})}async saveAdvancedConfig(e){return this.post("/api/settings/email/advanced",e)}async getHealth(){return this.get("/api/settings/email/health")}async fixDmarc(){return this.post("/api/settings/email/ses/fix-dmarc",{})}async listProviders(){return this.get("/api/settings/email/providers")}},J=class extends n{constructor(t){super(t);i(this,"email");this.email=new ge(t)}};var ue=class extends n{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},me=class extends n{async list(e,t){return this.get(`/api/saas/storage/files/${e}`,{params:t})}async getUploadUrl(e){return this.post("/api/saas/storage/upload-url",e)}async confirmUpload(e){return this.post("/api/saas/storage/confirm-upload",e)}async getDownloadUrl(e){return this.post("/api/saas/storage/download-url",{key:e})}async delete(e){return this.deleteRequest("/api/saas/storage/files",{params:{key:e}})}},W=class extends n{constructor(t){super(t);i(this,"folders");i(this,"files");this.folders=new ue(t),this.files=new me(t)}async usage(){return this.get("/api/saas/storage/usage")}};var v=class extends g{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},G=class{async constructEvent(e,t,a){if(!t)throw new v("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"),l=o.createHmac("sha256",a).update(e).digest("hex");if(!o.timingSafeEqual(Buffer.from(l),Buffer.from(r)))throw new v("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(o){throw o instanceof v?o:new v(`Webhook payload parsing failed: ${o.message}`)}}};var z=class extends n{async list(e){return this.get("/api/saas/chat/broadcasts",{params:e})}async retrieve(e){return this.get(`/api/saas/chat/broadcasts/${e}`)}async create(e){return this.post("/api/saas/chat/broadcast",e)}async update(e,t){return this.patch(`/api/saas/chat/broadcasts/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/chat/broadcasts/${e}`)}};var X=class extends n{async list(e){return this.get("/api/saas/chat/conversations",{params:e})}async create(e){return this.post("/api/saas/chat/conversations",e)}async retrieve(e){return this.get(`/api/saas/chat/conversations/${e}`)}async messages(e,t){return this.get(`/api/saas/chat/conversations/${e}/messages`,{params:t})}async linkLead(e,t,a){return this.post(`/api/saas/chat/conversations/${e}/link-lead`,{leadId:t,leadData:a})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`,{})}async delete(e){return this.deleteRequest(`/api/saas/chat/conversations/${e}`)}async bulkDelete(e){return this.post("/api/saas/chat/conversations/bulk-delete",{ids:e})}};var Y=class extends n{async send(e){return this.post("/api/saas/chat/send",e)}async sendTemplate(e){return this.post("/api/saas/chat/send",P(T({},e),{templateLanguage:e.language||e.templateLanguage||"en_US"}))}async star(e,t){return this.post(`/api/saas/chat/messages/${e}/star`,{isStarred:t})}async react(e,t){return this.post(`/api/saas/chat/messages/${e}/react`,{reaction:t})}async markRead(e){return this.post(`/api/saas/chat/conversations/${e}/read`)}async upload(e){let t=new FormData;return t.append("file",e),this.post("/api/saas/chat/upload",t,{headers:{"Content-Type":"multipart/form-data"}})}};var Z=class extends n{async list(e){return this.get("/api/saas/chat/templates",{params:e})}async sync(){return this.post("/api/saas/chat/templates/sync",{})}async retrieve(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}`)}async create(e){return this.post("/api/saas/chat/templates",e)}async update(e,t){return this.put(`/api/saas/chat/templates/${e}`,t)}async deleteTemplate(e,t){return this.deleteRequest(`/api/saas/chat/templates/${encodeURIComponent(e)}${t?"?force=true":""}`)}async mappingConfig(){return this.get("/api/saas/chat/templates/mapping/config")}async collections(){return this.get("/api/saas/chat/templates/collections")}async collectionFields(e){return this.get(`/api/saas/chat/templates/collections/${encodeURIComponent(e)}/fields`)}async updateMapping(e,t){return this.put(`/api/saas/chat/templates/${encodeURIComponent(e)}/mapping`,t)}async validate(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/validate`)}async preview(e,t){return this.post(`/api/saas/chat/templates/${encodeURIComponent(e)}/preview`,{context:t})}async getVariableManifest(e){var o,c;let t=await this.retrieve(e),a=Array.isArray((o=t.data)==null?void 0:o.components)?t.data.components:[],r=[];for(let l of a)if(l.text){let p=l.text.match(/{{(\d+)}}/g);if(p)for(let d of p){let y=d.replace(/{{|}}/g,"");r.push({key:`var_${y}`,label:`${l.type} Var {{${y}}}`,type:"string",required:!0,group:l.type,description:`Variable placeholder in template ${l.type}`})}}return{name:`Template variables: ${((c=t.data)==null?void 0:c.name)||e}`,fields:r,uiHints:{icon:"Variables",primaryColor:"#059669"}}}async checkUsage(e){return this.get(`/api/saas/chat/templates/${encodeURIComponent(e)}/usage`)}};var ee=class extends n{constructor(t){super(t);i(this,"messages");i(this,"conversations");i(this,"broadcasts");i(this,"templates");this.messages=new Y(t),this.conversations=new X(t),this.broadcasts=new z(t),this.templates=new Z(t)}async upload(t,a){let r=new FormData;return r.append("file",t,a),this.post("/api/saas/chat/upload",r,{headers:typeof r.getHeaders=="function"?r.getHeaders():void 0})}async sendTemplate(t){return this.post("/api/saas/marketing/whatsapp/send-template",t)}};var $e="https://api.ecodrix.com",w=class{constructor(e){i(this,"client");i(this,"socket",null);i(this,"socketPromise",null);i(this,"socketQueue",[]);i(this,"clientCode");i(this,"whatsapp");i(this,"crm");i(this,"media");i(this,"meet");i(this,"notifications");i(this,"email");i(this,"logs");i(this,"events");i(this,"webhooks");i(this,"storage");i(this,"marketing");i(this,"health");i(this,"queue");i(this,"agency");i(this,"services");i(this,"settings");i(this,"cors");i(this,"checkout");var p,d,y,x;if(!e.apiKey)throw new m("API Key is required");this.clientCode=(p=e.clientCode)==null?void 0:p.toUpperCase();let t=(d=e.baseUrl)!=null?d:$e,a=e.socketUrl||t,r=typeof window!="undefined"&&typeof window.document!="undefined",o=r?"browser":typeof process!="undefined"?`node ${process.version}`:"unknown",c=r?((y=globalThis.navigator)==null?void 0:y.userAgent)||"browser":typeof process!="undefined"?process.platform:"unknown",l={"x-api-key":e.apiKey,"x-client-code":((x=e.clientCode)==null?void 0:x.toUpperCase())||"","Content-Type":"application/json","x-ecodrix-client-agent":JSON.stringify({sdk_version:"1.0.0",runtime:o,os:c})};if(e.coreApiKey&&(l["x-core-api-key"]=e.coreApiKey),this.client=Ae.create({baseURL:t,headers:l}),ye(this.client,{retries:3,retryDelay:ye.exponentialDelay,retryCondition:h=>{var b;return ye.isNetworkOrIdempotentRequestError(h)||((b=h.response)==null?void 0:b.status)===429},onRetry:(h,b,u)=>{var de,he;typeof process!="undefined"&&((de=process.env)==null?void 0:de.NODE_ENV)==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${h}/3): ${(he=u.method)==null?void 0:he.toUpperCase()} ${u.url}. Reason: ${b.message}`)}}),this.whatsapp=new ee(this.client),this.crm=new M(this.client),this.media=new F(this.client),this.meet=new j(this.client),this.notifications=new K(this.client),this.email=new O(this.client),this.logs=new B(this.client),this.events=new N(this.client),this.webhooks=new G,this.storage=new W(this.client),this.marketing=new H(this.client),this.health=new _(this.client),this.queue=new V(this.client),this.agency=new R(this.client),this.services=new Q(this.client),this.settings=new J(this.client),this.cors=new C(this.client),this.checkout=new k(this.client),this.initSocket(a,e.apiKey,e.clientCode),r){let h={version:"1.2.2",clientCode:e.clientCode,initializedAt:new Date().toISOString()};window.__ECODRIX_SDK__=h,window.ecodrix||(window.ecodrix=this)}}initSocket(e,t,a){return this.socketPromise?this.socketPromise:(this.socketPromise=import("socket.io-client").then(({io:r})=>{this.socket=r(e,{extraHeaders:{"x-api-key":t,"x-client-code":(a==null?void 0:a.toUpperCase())||""}}),this.setupSocket(a);for(let{type:o,args:c}of this.socketQueue)o==="joinRoom"?this.socket.emit("join-room",c[0]):o==="leaveRoom"?this.socket.emit("leave-room",c[0]):o==="on"?this.socket.on(c[0],c[1]):o==="off"?this.socket.off(c[0],c[1]):o==="disconnect"&&this.socket.disconnect();this.socketQueue=[]}),this.socketPromise)}joinRoom(e){this.socket?this.socket.emit("join-room",e):this.socketQueue.push({type:"joinRoom",args:[e]})}leaveRoom(e){this.socket?this.socket.emit("leave-room",e):this.socketQueue.push({type:"leaveRoom",args:[e]})}setupSocket(e){this.socket&&this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket?this.socket.on(e,t):this.socketQueue.push({type:"on",args:[e,t]}),this}disconnect(){this.socket?this.socket.disconnect():this.socketQueue.push({type:"disconnect",args:[]})}off(e,t){return this.socket?this.socket.off(e,t):this.socketQueue.push({type:"off",args:[e,t]}),this}async request(e,t,a,r){var o,c,l;try{return(await this.client.request({method:e,url:t,data:a,params:r})).data}catch(p){throw p.response?new g(((o=p.response.data)==null?void 0:o.message)||((c=p.response.data)==null?void 0:c.error)||"Raw Execution Failed",p.response.status,(l=p.response.data)==null?void 0:l.code):new g(p.message||"Network Error")}}};var Ie={401:m,403:m,429:f};function Os(s){var e,t,a;if(s.response){let r=s.response.status,o=((e=s.response.data)==null?void 0:e.message)||((t=s.response.data)==null?void 0:t.error)||"API Request Failed",c=(a=s.response.data)==null?void 0:a.code,l=Ie[r]||g;throw l===m?new m(o):l===f?new f(o):new g(o,r,c)}throw new g(s.message||"Network Error")}function Ns(s,e){return s instanceof e}function _s(s){return s instanceof m?{message:s.message,status:s.status,code:s.code,type:"AuthenticationError"}:s instanceof f?{message:s.message,status:s.status,code:s.code,type:"RateLimitError"}:s instanceof g?{message:s.message,status:s.status,code:s.code,type:"APIError"}:{message:s.message||"Unknown error",type:"UnknownError"}}var be={[m.name]:{shouldRetry:!1,reason:"Authentication errors require fixing credentials, not retrying"},[f.name]:{shouldRetry:!0,maxRetries:3,baseDelay:1e3,backoffMultiplier:2,reason:"Rate limit errors can be retried with exponential backoff"},[g.name]:{shouldRetry:!0,maxRetries:2,baseDelay:500,backoffMultiplier:1.5,reason:"Generic API errors may be transient and worth retrying"}};function Bs(s){let e=s.constructor.name;return be[e]||be[g.name]}var js=w;export{g as APIError,m as AuthenticationError,w as ECODrIx,w as ECODrIxAPI,be as ERROR_RETRY_CONFIG,ae as EcodrixError,Ie as HTTP_STATUS_ERROR_MAP,f as RateLimitError,js as default,_s as getErrorDetails,Bs as getRetryConfig,Os as handleAPIError,Ns as isAPIError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecodrix/erix-api",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"author": "ECODrIx Team <contact@ecodrix.com>",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",
|