@ecodrix/erix-api 1.2.7 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import ie from"repl";import{Command as oe}from"commander";import ce from"dotenv";import o from"picocolors";import ae from"axios";import X from"axios-retry";import{io as ne}from"socket.io-client";var H=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends H{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},T=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}};var i=class{constructor(e){this.client=e}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){throw e.response?new u(e.response.data?.message||e.response.data?.error||"API Request Failed",e.response.status,e.response.data?.code):new u(e.message||"Network Error")}};var j=class extends i{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}`)}},f=class extends i{notes;constructor(e){super(e),this.notes=new j(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 b=class extends i{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 v=class extends i{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 x=class extends i{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/webhook-event",{ruleId:e,eventName:t,payload:a})}};var P=class extends i{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(r=>({key:`metadata.extra.${r.name}`,label:r.label||r.name,type:r.type||"string",required:!!r.required,options:r.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 l=e.slice(s,s+t).map(m=>this.create(m)),g=await Promise.allSettled(l);for(let m of g)if(m.status==="fulfilled")a.push(m.value);else throw m.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads: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}),r=Array.isArray(s.data)?s.data:s||[];if(r.length===0){a=!1;break}for(let l of r)yield l;s.pagination&&t<s.pagination.pages||!s.pagination&&r.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 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 bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}};var w=class extends i{async capture(e){return this.post("/api/crm/payments/capture",e)}};var $=class extends i{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 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 R=class extends i{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 C=class extends i{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 A=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new P(e),this.pipelines=new $(e),this.activities=new f(e),this.analytics=new b(e),this.automations=new x(e),this.sequences=new C(e),this.scoring=new R(e),this.payments=new w(e),this.automationDashboard=new v(e)}};var I=class extends i{async sendCampaign(e){return this.post("/api/saas/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/mail/templates/${e}/preview`,t)}};var k=class extends i{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/saas/crm/events/emit",e)}};var E=class extends i{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 S=class extends i{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 J=class extends i{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})}},Y=class extends i{async list(e){return this.get("/api/saas/marketing/campaigns",{params:e})}async create(e){return this.post("/api/saas/marketing/campaigns",e)}async retrieve(e){return this.get(`/api/saas/marketing/campaigns/${e}`)}async update(e,t){return this.patch(`/api/saas/marketing/campaigns/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/marketing/campaigns/${e}`)}async send(e,t){return this.post(`/api/saas/marketing/campaigns/${e}/send`,t||{})}async stats(e){return this.get(`/api/saas/marketing/campaigns/${e}/stats`)}},z=class extends i{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},D=class extends i{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new J(e),this.campaigns=new Y(e),this.whatsapp=new z(e)}};import se from"axios";var L=class extends i{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:r}=a.data;await se.put(s,e,{headers:{"Content-Type":t.contentType}});let l=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:r,sizeBytes:l})}};var q=class extends i{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 O=class extends i{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 M=class extends i{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 G=class extends i{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Q=class extends i{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}})}},N=class extends i{folders;files;constructor(e){super(e),this.folders=new G(e),this.files=new Q(e)}async usage(){return this.get("/api/saas/storage/usage")}};var h=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},U=class{async constructEvent(e,t,a){if(!t)throw new h("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let r=await import("crypto"),g=r.createHmac("sha256",a).update(e).digest("hex");if(!r.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new h("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(r){throw r instanceof h?r:new h(`Webhook payload parsing failed: ${r.message}`)}}};var _=class extends i{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 F=class extends i{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 B=class extends i{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 K=class extends i{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 r of a)if(r.text){let l=r.text.match(/{{(\d+)}}/g);if(l)for(let g of l){let m=g.replace(/{{|}}/g,"");s.push({key:`var_${m}`,label:`${r.type} Var {{${m}}}`,type:"string",required:!0,group:r.type,description:`Variable placeholder in template ${r.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 V=class extends i{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new B(e),this.conversations=new F(e),this.broadcasts=new _(e),this.templates=new K(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 re="https://api.ecodrix.com",W=class{client;socket;clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;constructor(e){if(!e.apiKey)throw new T("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??re,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",r=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",l=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown";if(this.client=ae.create({baseURL:t,headers:{"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:r,os:l})}}),X(this.client,{retries:3,retryDelay:X.exponentialDelay,retryCondition:g=>X.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,m,Z)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${Z.method?.toUpperCase()} ${Z.url}. Reason: ${m.message}`)}}),this.whatsapp=new V(this.client),this.crm=new A(this.client),this.media=new L(this.client),this.meet=new q(this.client),this.notifications=new O(this.client),this.email=new I(this.client),this.logs=new S(this.client),this.events=new k(this.client),this.webhooks=new U,this.storage=new N(this.client),this.marketing=new D(this.client),this.health=new E(this.client),this.queue=new M(this.client),this.socket=ne(a,{extraHeaders:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""}}),this.setupSocket(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)}}joinRoom(e){this.socket.emit("join-room",e)}leaveRoom(e){this.socket.emit("leave-room",e)}setupSocket(e){this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket.on(e,t),this}disconnect(){this.socket.disconnect()}off(e,t){return this.socket.off(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(r){throw r.response?new u(r.response.data?.message||r.response.data?.error||"Raw Execution Failed",r.response.status,r.response.data?.code):new u(r.message||"Network Error")}}};ce.config();var ee="1.2.7";var pe="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new oe;d.name("erix").description(pe).version(ee);function y(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 W({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=y(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 le=d.command("whatsapp").description("WhatsApp Business API operations");le.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(),r=y(s);try{let l=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let g=await r.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:l});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(l){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(l.message))}});var te=d.command("crm").description("CRM and Lead management");te.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=y(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let r={limit:s};n.status&&(r.status=n.status),n.pipeline&&(r.pipelineId=n.pipeline),n.search&&(r.search=n.search);let l=await a.crm.leads.list(r),g=Array.isArray(l.data)?l.data:Array.isArray(l)?l:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(m=>({ID:m.id||m._id,Name:`${m.firstName} ${m.lastName||""}`.trim(),Phone:m.phone,Status:m.status,Score:m.score||0,Created:new Date(m.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});te.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),r=s.data||s||[];if(r.length===0){console.log(o.yellow("No pipelines found."));return}console.table(r.map(l=>({ID:l.id||l._id,Name:l.name,Default:l.isDefault?"Yes":"No",Stages:l.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var me=d.command("analytics").description("Business Intelligence Analytics");me.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=y(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),r=s.data||s;console.log(`
2
+ import ie from"repl";import{Command as oe}from"commander";import ce from"dotenv";import o from"picocolors";import ae from"axios";import X from"axios-retry";import{io as ne}from"socket.io-client";var H=class extends Error{constructor(e){super(e),this.name="EcodrixError"}},u=class extends H{status;code;constructor(e,t,a){super(e),this.name="APIError",this.status=t,this.code=a}},T=class extends u{constructor(e="Invalid API Key or Client Code"){super(e,401,"AUTH_FAILED"),this.name="AuthenticationError"}};var i=class{constructor(e){this.client=e}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){throw e.response?new u(e.response.data?.message||e.response.data?.error||"API Request Failed",e.response.status,e.response.data?.code):new u(e.message||"Network Error")}};var j=class extends i{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}`)}},f=class extends i{notes;constructor(e){super(e),this.notes=new j(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 b=class extends i{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 v=class extends i{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 x=class extends i{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/webhook-event",{ruleId:e,eventName:t,payload:a})}};var P=class extends i{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(r=>({key:`metadata.extra.${r.name}`,label:r.label||r.name,type:r.type||"string",required:!!r.required,options:r.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 l=e.slice(s,s+t).map(m=>this.create(m)),g=await Promise.allSettled(l);for(let m of g)if(m.status==="fulfilled")a.push(m.value);else throw m.reason}return a}async import(e){return this.post("/api/crm/leads/import",{leads: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}),r=Array.isArray(s.data)?s.data:s||[];if(r.length===0){a=!1;break}for(let l of r)yield l;s.pagination&&t<s.pagination.pages||!s.pagination&&r.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 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 bulkDelete(e){return this.deleteRequest("/api/crm/leads",{data:{ids:e}})}};var w=class extends i{async capture(e){return this.post("/api/crm/payments/capture",e)}};var $=class extends i{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 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 R=class extends i{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 C=class extends i{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 A=class{leads;pipelines;activities;analytics;automations;sequences;scoring;payments;automationDashboard;constructor(e){this.leads=new P(e),this.pipelines=new $(e),this.activities=new f(e),this.analytics=new b(e),this.automations=new x(e),this.sequences=new C(e),this.scoring=new R(e),this.payments=new w(e),this.automationDashboard=new v(e)}};var I=class extends i{async sendCampaign(e){return this.post("/api/saas/emails/campaign",e)}async sendTest(e){return this.post("/api/saas/emails/test",{to:e})}async listTemplates(e){return this.get("/api/saas/mail/templates",{params:e})}async getTemplate(e){return this.get(`/api/saas/mail/templates/${e}`)}async createTemplate(e){return this.post("/api/saas/mail/templates",e)}async updateTemplate(e,t){return this.put(`/api/saas/mail/templates/${e}`,t)}async deleteTemplate(e,t=!1){return this.deleteRequest(`/api/saas/mail/templates/${e}`,{params:{force:t}})}async previewTemplate(e,t){return this.post(`/api/saas/mail/templates/${e}/preview`,t)}};var k=class extends i{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/saas/crm/events/emit",e)}};var E=class extends i{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 S=class extends i{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 J=class extends i{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})}},Y=class extends i{async list(e){return this.get("/api/saas/marketing/campaigns",{params:e})}async create(e){return this.post("/api/saas/marketing/campaigns",e)}async retrieve(e){return this.get(`/api/saas/marketing/campaigns/${e}`)}async update(e,t){return this.patch(`/api/saas/marketing/campaigns/${e}`,t)}async delete(e){return this.deleteRequest(`/api/saas/marketing/campaigns/${e}`)}async send(e,t){return this.post(`/api/saas/marketing/campaigns/${e}/send`,t||{})}async stats(e){return this.get(`/api/saas/marketing/campaigns/${e}/stats`)}},z=class extends i{async sendTemplate(e){return this.post("/api/saas/marketing/whatsapp/send-template",e)}},D=class extends i{emails;campaigns;whatsapp;constructor(e){super(e),this.emails=new J(e),this.campaigns=new Y(e),this.whatsapp=new z(e)}};import se from"axios";var L=class extends i{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:r}=a.data;await se.put(s,e,{headers:{"Content-Type":t.contentType}});let l=e.size||e.byteLength||0;return this.post("/api/saas/storage/confirm-upload",{key:r,sizeBytes:l})}};var q=class extends i{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 O=class extends i{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 M=class extends i{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 G=class extends i{async create(e){return this.post("/api/saas/storage/folders",{name:e})}async delete(e){return this.deleteRequest(`/api/saas/storage/folders/${encodeURIComponent(e)}`)}},Q=class extends i{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}})}},N=class extends i{folders;files;constructor(e){super(e),this.folders=new G(e),this.files=new Q(e)}async usage(){return this.get("/api/saas/storage/usage")}};var h=class extends u{constructor(e){super(e,400,"invalid_signature"),this.name="WebhookSignatureError"}},U=class{async constructEvent(e,t,a){if(!t)throw new h("No webhook signature provided");let s=Array.isArray(t)?t[0]:t;s.startsWith("sha256=")&&(s=s.slice(7));try{let r=await import("crypto"),g=r.createHmac("sha256",a).update(e).digest("hex");if(!r.timingSafeEqual(Buffer.from(g),Buffer.from(s)))throw new h("Invalid webhook signature provided");return JSON.parse(e.toString("utf8"))}catch(r){throw r instanceof h?r:new h(`Webhook payload parsing failed: ${r.message}`)}}};var _=class extends i{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 F=class extends i{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 B=class extends i{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 K=class extends i{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 r of a)if(r.text){let l=r.text.match(/{{(\d+)}}/g);if(l)for(let g of l){let m=g.replace(/{{|}}/g,"");s.push({key:`var_${m}`,label:`${r.type} Var {{${m}}}`,type:"string",required:!0,group:r.type,description:`Variable placeholder in template ${r.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 V=class extends i{messages;conversations;broadcasts;templates;constructor(e){super(e),this.messages=new B(e),this.conversations=new F(e),this.broadcasts=new _(e),this.templates=new K(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 re="https://api.ecodrix.com",W=class{client;socket;clientCode;whatsapp;crm;media;meet;notifications;email;logs;events;webhooks;storage;marketing;health;queue;constructor(e){if(!e.apiKey)throw new T("API Key is required");this.clientCode=e.clientCode?.toUpperCase();let t=e.baseUrl??re,a=e.socketUrl||t,s=typeof window<"u"&&typeof window.document<"u",r=s?"browser":typeof process<"u"?`node ${process.version}`:"unknown",l=s?globalThis.navigator?.userAgent||"browser":typeof process<"u"?process.platform:"unknown";if(this.client=ae.create({baseURL:t,headers:{"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:r,os:l})}}),X(this.client,{retries:3,retryDelay:X.exponentialDelay,retryCondition:g=>X.isNetworkOrIdempotentRequestError(g)||g.response?.status===429,onRetry:(g,m,Z)=>{typeof process<"u"&&process.env?.NODE_ENV==="development"&&console.warn(`[ECODrIx SDK] Retrying request (${g}/3): ${Z.method?.toUpperCase()} ${Z.url}. Reason: ${m.message}`)}}),this.whatsapp=new V(this.client),this.crm=new A(this.client),this.media=new L(this.client),this.meet=new q(this.client),this.notifications=new O(this.client),this.email=new I(this.client),this.logs=new S(this.client),this.events=new k(this.client),this.webhooks=new U,this.storage=new N(this.client),this.marketing=new D(this.client),this.health=new E(this.client),this.queue=new M(this.client),this.socket=ne(a,{extraHeaders:{"x-api-key":e.apiKey,"x-client-code":e.clientCode?.toUpperCase()||""}}),this.setupSocket(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)}}joinRoom(e){this.socket.emit("join-room",e)}leaveRoom(e){this.socket.emit("leave-room",e)}setupSocket(e){this.socket.on("connect",()=>{e&&this.socket.emit("join-room",e.toUpperCase())})}on(e,t){return this.socket.on(e,t),this}disconnect(){this.socket.disconnect()}off(e,t){return this.socket.off(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(r){throw r.response?new u(r.response.data?.message||r.response.data?.error||"Raw Execution Failed",r.response.status,r.response.data?.code):new u(r.message||"Network Error")}}};ce.config();var ee="1.2.9";var pe="Official Isomorphic SDK for the ECODrIx platform. Native support for WhatsApp, CRM, Storage, and Meetings across TS, JS, Python, and Java.",d=new oe;d.name("erix").description(pe).version(ee);function y(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 W({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=y(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 le=d.command("whatsapp").description("WhatsApp Business API operations");le.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(),r=y(s);try{let l=JSON.parse(t.vars);console.log(o.cyan(`Sending template '${e}' to ${n}...`));let g=await r.whatsapp.messages.sendTemplate({to:n,templateName:e,language:"en_US",variables:l});console.log(o.green("\u2714 Message sent successfully!")),console.log(o.dim(`ID: ${g?.id||"N/A"}`))}catch(l){console.error(o.red("\u2716 Failed to send message")),console.error(o.dim(l.message))}});var te=d.command("crm").description("CRM and Lead management");te.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=y(t);try{let s=Number.parseInt(n.limit);console.log(o.cyan(`Fetching last ${s} leads...`));let r={limit:s};n.status&&(r.status=n.status),n.pipeline&&(r.pipelineId=n.pipeline),n.search&&(r.search=n.search);let l=await a.crm.leads.list(r),g=Array.isArray(l.data)?l.data:Array.isArray(l)?l:[];if(g.length===0){console.log(o.yellow("No leads found."));return}console.table(g.map(m=>({ID:m.id||m._id,Name:`${m.firstName} ${m.lastName||""}`.trim(),Phone:m.phone,Status:m.status,Score:m.score||0,Created:new Date(m.createdAt).toLocaleDateString()})))}catch(s){console.error(o.red("\u2716 Failed to fetch leads")),console.error(o.dim(s.message))}});te.command("pipelines").description("List all CRM pipelines").action(async(n,e)=>{let t=e.parent.parent.opts(),a=y(t);try{console.log(o.cyan("Fetching pipelines..."));let s=await a.crm.pipelines.list(),r=s.data||s||[];if(r.length===0){console.log(o.yellow("No pipelines found."));return}console.table(r.map(l=>({ID:l.id||l._id,Name:l.name,Default:l.isDefault?"Yes":"No",Stages:l.stages?.length||0})))}catch(s){console.error(o.red("\u2716 Failed to fetch pipelines")),console.error(o.dim(s.message))}});var me=d.command("analytics").description("Business Intelligence Analytics");me.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=y(t);try{console.log(o.cyan(`Fetching overview metrics for last ${n.range}...`));let s=await a.crm.analytics.overview({range:n.range}),r=s.data||s;console.log(`
3
3
  ${o.bold("OVERVIEW KPIs:")}`),console.log(`Total Leads: ${o.green(r.totalLeads||0)}`),console.log(`Open Value: ${o.yellow(`$${(r.openValue||0).toLocaleString()}`)}`),console.log(`Won Revenue: ${o.green(`$${(r.wonRevenue||0).toLocaleString()}`)}`),console.log(`Avg Score: ${o.blue(r.avgScore?.toFixed(1)||0)}`),console.log(`Conversion: ${o.magenta(`${(r.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 ge=d.command("webhooks").description("Webhook utility tools");ge.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 r=s.parent.parent.opts(),l=y(r);try{await l.webhooks.constructEvent(n,e,t),console.log(o.green("\u2714 Signature is VALID"))}catch(g){console.error(o.red("\u2716 Error during verification")),console.error(o.dim(g.message))}});d.command("shell").alias("repl").description("Start an interactive SDK shell").action(async(n,e)=>{let t=e.parent.opts(),a=y(t);console.log(o.magenta(o.bold(`
5
5
  Welcome to the Erix Interactive Shell`))),console.log(o.dim(`SDK Version: ${ee}`)),console.log(o.dim(`The 'ecod' client is pre-initialized and ready.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecodrix/erix-api",
3
- "version": "1.2.7",
3
+ "version": "1.2.9",
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.",
@@ -41,24 +41,8 @@
41
41
  }
42
42
  },
43
43
  "files": [
44
- "dist",
45
- "src",
46
- "schema"
44
+ "dist"
47
45
  ],
48
- "scripts": {
49
- "build": "tsup",
50
- "build:final": "pnpm clear && pnpm build",
51
- "dev": "tsup --watch",
52
- "type": "tsc --noEmit",
53
- "clear": "rm -rf dist",
54
- "lint": "biome lint .",
55
- "format": "biome format --write .",
56
- "check": "biome check --write .",
57
- "prepublishOnly": "pnpm build:final",
58
- "publish:latest": "pnpm build:final && pnpm publish --access public --no-git-checks --tag latest",
59
- "publish:beta": "pnpm build:final && pnpm publish --access public --no-git-checks --tag beta",
60
- "publish:patch": "pnpm build:final && pnpm publish --access public --no-git-checks --tag patch"
61
- },
62
46
  "dependencies": {
63
47
  "axios": "^1.7.9",
64
48
  "axios-retry": "^4.5.0",
@@ -75,5 +59,18 @@
75
59
  },
76
60
  "publishConfig": {
77
61
  "access": "public"
62
+ },
63
+ "scripts": {
64
+ "build": "tsup",
65
+ "build:final": "pnpm clear && pnpm build",
66
+ "dev": "tsup --watch",
67
+ "type": "tsc --noEmit",
68
+ "clear": "rm -rf dist",
69
+ "lint": "biome lint .",
70
+ "format": "biome format --write .",
71
+ "check": "biome check --write .",
72
+ "publish:latest": "pnpm build:final && pnpm publish --access public --no-git-checks --tag latest",
73
+ "publish:beta": "pnpm build:final && pnpm publish --access public --no-git-checks --tag beta",
74
+ "publish:patch": "pnpm build:final && pnpm publish --access public --no-git-checks --tag patch"
78
75
  }
79
- }
76
+ }
@@ -1,199 +0,0 @@
1
- openapi: 3.0.0
2
- info:
3
- title: ECOD platform API
4
- description: The official API for the ECODrIx (ECOD) platform, supporting WhatsApp, CRM, Storage, and Meetings.
5
- version: 1.0.0
6
- servers:
7
- - url: https://api.ecodrix.com
8
- description: Production server
9
-
10
- components:
11
- securitySchemes:
12
- ApiKeyAuth:
13
- type: apiKey
14
- in: header
15
- name: x-api-key
16
- ClientCodeAuth:
17
- type: apiKey
18
- in: header
19
- name: x-client-code
20
-
21
- schemas:
22
- SuccessResponse:
23
- type: object
24
- properties:
25
- success:
26
- type: boolean
27
- message:
28
- type: string
29
- data:
30
- type: object
31
-
32
- Lead:
33
- type: object
34
- properties:
35
- id:
36
- type: string
37
- firstName:
38
- type: string
39
- lastName:
40
- type: string
41
- email:
42
- type: string
43
- phone:
44
- type: string
45
- status:
46
- type: string
47
- enum: [new, contacting, qualified, lost, won]
48
- pipelineId:
49
- type: string
50
- stageId:
51
- type: string
52
-
53
- Meeting:
54
- type: object
55
- properties:
56
- id:
57
- type: string
58
- title:
59
- type: string
60
- startTime:
61
- type: string
62
- format: date-time
63
- endTime:
64
- type: string
65
- format: date-time
66
- status:
67
- type: string
68
- enum: [scheduled, cancelled, completed]
69
-
70
- WhatsAppMessage:
71
- type: object
72
- properties:
73
- id:
74
- type: string
75
- to:
76
- type: string
77
- body:
78
- type: string
79
- type:
80
- type: string
81
- enum: [text, image, document]
82
-
83
- security:
84
- - ApiKeyAuth: []
85
- ClientCodeAuth: []
86
-
87
- paths:
88
- # --- CRM LEADS ---
89
- /saas/crm/leads:
90
- get:
91
- summary: List all leads
92
- tags: [CRM]
93
- responses:
94
- "200":
95
- description: A list of leads
96
- content:
97
- application/json:
98
- schema:
99
- type: object
100
- properties:
101
- success: { type: boolean }
102
- data:
103
- type: array
104
- items: { $ref: "#/components/schemas/Lead" }
105
- post:
106
- summary: Create a new lead
107
- tags: [CRM]
108
- requestBody:
109
- required: true
110
- content:
111
- application/json:
112
- schema: { $ref: "#/components/schemas/Lead" }
113
- responses:
114
- "201":
115
- description: Lead created
116
- content:
117
- application/json:
118
- schema: { $ref: "#/components/schemas/SuccessResponse" }
119
-
120
- /saas/crm/leads/{id}:
121
- parameters:
122
- - name: id
123
- in: path
124
- required: true
125
- schema: { type: string }
126
- get:
127
- summary: Retrieve a specific lead
128
- tags: [CRM]
129
- responses:
130
- "200":
131
- description: The lead details
132
- patch:
133
- summary: Update a lead
134
- tags: [CRM]
135
- requestBody:
136
- content:
137
- application/json:
138
- schema: { $ref: "#/components/schemas/Lead" }
139
- responses:
140
- "200":
141
- description: Lead updated
142
- delete:
143
- summary: Delete a lead
144
- tags: [CRM]
145
- responses:
146
- "200":
147
- description: Lead deleted
148
-
149
- # --- MEETINGS ---
150
- /saas/meet/meetings:
151
- get:
152
- summary: List scheduled meetings
153
- tags: [Meetings]
154
- responses:
155
- "200":
156
- description: List of meetings
157
- post:
158
- summary: Schedule a new meeting
159
- tags: [Meetings]
160
- requestBody:
161
- required: true
162
- content:
163
- application/json:
164
- schema: { $ref: "#/components/schemas/Meeting" }
165
- responses:
166
- "201":
167
- description: Meeting scheduled
168
-
169
- # --- STORAGE ---
170
- /saas/storage/presigned-url:
171
- post:
172
- summary: Generate a presigned URL for direct R2 upload
173
- tags: [Storage]
174
- requestBody:
175
- required: true
176
- content:
177
- application/json:
178
- schema:
179
- type: object
180
- properties:
181
- filename: { type: string }
182
- contentType: { type: string }
183
- responses:
184
- "200":
185
- description: Presigned URL generated
186
-
187
- # --- WHATSAPP ---
188
- /saas/whatsapp/messages:
189
- post:
190
- summary: Send a WhatsApp message
191
- tags: [WhatsApp]
192
- requestBody:
193
- required: true
194
- content:
195
- application/json:
196
- schema: { $ref: "#/components/schemas/WhatsAppMessage" }
197
- responses:
198
- "200":
199
- description: Message sent