@supsis/supsis-js 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Supsis JS SDK v1.0.0
2
+ * Supsis JS SDK v1.1.0
3
3
  * Supsis API SDK - Browser ve Node.js için omnichannel messaging, chatbot, automation, task, ticket ve voice agent entegrasyonu
4
4
  *
5
5
  * @license MIT
@@ -94,11 +94,22 @@ class HttpClient {
94
94
  * @param {boolean} [config.verbose=false] - Debug logları göster
95
95
  */
96
96
  constructor(config) {
97
+ config = config || {};
97
98
  this.config = Object.assign({}, DEFAULT_CONFIG, config);
98
99
  this.baseUrl = this._resolveBaseUrl();
99
100
  this.token = null;
100
- this.siteId = config.siteId || null;
101
- this.verbose = config.verbose || false;
101
+ this.siteId = this.config.siteId || null;
102
+ this.verbose = this.config.verbose || false;
103
+
104
+ // Debug: config değerlerini logla
105
+ if (this.verbose) {
106
+ console.log('[SupsisJS] HttpClient config:', {
107
+ timeout: this.config.timeout,
108
+ retryCount: this.config.retryCount,
109
+ env: this.config.env,
110
+ baseUrl: this.baseUrl
111
+ });
112
+ }
102
113
  }
103
114
 
104
115
  /**
@@ -236,10 +247,13 @@ class HttpClient {
236
247
  */
237
248
  async _fetchWithTimeout(url, options) {
238
249
  var self = this;
250
+ var timeout = this.config.timeout || 30000;
239
251
  var controller = new AbortController();
240
252
  var timeoutId = setTimeout(function() {
241
253
  controller.abort();
242
- }, this.config.timeout);
254
+ }, timeout);
255
+
256
+ self._log('info', 'Fetch timeout set to:', timeout, 'ms');
243
257
 
244
258
  try {
245
259
  var response = await fetch(url, Object.assign({}, options, {
@@ -250,19 +264,44 @@ class HttpClient {
250
264
  } catch (error) {
251
265
  clearTimeout(timeoutId);
252
266
 
253
- self._log('error', 'Fetch error:', error.name, error.message);
267
+ // Detaylı hata bilgisi
268
+ self._log('error', 'Fetch error details:', {
269
+ name: error.name,
270
+ message: error.message,
271
+ code: error.code,
272
+ cause: error.cause ? String(error.cause) : undefined
273
+ });
254
274
 
275
+ // AbortError - gerçek timeout mu yoksa başka bir sebep mi?
255
276
  if (error.name === 'AbortError') {
256
- throw new SupsisAPIError('Request timeout after ' + self.config.timeout + 'ms', 408, { originalError: error.message });
277
+ // error.cause varsa gerçek sebebi göster
278
+ var realCause = error.cause ? String(error.cause) : error.message;
279
+ throw new SupsisAPIError('Request aborted: ' + realCause, 408, {
280
+ originalError: error.message,
281
+ cause: realCause,
282
+ timeout: timeout
283
+ });
257
284
  }
258
285
 
259
286
  // Network hataları için daha açıklayıcı hata mesajı
260
- if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND' || error.message.indexOf('fetch') !== -1) {
261
- throw new SupsisAPIError('Network error: ' + error.message, 0, { originalError: error.message, code: error.code });
287
+ if (error.code === 'ECONNREFUSED') {
288
+ throw new SupsisAPIError('Connection refused: ' + url, 0, { originalError: error.message, code: error.code });
289
+ }
290
+
291
+ if (error.code === 'ENOTFOUND') {
292
+ throw new SupsisAPIError('Host not found: ' + url, 0, { originalError: error.message, code: error.code });
293
+ }
294
+
295
+ if (error.code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' || error.code === 'CERT_HAS_EXPIRED' || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') {
296
+ throw new SupsisAPIError('SSL/TLS certificate error: ' + error.message, 0, { originalError: error.message, code: error.code });
262
297
  }
263
298
 
264
299
  // Diğer hatalar için SupsisAPIError'a çevir
265
- throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, { originalError: error.message });
300
+ throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, {
301
+ originalError: error.message,
302
+ code: error.code,
303
+ cause: error.cause ? String(error.cause) : undefined
304
+ });
266
305
  }
267
306
  }
268
307
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Supsis JS SDK v1.0.0
2
+ * Supsis JS SDK v1.1.0
3
3
  * Supsis API SDK - Browser ve Node.js için omnichannel messaging, chatbot, automation, task, ticket ve voice agent entegrasyonu
4
4
  *
5
5
  * @license MIT
@@ -90,11 +90,22 @@ class HttpClient {
90
90
  * @param {boolean} [config.verbose=false] - Debug logları göster
91
91
  */
92
92
  constructor(config) {
93
+ config = config || {};
93
94
  this.config = Object.assign({}, DEFAULT_CONFIG, config);
94
95
  this.baseUrl = this._resolveBaseUrl();
95
96
  this.token = null;
96
- this.siteId = config.siteId || null;
97
- this.verbose = config.verbose || false;
97
+ this.siteId = this.config.siteId || null;
98
+ this.verbose = this.config.verbose || false;
99
+
100
+ // Debug: config değerlerini logla
101
+ if (this.verbose) {
102
+ console.log('[SupsisJS] HttpClient config:', {
103
+ timeout: this.config.timeout,
104
+ retryCount: this.config.retryCount,
105
+ env: this.config.env,
106
+ baseUrl: this.baseUrl
107
+ });
108
+ }
98
109
  }
99
110
 
100
111
  /**
@@ -232,10 +243,13 @@ class HttpClient {
232
243
  */
233
244
  async _fetchWithTimeout(url, options) {
234
245
  var self = this;
246
+ var timeout = this.config.timeout || 30000;
235
247
  var controller = new AbortController();
236
248
  var timeoutId = setTimeout(function() {
237
249
  controller.abort();
238
- }, this.config.timeout);
250
+ }, timeout);
251
+
252
+ self._log('info', 'Fetch timeout set to:', timeout, 'ms');
239
253
 
240
254
  try {
241
255
  var response = await fetch(url, Object.assign({}, options, {
@@ -246,19 +260,44 @@ class HttpClient {
246
260
  } catch (error) {
247
261
  clearTimeout(timeoutId);
248
262
 
249
- self._log('error', 'Fetch error:', error.name, error.message);
263
+ // Detaylı hata bilgisi
264
+ self._log('error', 'Fetch error details:', {
265
+ name: error.name,
266
+ message: error.message,
267
+ code: error.code,
268
+ cause: error.cause ? String(error.cause) : undefined
269
+ });
250
270
 
271
+ // AbortError - gerçek timeout mu yoksa başka bir sebep mi?
251
272
  if (error.name === 'AbortError') {
252
- throw new SupsisAPIError('Request timeout after ' + self.config.timeout + 'ms', 408, { originalError: error.message });
273
+ // error.cause varsa gerçek sebebi göster
274
+ var realCause = error.cause ? String(error.cause) : error.message;
275
+ throw new SupsisAPIError('Request aborted: ' + realCause, 408, {
276
+ originalError: error.message,
277
+ cause: realCause,
278
+ timeout: timeout
279
+ });
253
280
  }
254
281
 
255
282
  // Network hataları için daha açıklayıcı hata mesajı
256
- if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND' || error.message.indexOf('fetch') !== -1) {
257
- throw new SupsisAPIError('Network error: ' + error.message, 0, { originalError: error.message, code: error.code });
283
+ if (error.code === 'ECONNREFUSED') {
284
+ throw new SupsisAPIError('Connection refused: ' + url, 0, { originalError: error.message, code: error.code });
285
+ }
286
+
287
+ if (error.code === 'ENOTFOUND') {
288
+ throw new SupsisAPIError('Host not found: ' + url, 0, { originalError: error.message, code: error.code });
289
+ }
290
+
291
+ if (error.code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' || error.code === 'CERT_HAS_EXPIRED' || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') {
292
+ throw new SupsisAPIError('SSL/TLS certificate error: ' + error.message, 0, { originalError: error.message, code: error.code });
258
293
  }
259
294
 
260
295
  // Diğer hatalar için SupsisAPIError'a çevir
261
- throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, { originalError: error.message });
296
+ throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, {
297
+ originalError: error.message,
298
+ code: error.code,
299
+ cause: error.cause ? String(error.cause) : undefined
300
+ });
262
301
  }
263
302
  }
264
303
 
package/dist/supsis.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Supsis JS SDK v1.0.0
2
+ * Supsis JS SDK v1.1.0
3
3
  * Supsis API SDK - Browser ve Node.js için omnichannel messaging, chatbot, automation, task, ticket ve voice agent entegrasyonu
4
4
  *
5
5
  * @license MIT
@@ -96,11 +96,22 @@
96
96
  * @param {boolean} [config.verbose=false] - Debug logları göster
97
97
  */
98
98
  constructor(config) {
99
+ config = config || {};
99
100
  this.config = Object.assign({}, DEFAULT_CONFIG, config);
100
101
  this.baseUrl = this._resolveBaseUrl();
101
102
  this.token = null;
102
- this.siteId = config.siteId || null;
103
- this.verbose = config.verbose || false;
103
+ this.siteId = this.config.siteId || null;
104
+ this.verbose = this.config.verbose || false;
105
+
106
+ // Debug: config değerlerini logla
107
+ if (this.verbose) {
108
+ console.log('[SupsisJS] HttpClient config:', {
109
+ timeout: this.config.timeout,
110
+ retryCount: this.config.retryCount,
111
+ env: this.config.env,
112
+ baseUrl: this.baseUrl
113
+ });
114
+ }
104
115
  }
105
116
 
106
117
  /**
@@ -238,10 +249,13 @@
238
249
  */
239
250
  async _fetchWithTimeout(url, options) {
240
251
  var self = this;
252
+ var timeout = this.config.timeout || 30000;
241
253
  var controller = new AbortController();
242
254
  var timeoutId = setTimeout(function() {
243
255
  controller.abort();
244
- }, this.config.timeout);
256
+ }, timeout);
257
+
258
+ self._log('info', 'Fetch timeout set to:', timeout, 'ms');
245
259
 
246
260
  try {
247
261
  var response = await fetch(url, Object.assign({}, options, {
@@ -252,19 +266,44 @@
252
266
  } catch (error) {
253
267
  clearTimeout(timeoutId);
254
268
 
255
- self._log('error', 'Fetch error:', error.name, error.message);
269
+ // Detaylı hata bilgisi
270
+ self._log('error', 'Fetch error details:', {
271
+ name: error.name,
272
+ message: error.message,
273
+ code: error.code,
274
+ cause: error.cause ? String(error.cause) : undefined
275
+ });
256
276
 
277
+ // AbortError - gerçek timeout mu yoksa başka bir sebep mi?
257
278
  if (error.name === 'AbortError') {
258
- throw new SupsisAPIError('Request timeout after ' + self.config.timeout + 'ms', 408, { originalError: error.message });
279
+ // error.cause varsa gerçek sebebi göster
280
+ var realCause = error.cause ? String(error.cause) : error.message;
281
+ throw new SupsisAPIError('Request aborted: ' + realCause, 408, {
282
+ originalError: error.message,
283
+ cause: realCause,
284
+ timeout: timeout
285
+ });
259
286
  }
260
287
 
261
288
  // Network hataları için daha açıklayıcı hata mesajı
262
- if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND' || error.message.indexOf('fetch') !== -1) {
263
- throw new SupsisAPIError('Network error: ' + error.message, 0, { originalError: error.message, code: error.code });
289
+ if (error.code === 'ECONNREFUSED') {
290
+ throw new SupsisAPIError('Connection refused: ' + url, 0, { originalError: error.message, code: error.code });
291
+ }
292
+
293
+ if (error.code === 'ENOTFOUND') {
294
+ throw new SupsisAPIError('Host not found: ' + url, 0, { originalError: error.message, code: error.code });
295
+ }
296
+
297
+ if (error.code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' || error.code === 'CERT_HAS_EXPIRED' || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') {
298
+ throw new SupsisAPIError('SSL/TLS certificate error: ' + error.message, 0, { originalError: error.message, code: error.code });
264
299
  }
265
300
 
266
301
  // Diğer hatalar için SupsisAPIError'a çevir
267
- throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, { originalError: error.message });
302
+ throw new SupsisAPIError(error.message || 'Unknown fetch error', 0, {
303
+ originalError: error.message,
304
+ code: error.code,
305
+ cause: error.cause ? String(error.cause) : undefined
306
+ });
268
307
  }
269
308
  }
270
309
 
@@ -1,12 +1,12 @@
1
1
  /**
2
- * Supsis JS SDK v1.0.0
2
+ * Supsis JS SDK v1.1.0
3
3
  * Supsis API SDK - Browser ve Node.js için omnichannel messaging, chatbot, automation, task, ticket ve voice agent entegrasyonu
4
4
  *
5
5
  * @license MIT
6
6
  * @author Supsis Ai <info@softcand.com>
7
7
  * @see https://supsis.com
8
8
  */
9
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SupsisJS={})}(this,function(t){"use strict";const e={production:"https://api.supsis.live",stage:"https://beta-api.supsis.live",local:"https://tablet-api-local.supsis.live:50101"},a={env:"production",baseApiAddress:null,timeout:3e4,retryCount:3,retryDelay:1e3,verbose:!1},i=401,s=403,r="1.0.0";class n extends Error{constructor(t,e,a){super(t),this.name="SupsisAPIError",this.statusCode=e,this.response=a}}class d{constructor(t){this.config=Object.assign({},a,t),this.baseUrl=this._resolveBaseUrl(),this.token=null,this.siteId=t.siteId||null,this.verbose=t.verbose||!1}_log(t){if(this.verbose){var e=Array.prototype.slice.call(arguments,1),a="[SupsisJS]",i=(new Date).toISOString();switch(t){case"info":console.log.apply(console,[a,i,"INFO:"].concat(e));break;case"warn":console.warn.apply(console,[a,i,"WARN:"].concat(e));break;case"error":console.error.apply(console,[a,i,"ERROR:"].concat(e));break;case"request":console.log.apply(console,[a,i,"→ REQUEST:"].concat(e));break;case"response":console.log.apply(console,[a,i,"← RESPONSE:"].concat(e));break;default:console.log.apply(console,[a,i].concat(e))}}}_resolveBaseUrl(){return this.config.baseApiAddress?this.config.baseApiAddress.replace(/\/$/,""):e[this.config.env]||e.production}setToken(t){this.token=t}setSiteId(t){this.siteId=t}async request(t,e,a){a=a||{};const r=this._buildUrl(e,a.query),n=this._buildHeaders(a.headers,a.skipAuth),d={method:t.toUpperCase(),headers:n};let o;a.body&&"GET"!==t.toUpperCase()&&(d.body=JSON.stringify(a.body)),this._log("request",t.toUpperCase(),r,a.body?JSON.stringify(a.body).substring(0,200):"");const l=void 0!==a.retryCount?a.retryCount:this.config.retryCount;for(let t=0;t<=l;t++)try{t>0&&this._log("info","Retry attempt",t,"of",l);const a=await this._fetchWithTimeout(r,d),i=await this._handleResponse(a);return this._log("response",a.status,e,"object"==typeof i?JSON.stringify(i).substring(0,200):i),i}catch(e){if(o=e,this._log("error","Request failed:",e.message,"Status:",e.statusCode||"N/A"),e.statusCode===i||e.statusCode===s)throw e;t<l&&(this._log("info","Waiting",this.config.retryDelay*(t+1),"ms before retry..."),await this._sleep(this.config.retryDelay*(t+1)))}throw o}async _fetchWithTimeout(t,e){var a=new AbortController,i=setTimeout(function(){a.abort()},this.config.timeout);try{var s=await fetch(t,Object.assign({},e,{signal:a.signal}));return clearTimeout(i),s}catch(t){if(clearTimeout(i),this._log("error","Fetch error:",t.name,t.message),"AbortError"===t.name)throw new n("Request timeout after "+this.config.timeout+"ms",408,{originalError:t.message});if("ECONNREFUSED"===t.code||"ENOTFOUND"===t.code||-1!==t.message.indexOf("fetch"))throw new n("Network error: "+t.message,0,{originalError:t.message,code:t.code});throw new n(t.message||"Unknown fetch error",0,{originalError:t.message})}}_buildUrl(t,e){let a=this.baseUrl+t;if(e&&Object.keys(e).length>0){const t=new URLSearchParams;Object.keys(e).forEach(function(a){void 0!==e[a]&&null!==e[a]&&t.append(a,e[a])}),a=a+"?"+t.toString()}return a}_buildHeaders(t,e){const a={"Content-Type":"application/json",Accept:"application/json"};return this.siteId&&(a["site-id"]=this.siteId),!e&&this.token&&(a.Authorization="Bearer "+this.token),t&&Object.assign(a,t),a}async _handleResponse(t){let e;try{const a=t.headers.get("content-type");e=a&&-1!==a.indexOf("application/json")?await t.json():await t.text()}catch(t){e=null}if(!t.ok){const a=e&&e.message||e&&e.error||t.statusText||"API Error";throw new n(a,t.status,e)}return e}_sleep(t){return new Promise(function(e){setTimeout(e,t)})}get(t,e){return this.request("GET",t,e)}post(t,e,a){return this.request("POST",t,Object.assign({},a,{body:e}))}put(t,e,a){return this.request("PUT",t,Object.assign({},a,{body:e}))}patch(t,e,a){return this.request("PATCH",t,Object.assign({},a,{body:e}))}delete(t,e){return this.request("DELETE",t,e)}}class o{constructor(t){if(!t)throw new Error("HttpClient is required");this.http=t}_normalizePagination(t){const e=(t=t||{}).page||1,a=t.limit||20;return{page:e,limit:a,offset:void 0!==t.offset?t.offset:(e-1)*a}}_isValidObjectId(t){return!(!t||"string"!=typeof t)&&/^[a-fA-F0-9]{24}$/.test(t)}_validateRequired(t,e){const a=[];if(e.forEach(function(e){void 0!==t[e]&&null!==t[e]||a.push(e)}),a.length>0)throw new Error("Missing required parameters: "+a.join(", "))}_toISODate(t){return t?t instanceof Date?t.toISOString():"number"==typeof t||"string"==typeof t?new Date(t).toISOString():null:null}_cleanObject(t){if(!t||"object"!=typeof t)return t;const e={};return Object.keys(t).forEach(function(a){void 0!==t[a]&&(e[a]=t[a])}),e}}class l extends o{async get(t){return this._validateRequired({chatId:t},["chatId"]),await this.http.get("/api/conversations/"+t)}async getMessages(t,e){return this._validateRequired({chatId:t},["chatId"]),e=e||{},await this.http.get("/api/conversations/"+t+"/messages",{query:this._cleanObject({limit:e.limit,before:e.before})})}async getMessageHistory(t,e){this._validateRequired({chatId:t},["chatId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/conversations/"+t+"/v2-message-history",{query:{page:a.page,limit:a.limit}})}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.get("/api/conversations/history",{query:this._cleanObject({status:t.status,channel:t.channel,userId:t.userId,visitorId:t.visitorId,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})})}async getStats(){return await this.http.get("/api/conversations/conversation-stat-realtime")}async addNote(t,e){return this._validateRequired({chatId:t,note:e},["chatId","note"]),await this.http.post("/api/conversations/"+t+"/note",{note:e})}async updateTags(t,e){return this._validateRequired({chatId:t},["chatId"]),await this.http.post("/api/conversations/"+t+"/tags",{tags:e||[]})}async rate(t,e,a){return this._validateRequired({chatId:t,rating:e},["chatId","rating"]),await this.http.post("/api/conversations/"+t+"/rate",{point:e,description:a})}async sendTranscript(t,e){return this._validateRequired({chatId:t,email:e},["chatId","email"]),await this.http.get("/api/conversations/"+t+"/sendTranscript",{query:{email:e}})}async destroy(t){return this._validateRequired({chatId:t},["chatId"]),await this.http.post("/api/conversations/"+t+"/destroy")}async getByUser(t,e){return this._validateRequired({userId:t},["userId"]),e=e||{},await this.http.get("/api/conversations/user/"+t,{query:this._cleanObject(e)})}async getWhatsAppContactList(t){return t=t||{},await this.http.get("/api/conversations/contact-list/whatsapp",{query:this._cleanObject(t)})}async getContactListByChannel(t,e){return this._validateRequired({channelId:t},["channelId"]),e=e||{},await this.http.get("/api/conversations/contact-list-by-channels",{query:this._cleanObject({channels:t,page:e.page,limit:e.limit})})}async getLastMessages(t){return this._validateRequired({chatIds:t},["chatIds"]),await this.http.post("/api/conversations/last-messages",{conversationIds:t})}async updateField(t,e,a){return this._validateRequired({chatId:t,key:e},["chatId","key"]),await this.http.put("/api/conversations/"+t+"/update-single-key",{key:e,value:a})}}class c extends o{async get(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t)}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/visitors/visitor-list",{page:e.page,limit:e.limit,search:t.search,owner:t.owner,tags:t.tags,channel:t.channel})}async search(t,e){t=t||{},e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/visitors/search",{query:this._cleanObject({email:t.email,phone:t.phone,fullname:t.fullname,query:t.query,page:a.page,limit:a.limit})})}async advancedSearch(t,e,a){e=e||{};const i=this._normalizePagination(e);return await this.http.post("/api/visitors/contacts-by-advanced-filter",{filterGroups:t,cursor:{offset:i.offset,limit:i.limit},projectionFields:a})}async create(t){return this._validateRequired(t,["fullname"]),await this.http.post("/api/visitors/contacts",t)}async update(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/update",e)}async delete(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.delete("/api/visitors/"+t)}async deleteMany(t){return this._validateRequired({contactIds:t},["contactIds"]),await this.http.post("/api/visitors/delete-multi-visitor",{visitorIds:t})}async addTag(t,e){return this._validateRequired({contactId:t,tagId:e},["contactId","tagId"]),await this.http.post("/api/visitors/updateTagVisitor/"+t,{tagId:e,action:"add"})}async removeTag(t,e){return this._validateRequired({contactId:t,tagId:e},["contactId","tagId"]),await this.http.post("/api/visitors/updateTagVisitor/"+t,{tagId:e,action:"remove"})}async block(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/block",{reason:e})}async unblock(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/unblock")}async getChatHistory(t,e){this._validateRequired({contactId:t},["contactId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/visitors/"+t+"/conversations-paged",{query:{page:a.page,limit:a.limit}})}async getNotes(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t+"/notes-v2")}async addNote(t,e){return this._validateRequired({contactId:t,content:e},["contactId","content"]),await this.http.post("/api/visitors/"+t+"/notes-v2",{content:e})}async updateNote(t,e,a){return this._validateRequired({contactId:t,noteId:e,content:a},["contactId","noteId","content"]),await this.http.post("/api/visitors/"+t+"/notes-v2/"+e,{content:a})}async deleteNote(t){return this._validateRequired({noteId:t},["noteId"]),await this.http.delete("/api/visitors/notes-v2/"+t)}async updateProperty(t,e,a){return this._validateRequired({contactId:t,propertyId:e},["contactId","propertyId"]),await this.http.put("/api/visitors/"+t+"/contact-property/"+e,{value:a})}async changeOwner(t,e){return this._validateRequired({contactId:t,ownerId:e},["contactId","ownerId"]),await this.http.post("/api/visitors/"+t+"/update",{owner:e})}async updatePreferredAgents(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/update-preferred-agents",{agents:e||[]})}async getMedia(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t+"/media",{query:this._cleanObject(e)})}async merge(t,e){return this._validateRequired({primaryContactId:t,secondaryContactId:e},["primaryContactId","secondaryContactId"]),await this.http.post("/api/visitors/merge-visitors",{primaryVisitorId:t,secondaryVisitorId:e})}async downloadExcel(t){return await this.http.post("/api/visitors/visitor-list/download",t||{})}}class h extends o{async get(t){return this._validateRequired({messageId:t},["messageId"]),await this.http.post("/api/messages/get-message",{messageId:t})}async list(t,e){return this._validateRequired({conversationId:t},["conversationId"]),e=e||{},await this.http.get("/api/messages/"+t,{query:this._cleanObject({limit:e.limit,before:e.before,after:e.after})})}async search(t){this._validateRequired(t,["query"]);const e=this._normalizePagination(t);return await this.http.post("/api/messages/search-messages",{query:t.query,conversationId:t.conversationId,visitorId:t.visitorId,userId:t.userId,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})}async getMany(t){return this._validateRequired({messageIds:t},["messageIds"]),await this.http.post("/api/messages/get-message",{messageIds:t})}}class p extends o{async get(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.get("/api/tasks/"+t+"/detail")}async list(t,e){return this._validateRequired({workflowId:t},["workflowId"]),(e=e||{}).pipelineId?await this.http.get("/api/tasks/"+t+"/"+e.pipelineId):await this.http.get("/api/tasks/"+t)}async create(t){return this._validateRequired(t,["title","workflowId","pipelineId"]),await this.http.post("/api/tasks",{title:t.title,workflowId:t.workflowId,pipelineId:t.pipelineId,description:t.description,assignee:t.assignee,dueDate:this._toISODate(t.dueDate),priority:t.priority,contactId:t.contactId,customFields:t.customFields})}async createSimple(t){return this._validateRequired(t,["title","workflowId","pipelineId"]),await this.http.post("/api/tasks/simple",t)}async update(t,e){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t,e)}async delete(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.delete("/api/tasks/"+t)}async move(t,e,a){return this._validateRequired({taskId:t,pipelineId:e},["taskId","pipelineId"]),await this.http.patch("/api/tasks/"+t+"/position",{pipelineId:e,position:a})}async complete(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t+"/done")}async archive(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t+"/archive")}async deleteMany(t){return this._validateRequired({taskIds:t},["taskIds"]),await this.http.post("/api/tasks/multiple/delete",{taskIds:t})}async moveMany(t,e){return this._validateRequired({taskIds:t,pipelineId:e},["taskIds","pipelineId"]),await this.http.post("/api/tasks/multiple/change-pipeline",{taskIds:t,pipelineId:e})}async completeMany(t){return this._validateRequired({taskIds:t},["taskIds"]),await this.http.post("/api/tasks/multiple/done",{taskIds:t})}async getActivities(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.get("/api/tasks/get-task-activity/"+t)}async listCompleted(t){return await this.http.get("/api/tasks/done-tasks",{query:this._cleanObject(t)})}async listArchived(t){return await this.http.get("/api/tasks/archive-tasks",{query:this._cleanObject(t)})}async listByDate(t){return this._validateRequired({date:t},["date"]),await this.http.get("/api/tasks/get-event-list-by-date",{query:{date:this._toISODate(t)}})}async listByContact(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/tasks/visitor-tasks",{query:{visitorId:t}})}async listWorkflows(){return await this.http.get("/api/tasks/workflows")}async getWorkflow(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t)}async createWorkflow(t){return this._validateRequired(t,["name"]),await this.http.post("/api/tasks/workflows",t)}async updateWorkflow(t,e){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.patch("/api/tasks/workflows/"+t,e)}async deleteWorkflow(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.delete("/api/tasks/workflows/"+t)}async getWorkflowFull(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/full")}async getWorkflowReports(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/reports")}async listPipelines(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/pipelines")}async createPipeline(t,e){return this._validateRequired({workflowId:t},["workflowId"]),this._validateRequired(e,["name"]),await this.http.post("/api/tasks/workflows/"+t+"/pipelines",e)}async updatePipeline(t,e){return this._validateRequired({pipelineId:t},["pipelineId"]),await this.http.patch("/api/tasks/pipelines/"+t,e)}async deletePipeline(t){return this._validateRequired({pipelineId:t},["pipelineId"]),await this.http.delete("/api/tasks/pipelines/"+t)}async updatePipelinePosition(t,e,a){return this._validateRequired({workflowId:t,pipelineId:e},["workflowId","pipelineId"]),await this.http.patch("/api/tasks/"+t+"/"+e+"/position",{position:a})}}class u extends o{async makeCall(t){return this._validateRequired(t,["agentId","toNumber","fromNumber"]),await this.http.post("/api/voice-agent/calls/phone",{overrideAgentId:t.agentId,toNumber:t.toNumber,fromNumber:t.fromNumber,retellLlmDynamicVariables:t.variables||{},metadata:t.metadata})}async makeWebCall(t){return this._validateRequired(t,["agentId"]),await this.http.post("/api/voice-agent/calls/web",{agentId:t.agentId,retellLlmDynamicVariables:t.variables||{}})}async makeBatchCall(t){return this._validateRequired(t,["agentId","fromNumber","calls"]),await this.http.post("/api/voice-agent/calls/batch",t)}async getCall(t){return this._validateRequired({callId:t},["callId"]),await this.http.get("/api/voice-agent/calls/"+t)}async listCalls(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/voice-agent/calls/list",{agentId:t.agentId,status:t.status,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})}async listBatchCalls(){return await this.http.get("/api/voice-agent/calls/batch")}async listAgents(){return await this.http.get("/api/voice-agent/agents")}async getAgent(t){return this._validateRequired({agentId:t},["agentId"]),await this.http.get("/api/voice-agent/agents/"+t)}async createAgent(t){return this._validateRequired(t,["name"]),await this.http.post("/api/voice-agent/agents",t)}async updateAgent(t,e){return this._validateRequired({agentId:t},["agentId"]),await this.http.patch("/api/voice-agent/agents/"+t,e)}async deleteAgent(t){return this._validateRequired({agentId:t},["agentId"]),await this.http.delete("/api/voice-agent/agents/"+t)}async listNumbers(){return await this.http.get("/api/voice-agent/numbers")}async getNumber(t){return this._validateRequired({phoneNumber:t},["phoneNumber"]),await this.http.get("/api/voice-agent/numbers/"+encodeURIComponent(t))}async listVoices(){return await this.http.get("/api/voice-agent/voices")}async getVoice(t){return this._validateRequired({voiceId:t},["voiceId"]),await this.http.get("/api/voice-agent/voices/"+t)}async listKnowledgeBases(){return await this.http.get("/api/voice-agent/knowledgebases")}async getKnowledgeBase(t){return this._validateRequired({knowledgeBaseId:t},["knowledgeBaseId"]),await this.http.get("/api/voice-agent/knowledgebases/"+t)}async deleteKnowledgeBase(t){return this._validateRequired({knowledgeBaseId:t},["knowledgeBaseId"]),await this.http.delete("/api/voice-agent/knowledgebases/"+t)}async listLLMs(){return await this.http.get("/api/voice-agent/llms")}async getLLM(t){return this._validateRequired({llmId:t},["llmId"]),await this.http.get("/api/voice-agent/llms/"+t)}async createLLM(t){return await this.http.post("/api/voice-agent/llms",t)}async updateLLM(t,e){return this._validateRequired({llmId:t},["llmId"]),await this.http.patch("/api/voice-agent/llms/"+t,e)}async deleteLLM(t){return this._validateRequired({llmId:t},["llmId"]),await this.http.delete("/api/voice-agent/llms/"+t)}}class g extends o{async get(t){return this._validateRequired({assetId:t},["assetId"]),await this.http.get("/api/assets/id/"+t)}getUrl(t){return t?"https://supsis-storage.s3.amazonaws.com/"+t:null}}class w extends o{async list(){return await this.http.get("/api/tables")}async get(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t)}async create(t){return this._validateRequired(t,["name"]),await this.http.put("/api/tables",t)}async update(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.post("/api/tables/"+t,e)}async delete(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.delete("/api/tables/"+t)}async duplicate(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.post("/api/tables/"+t+"/duplicate")}async export(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/export")}async import(t){return await this.http.post("/api/tables/import",t)}async listFields(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/fields")}async createField(t,e){return this._validateRequired({tableId:t},["tableId"]),this._validateRequired(e,["name","type"]),await this.http.put("/api/tables/"+t+"/fields",e)}async updateField(t,e,a){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.post("/api/tables/"+t+"/fields/"+e,a)}async deleteField(t,e){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.delete("/api/tables/"+t+"/fields/"+e)}async listRecords(t,e){this._validateRequired({tableId:t},["tableId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.post("/api/tables/"+t+"/records",{filters:e.filters,sort:e.sort,page:a.page,limit:a.limit,viewId:e.viewId})}async getRecord(t,e){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.get("/api/tables/"+t+"/records/"+e)}async createRecord(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/records",e)}async createEmptyRecord(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/records/empty")}async createManyRecords(t,e){return this._validateRequired({tableId:t,records:e},["tableId","records"]),await this.http.put("/api/tables/"+t+"/records/multi",{records:e})}async updateRecord(t,e,a){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.post("/api/tables/"+t+"/records/"+e+"/update",a)}async updateManyRecords(t,e,a,i){return this._validateRequired({tableId:t,fieldId:e,recordIds:a},["tableId","fieldId","recordIds"]),await this.http.put("/api/tables/"+t+"/fields/"+e+"/records",{recordIds:a,value:i})}async deleteRecord(t,e){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.delete("/api/tables/"+t+"/records/"+e)}async deleteManyRecords(t,e){return this._validateRequired({tableId:t,recordIds:e},["tableId","recordIds"]),await this.http.post("/api/tables/"+t+"/records/delete",{recordIds:e})}async duplicateRecords(t,e){return this._validateRequired({tableId:t,recordIds:e},["tableId","recordIds"]),await this.http.post("/api/tables/"+t+"/records/duplicate",{recordIds:e})}async searchFieldValues(t,e,a){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.get("/api/tables/"+t+"/"+e+"/search",{query:{q:a}})}async listViews(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/views")}async createView(t,e){return this._validateRequired({tableId:t},["tableId"]),this._validateRequired(e,["name"]),await this.http.put("/api/tables/"+t+"/views",e)}async updateView(t,e,a){return this._validateRequired({tableId:t,viewId:e},["tableId","viewId"]),await this.http.post("/api/tables/"+t+"/views/"+e,a)}async deleteView(t,e){return this._validateRequired({tableId:t,viewId:e},["tableId","viewId"]),await this.http.delete("/api/tables/"+t+"/views/"+e)}async listPages(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/pages")}async getPage(t,e){return this._validateRequired({tableId:t,pageId:e},["tableId","pageId"]),await this.http.get("/api/tables/"+t+"/pages/"+e)}async createPage(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/pages",e)}async listWidgets(t,e){return this._validateRequired({tableId:t,pageId:e},["tableId","pageId"]),await this.http.get("/api/tables/"+t+"/pages/"+e+"/widgets")}async getWidgetChartData(t,e,a){return this._validateRequired({tableId:t,widgetId:e},["tableId","widgetId"]),await this.http.post("/api/tables/"+t+"/widgets/"+e+"/chart-data",a||{})}}class I extends o{async list(){return await this.http.get("/api/module")}async create(t){return this._validateRequired(t,["name","displayName"]),await this.http.post("/api/module",t)}async update(t,e){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.post("/api/module/"+t,e)}async delete(t){return this._validateRequired({moduleId:t},["moduleId"]),await this.http.delete("/api/module/"+t)}async listRecords(t,e){this._validateRequired({moduleName:t},["moduleName"]),e=e||{};const a=this._normalizePagination(e);return await this.http.post("/api/module/"+t+"/records",{filters:e.filters,sort:e.sort,page:a.page,limit:a.limit})}async listAllRecords(t){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.get("/api/module/"+t+"/records")}async searchRecords(t,e){return this._validateRequired({moduleName:t,query:e},["moduleName","query"]),await this.http.get("/api/module/"+t+"/records/search",{query:{q:e}})}async getRecord(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.get("/api/module/"+t+"/records/"+e)}async createRecord(t,e){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.put("/api/module/"+t+"/records",e)}async createManyRecords(t,e){return this._validateRequired({moduleName:t,records:e},["moduleName","records"]),await this.http.put("/api/module/"+t+"/records/multi",{records:e})}async updateRecord(t,e,a){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.put("/api/module/"+t+"/records/"+e,a)}async deleteRecord(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.delete("/api/module/"+t+"/records/"+e)}async listContactRelatedRecords(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/module/records/contact-related-list",{query:{contactId:t}})}async listModuleRelatedRecords(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.get("/api/module/records/module-related-list",{query:{moduleName:t,recordId:e}})}}class y extends o{async me(){return await this.http.get("/api/users/me")}async updateMe(t){return await this.http.put("/api/users/me",t)}async get(t){return this._validateRequired({userId:t},["userId"]),await this.http.get("/api/users/user/"+t)}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.get("/api/users/pagination",{query:this._cleanObject({page:e.page,limit:e.limit,status:t.status})})}async listOnline(){return await this.http.get("/api/users/list-online-users")}async create(t){return this._validateRequired(t,["fullname","email","password"]),await this.http.post("/api/users",t)}async update(t,e){return this._validateRequired({userId:t},["userId"]),await this.http.put("/api/users/"+t,e)}async delete(t){return this._validateRequired({userId:t},["userId"]),await this.http.delete("/api/users/"+t)}async updatePassword(t,e){return this._validateRequired({userId:t,newPassword:e},["userId","newPassword"]),await this.http.put("/api/users/"+t+"/updatePassword",{password:e})}async updateOnlineStatus(t,e){return this._validateRequired({userId:t},["userId"]),await this.http.put("/api/users/"+t+"/onlineStatus",{isOnline:e})}async updateStatus(t,e){return this._validateRequired({userId:t,status:e},["userId","status"]),await this.http.put("/api/users/"+t+"/status",{status:e})}async getActiveCount(){return await this.http.get("/api/users/active-user-count")}async getNotificationSettings(){return await this.http.get("/api/users/me/notification-settings")}async completeTutorial(t){return this._validateRequired({tutorialKey:t},["tutorialKey"]),await this.http.post("/api/users/me/setup-guide/"+t)}async logout(){return await this.http.get("/api/users/logout")}}class v extends o{async list(t){const e=t?"/api/tags/"+t:"/api/tags";return await this.http.get(e)}async create(t){return this._validateRequired(t,["name"]),await this.http.post("/api/tags",t)}async update(t){return this._validateRequired(t,["_id"]),await this.http.patch("/api/tags",t)}async delete(t){return this._validateRequired({tagId:t},["tagId"]),await this.http.delete("/api/tags/"+t)}}class _ extends o{async getCurrentPlan(){return await this.http.get("/api/sites/current-plan")}async getFeatures(){return await this.http.get("/api/sites/features")}async getWallet(){return await this.http.get("/api/sites/wallet")}async getWalletActivities(t){return t=t||{},await this.http.get("/api/sites/wallet/activities",{query:this._cleanObject({walletType:t.walletType,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate)})})}async depositWallet(t,e){return this._validateRequired({walletType:t,amount:e},["walletType","amount"]),await this.http.post("/api/sites/wallet/"+t,{amount:e})}async getAutoRebalanceSettings(t){return this._validateRequired({walletType:t},["walletType"]),await this.http.get("/api/sites/wallet/"+t+"/auto-rebalance")}async updateAutoRebalanceSettings(t,e){return this._validateRequired({walletType:t},["walletType"]),await this.http.put("/api/sites/wallet/"+t+"/auto-rebalance",e)}async getConversationUsage(){return await this.http.get("/api/sites/conversation-usages")}async getStorageUsage(t){return await this.http.post("/api/sites/storage-usages",t||{})}async checkIntegrationStatus(t){return await this.http.post("/api/public/sites/check-integration-status",t||{})}}class m extends o{async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/cache/list",{pattern:t.pattern,type:t.type,actorType:t.actorType,page:e.page,limit:e.limit})}async write(t,e,a){this._validateRequired({key:t},["key"]);const i={key:t,value:e,type:(a=a||{}).type||"public",dataType:a.dataType||"mixed"};if(a.expiresIn){const t=new Date,e={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5,months:2592e6},s=a.expiresIn.value*(e[a.expiresIn.unit]||e.hours);i.expiresAt=new Date(t.getTime()+s).toISOString()}else a.expiresAt&&(i.expiresAt=this._toISODate(a.expiresAt));return await this.http.post("/api/cache/write",i)}async read(t,e){this._validateRequired({key:t},["key"]);try{const a=await this.http.post("/api/cache/list",{pattern:t,limit:1});return a&&a.data&&a.data.length>0?a.data[0].value:void 0!==e?e:null}catch(t){return void 0!==e?e:null}}async update(t,e){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.post("/api/cache/"+t+"/update",{value:e})}async extend(t,e){this._validateRequired({cacheId:t,expiresIn:e},["cacheId","expiresIn"]);const a={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5,months:2592e6},i=new Date,s=e.value*(a[e.unit]||a.hours),r=new Date(i.getTime()+s);return await this.http.post("/api/cache/"+t+"/extend",{expiresAt:r.toISOString()})}async makeNeverExpire(t){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.post("/api/cache/"+t+"/never-expire")}async delete(t){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.delete("/api/cache/"+t)}async deleteMany(t){return this._validateRequired({cacheIds:t},["cacheIds"]),await this.http.post("/api/cache/bulk-delete",{cacheIds:t})}async deleteByActor(t,e){return this._validateRequired({actorType:t,actorId:e},["actorType","actorId"]),await this.http.post("/api/cache/delete-by-actor",{actorType:t,actorId:e})}async deleteByPattern(t){return this._validateRequired({pattern:t},["pattern"]),await this.http.post("/api/cache/delete-by-pattern",{pattern:t})}}class b{constructor(t){if(!t)throw new Error("Config is required");this._validateConfig(t),this._config=t,this._verbose=t.verbose||!1,this._http=new d({env:t.env||"production",baseApiAddress:t.baseApiAddress,siteId:t.siteId,timeout:t.timeout,retryCount:t.retryCount,verbose:t.verbose}),this._connected=!1,this._token=null,this._user=null,this._initModules(),this._log("info","SupsisJS initialized",{env:t.env||"production",baseApiAddress:t.baseApiAddress||"default",siteId:t.siteId})}_log(t){if(this._verbose){var e=Array.prototype.slice.call(arguments,1),a="[SupsisJS]",i=(new Date).toISOString();switch(t){case"info":console.log.apply(console,[a,i,"INFO:"].concat(e));break;case"warn":console.warn.apply(console,[a,i,"WARN:"].concat(e));break;case"error":console.error.apply(console,[a,i,"ERROR:"].concat(e));break;default:console.log.apply(console,[a,i].concat(e))}}}_validateConfig(t){if(!t.email)throw new Error("email is required");if(!t.password)throw new Error("password is required");if(!t.siteId)throw new Error("siteId is required")}_initModules(){this.chat=new l(this._http),this.contact=new c(this._http),this.message=new h(this._http),this.task=new p(this._http),this.aicall=new u(this._http),this.asset=new g(this._http),this.table=new w(this._http),this.module=new I(this._http),this.user=new y(this._http),this.tag=new v(this._http),this.site=new _(this._http),this.cache=new m(this._http)}async connect(){var t;if(this._connected)return this._log("info","Already connected"),this._user;this._log("info","Connecting to Supsis API..."),this._log("info","Base URL:",this._http.baseUrl);try{t=await this._http.post("/api/users/login",{email:this._config.email,password:this._config.password},{skipAuth:!0,retryCount:0})}catch(t){throw this._log("error","Login failed:",t.message),t}if(!t||!t.token){var e="Login failed: No token received";throw t&&t.message&&(e="Login failed: "+t.message),this._log("error",e),new n(e,401,t)}return this._token=t.token,this._user=t.user||t,this._http.setToken(this._token),this._connected=!0,this._log("info","Connected successfully as:",this._user.fullname||this._user.email),this._user}async disconnect(){if(this._connected){try{await this._http.get("/api/users/logout")}catch(t){}this._token=null,this._user=null,this._http.setToken(null),this._connected=!1}}get isConnected(){return this._connected}get currentUser(){return this._user}get token(){return this._token}get version(){return r}get http(){return this._http}setToken(t){this._token=t,this._http.setToken(t),this._connected=!0}}
9
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SupsisJS={})}(this,function(t){"use strict";const e={production:"https://api.supsis.live",stage:"https://beta-api.supsis.live",local:"https://tablet-api-local.supsis.live:50101"},a={env:"production",baseApiAddress:null,timeout:3e4,retryCount:3,retryDelay:1e3,verbose:!1},i=401,s=403,r="1.0.0";class n extends Error{constructor(t,e,a){super(t),this.name="SupsisAPIError",this.statusCode=e,this.response=a}}class d{constructor(t){t=t||{},this.config=Object.assign({},a,t),this.baseUrl=this._resolveBaseUrl(),this.token=null,this.siteId=this.config.siteId||null,this.verbose=this.config.verbose||!1,this.verbose&&console.log("[SupsisJS] HttpClient config:",{timeout:this.config.timeout,retryCount:this.config.retryCount,env:this.config.env,baseUrl:this.baseUrl})}_log(t){if(this.verbose){var e=Array.prototype.slice.call(arguments,1),a="[SupsisJS]",i=(new Date).toISOString();switch(t){case"info":console.log.apply(console,[a,i,"INFO:"].concat(e));break;case"warn":console.warn.apply(console,[a,i,"WARN:"].concat(e));break;case"error":console.error.apply(console,[a,i,"ERROR:"].concat(e));break;case"request":console.log.apply(console,[a,i,"→ REQUEST:"].concat(e));break;case"response":console.log.apply(console,[a,i,"← RESPONSE:"].concat(e));break;default:console.log.apply(console,[a,i].concat(e))}}}_resolveBaseUrl(){return this.config.baseApiAddress?this.config.baseApiAddress.replace(/\/$/,""):e[this.config.env]||e.production}setToken(t){this.token=t}setSiteId(t){this.siteId=t}async request(t,e,a){a=a||{};const r=this._buildUrl(e,a.query),n=this._buildHeaders(a.headers,a.skipAuth),d={method:t.toUpperCase(),headers:n};let o;a.body&&"GET"!==t.toUpperCase()&&(d.body=JSON.stringify(a.body)),this._log("request",t.toUpperCase(),r,a.body?JSON.stringify(a.body).substring(0,200):"");const l=void 0!==a.retryCount?a.retryCount:this.config.retryCount;for(let t=0;t<=l;t++)try{t>0&&this._log("info","Retry attempt",t,"of",l);const a=await this._fetchWithTimeout(r,d),i=await this._handleResponse(a);return this._log("response",a.status,e,"object"==typeof i?JSON.stringify(i).substring(0,200):i),i}catch(e){if(o=e,this._log("error","Request failed:",e.message,"Status:",e.statusCode||"N/A"),e.statusCode===i||e.statusCode===s)throw e;t<l&&(this._log("info","Waiting",this.config.retryDelay*(t+1),"ms before retry..."),await this._sleep(this.config.retryDelay*(t+1)))}throw o}async _fetchWithTimeout(t,e){var a=this.config.timeout||3e4,i=new AbortController,s=setTimeout(function(){i.abort()},a);this._log("info","Fetch timeout set to:",a,"ms");try{var r=await fetch(t,Object.assign({},e,{signal:i.signal}));return clearTimeout(s),r}catch(e){if(clearTimeout(s),this._log("error","Fetch error details:",{name:e.name,message:e.message,code:e.code,cause:e.cause?String(e.cause):void 0}),"AbortError"===e.name){var d=e.cause?String(e.cause):e.message;throw new n("Request aborted: "+d,408,{originalError:e.message,cause:d,timeout:a})}if("ECONNREFUSED"===e.code)throw new n("Connection refused: "+t,0,{originalError:e.message,code:e.code});if("ENOTFOUND"===e.code)throw new n("Host not found: "+t,0,{originalError:e.message,code:e.code});if("UNABLE_TO_VERIFY_LEAF_SIGNATURE"===e.code||"CERT_HAS_EXPIRED"===e.code||"DEPTH_ZERO_SELF_SIGNED_CERT"===e.code)throw new n("SSL/TLS certificate error: "+e.message,0,{originalError:e.message,code:e.code});throw new n(e.message||"Unknown fetch error",0,{originalError:e.message,code:e.code,cause:e.cause?String(e.cause):void 0})}}_buildUrl(t,e){let a=this.baseUrl+t;if(e&&Object.keys(e).length>0){const t=new URLSearchParams;Object.keys(e).forEach(function(a){void 0!==e[a]&&null!==e[a]&&t.append(a,e[a])}),a=a+"?"+t.toString()}return a}_buildHeaders(t,e){const a={"Content-Type":"application/json",Accept:"application/json"};return this.siteId&&(a["site-id"]=this.siteId),!e&&this.token&&(a.Authorization="Bearer "+this.token),t&&Object.assign(a,t),a}async _handleResponse(t){let e;try{const a=t.headers.get("content-type");e=a&&-1!==a.indexOf("application/json")?await t.json():await t.text()}catch(t){e=null}if(!t.ok){const a=e&&e.message||e&&e.error||t.statusText||"API Error";throw new n(a,t.status,e)}return e}_sleep(t){return new Promise(function(e){setTimeout(e,t)})}get(t,e){return this.request("GET",t,e)}post(t,e,a){return this.request("POST",t,Object.assign({},a,{body:e}))}put(t,e,a){return this.request("PUT",t,Object.assign({},a,{body:e}))}patch(t,e,a){return this.request("PATCH",t,Object.assign({},a,{body:e}))}delete(t,e){return this.request("DELETE",t,e)}}class o{constructor(t){if(!t)throw new Error("HttpClient is required");this.http=t}_normalizePagination(t){const e=(t=t||{}).page||1,a=t.limit||20;return{page:e,limit:a,offset:void 0!==t.offset?t.offset:(e-1)*a}}_isValidObjectId(t){return!(!t||"string"!=typeof t)&&/^[a-fA-F0-9]{24}$/.test(t)}_validateRequired(t,e){const a=[];if(e.forEach(function(e){void 0!==t[e]&&null!==t[e]||a.push(e)}),a.length>0)throw new Error("Missing required parameters: "+a.join(", "))}_toISODate(t){return t?t instanceof Date?t.toISOString():"number"==typeof t||"string"==typeof t?new Date(t).toISOString():null:null}_cleanObject(t){if(!t||"object"!=typeof t)return t;const e={};return Object.keys(t).forEach(function(a){void 0!==t[a]&&(e[a]=t[a])}),e}}class l extends o{async get(t){return this._validateRequired({chatId:t},["chatId"]),await this.http.get("/api/conversations/"+t)}async getMessages(t,e){return this._validateRequired({chatId:t},["chatId"]),e=e||{},await this.http.get("/api/conversations/"+t+"/messages",{query:this._cleanObject({limit:e.limit,before:e.before})})}async getMessageHistory(t,e){this._validateRequired({chatId:t},["chatId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/conversations/"+t+"/v2-message-history",{query:{page:a.page,limit:a.limit}})}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.get("/api/conversations/history",{query:this._cleanObject({status:t.status,channel:t.channel,userId:t.userId,visitorId:t.visitorId,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})})}async getStats(){return await this.http.get("/api/conversations/conversation-stat-realtime")}async addNote(t,e){return this._validateRequired({chatId:t,note:e},["chatId","note"]),await this.http.post("/api/conversations/"+t+"/note",{note:e})}async updateTags(t,e){return this._validateRequired({chatId:t},["chatId"]),await this.http.post("/api/conversations/"+t+"/tags",{tags:e||[]})}async rate(t,e,a){return this._validateRequired({chatId:t,rating:e},["chatId","rating"]),await this.http.post("/api/conversations/"+t+"/rate",{point:e,description:a})}async sendTranscript(t,e){return this._validateRequired({chatId:t,email:e},["chatId","email"]),await this.http.get("/api/conversations/"+t+"/sendTranscript",{query:{email:e}})}async destroy(t){return this._validateRequired({chatId:t},["chatId"]),await this.http.post("/api/conversations/"+t+"/destroy")}async getByUser(t,e){return this._validateRequired({userId:t},["userId"]),e=e||{},await this.http.get("/api/conversations/user/"+t,{query:this._cleanObject(e)})}async getWhatsAppContactList(t){return t=t||{},await this.http.get("/api/conversations/contact-list/whatsapp",{query:this._cleanObject(t)})}async getContactListByChannel(t,e){return this._validateRequired({channelId:t},["channelId"]),e=e||{},await this.http.get("/api/conversations/contact-list-by-channels",{query:this._cleanObject({channels:t,page:e.page,limit:e.limit})})}async getLastMessages(t){return this._validateRequired({chatIds:t},["chatIds"]),await this.http.post("/api/conversations/last-messages",{conversationIds:t})}async updateField(t,e,a){return this._validateRequired({chatId:t,key:e},["chatId","key"]),await this.http.put("/api/conversations/"+t+"/update-single-key",{key:e,value:a})}}class c extends o{async get(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t)}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/visitors/visitor-list",{page:e.page,limit:e.limit,search:t.search,owner:t.owner,tags:t.tags,channel:t.channel})}async search(t,e){t=t||{},e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/visitors/search",{query:this._cleanObject({email:t.email,phone:t.phone,fullname:t.fullname,query:t.query,page:a.page,limit:a.limit})})}async advancedSearch(t,e,a){e=e||{};const i=this._normalizePagination(e);return await this.http.post("/api/visitors/contacts-by-advanced-filter",{filterGroups:t,cursor:{offset:i.offset,limit:i.limit},projectionFields:a})}async create(t){return this._validateRequired(t,["fullname"]),await this.http.post("/api/visitors/contacts",t)}async update(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/update",e)}async delete(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.delete("/api/visitors/"+t)}async deleteMany(t){return this._validateRequired({contactIds:t},["contactIds"]),await this.http.post("/api/visitors/delete-multi-visitor",{visitorIds:t})}async addTag(t,e){return this._validateRequired({contactId:t,tagId:e},["contactId","tagId"]),await this.http.post("/api/visitors/updateTagVisitor/"+t,{tagId:e,action:"add"})}async removeTag(t,e){return this._validateRequired({contactId:t,tagId:e},["contactId","tagId"]),await this.http.post("/api/visitors/updateTagVisitor/"+t,{tagId:e,action:"remove"})}async block(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/block",{reason:e})}async unblock(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/unblock")}async getChatHistory(t,e){this._validateRequired({contactId:t},["contactId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.get("/api/visitors/"+t+"/conversations-paged",{query:{page:a.page,limit:a.limit}})}async getNotes(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t+"/notes-v2")}async addNote(t,e){return this._validateRequired({contactId:t,content:e},["contactId","content"]),await this.http.post("/api/visitors/"+t+"/notes-v2",{content:e})}async updateNote(t,e,a){return this._validateRequired({contactId:t,noteId:e,content:a},["contactId","noteId","content"]),await this.http.post("/api/visitors/"+t+"/notes-v2/"+e,{content:a})}async deleteNote(t){return this._validateRequired({noteId:t},["noteId"]),await this.http.delete("/api/visitors/notes-v2/"+t)}async updateProperty(t,e,a){return this._validateRequired({contactId:t,propertyId:e},["contactId","propertyId"]),await this.http.put("/api/visitors/"+t+"/contact-property/"+e,{value:a})}async changeOwner(t,e){return this._validateRequired({contactId:t,ownerId:e},["contactId","ownerId"]),await this.http.post("/api/visitors/"+t+"/update",{owner:e})}async updatePreferredAgents(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.post("/api/visitors/"+t+"/update-preferred-agents",{agents:e||[]})}async getMedia(t,e){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/visitors/"+t+"/media",{query:this._cleanObject(e)})}async merge(t,e){return this._validateRequired({primaryContactId:t,secondaryContactId:e},["primaryContactId","secondaryContactId"]),await this.http.post("/api/visitors/merge-visitors",{primaryVisitorId:t,secondaryVisitorId:e})}async downloadExcel(t){return await this.http.post("/api/visitors/visitor-list/download",t||{})}}class h extends o{async get(t){return this._validateRequired({messageId:t},["messageId"]),await this.http.post("/api/messages/get-message",{messageId:t})}async list(t,e){return this._validateRequired({conversationId:t},["conversationId"]),e=e||{},await this.http.get("/api/messages/"+t,{query:this._cleanObject({limit:e.limit,before:e.before,after:e.after})})}async search(t){this._validateRequired(t,["query"]);const e=this._normalizePagination(t);return await this.http.post("/api/messages/search-messages",{query:t.query,conversationId:t.conversationId,visitorId:t.visitorId,userId:t.userId,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})}async getMany(t){return this._validateRequired({messageIds:t},["messageIds"]),await this.http.post("/api/messages/get-message",{messageIds:t})}}class p extends o{async get(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.get("/api/tasks/"+t+"/detail")}async list(t,e){return this._validateRequired({workflowId:t},["workflowId"]),(e=e||{}).pipelineId?await this.http.get("/api/tasks/"+t+"/"+e.pipelineId):await this.http.get("/api/tasks/"+t)}async create(t){return this._validateRequired(t,["title","workflowId","pipelineId"]),await this.http.post("/api/tasks",{title:t.title,workflowId:t.workflowId,pipelineId:t.pipelineId,description:t.description,assignee:t.assignee,dueDate:this._toISODate(t.dueDate),priority:t.priority,contactId:t.contactId,customFields:t.customFields})}async createSimple(t){return this._validateRequired(t,["title","workflowId","pipelineId"]),await this.http.post("/api/tasks/simple",t)}async update(t,e){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t,e)}async delete(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.delete("/api/tasks/"+t)}async move(t,e,a){return this._validateRequired({taskId:t,pipelineId:e},["taskId","pipelineId"]),await this.http.patch("/api/tasks/"+t+"/position",{pipelineId:e,position:a})}async complete(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t+"/done")}async archive(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.patch("/api/tasks/"+t+"/archive")}async deleteMany(t){return this._validateRequired({taskIds:t},["taskIds"]),await this.http.post("/api/tasks/multiple/delete",{taskIds:t})}async moveMany(t,e){return this._validateRequired({taskIds:t,pipelineId:e},["taskIds","pipelineId"]),await this.http.post("/api/tasks/multiple/change-pipeline",{taskIds:t,pipelineId:e})}async completeMany(t){return this._validateRequired({taskIds:t},["taskIds"]),await this.http.post("/api/tasks/multiple/done",{taskIds:t})}async getActivities(t){return this._validateRequired({taskId:t},["taskId"]),await this.http.get("/api/tasks/get-task-activity/"+t)}async listCompleted(t){return await this.http.get("/api/tasks/done-tasks",{query:this._cleanObject(t)})}async listArchived(t){return await this.http.get("/api/tasks/archive-tasks",{query:this._cleanObject(t)})}async listByDate(t){return this._validateRequired({date:t},["date"]),await this.http.get("/api/tasks/get-event-list-by-date",{query:{date:this._toISODate(t)}})}async listByContact(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/tasks/visitor-tasks",{query:{visitorId:t}})}async listWorkflows(){return await this.http.get("/api/tasks/workflows")}async getWorkflow(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t)}async createWorkflow(t){return this._validateRequired(t,["name"]),await this.http.post("/api/tasks/workflows",t)}async updateWorkflow(t,e){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.patch("/api/tasks/workflows/"+t,e)}async deleteWorkflow(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.delete("/api/tasks/workflows/"+t)}async getWorkflowFull(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/full")}async getWorkflowReports(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/reports")}async listPipelines(t){return this._validateRequired({workflowId:t},["workflowId"]),await this.http.get("/api/tasks/workflows/"+t+"/pipelines")}async createPipeline(t,e){return this._validateRequired({workflowId:t},["workflowId"]),this._validateRequired(e,["name"]),await this.http.post("/api/tasks/workflows/"+t+"/pipelines",e)}async updatePipeline(t,e){return this._validateRequired({pipelineId:t},["pipelineId"]),await this.http.patch("/api/tasks/pipelines/"+t,e)}async deletePipeline(t){return this._validateRequired({pipelineId:t},["pipelineId"]),await this.http.delete("/api/tasks/pipelines/"+t)}async updatePipelinePosition(t,e,a){return this._validateRequired({workflowId:t,pipelineId:e},["workflowId","pipelineId"]),await this.http.patch("/api/tasks/"+t+"/"+e+"/position",{position:a})}}class u extends o{async makeCall(t){return this._validateRequired(t,["agentId","toNumber","fromNumber"]),await this.http.post("/api/voice-agent/calls/phone",{overrideAgentId:t.agentId,toNumber:t.toNumber,fromNumber:t.fromNumber,retellLlmDynamicVariables:t.variables||{},metadata:t.metadata})}async makeWebCall(t){return this._validateRequired(t,["agentId"]),await this.http.post("/api/voice-agent/calls/web",{agentId:t.agentId,retellLlmDynamicVariables:t.variables||{}})}async makeBatchCall(t){return this._validateRequired(t,["agentId","fromNumber","calls"]),await this.http.post("/api/voice-agent/calls/batch",t)}async getCall(t){return this._validateRequired({callId:t},["callId"]),await this.http.get("/api/voice-agent/calls/"+t)}async listCalls(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/voice-agent/calls/list",{agentId:t.agentId,status:t.status,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate),page:e.page,limit:e.limit})}async listBatchCalls(){return await this.http.get("/api/voice-agent/calls/batch")}async listAgents(){return await this.http.get("/api/voice-agent/agents")}async getAgent(t){return this._validateRequired({agentId:t},["agentId"]),await this.http.get("/api/voice-agent/agents/"+t)}async createAgent(t){return this._validateRequired(t,["name"]),await this.http.post("/api/voice-agent/agents",t)}async updateAgent(t,e){return this._validateRequired({agentId:t},["agentId"]),await this.http.patch("/api/voice-agent/agents/"+t,e)}async deleteAgent(t){return this._validateRequired({agentId:t},["agentId"]),await this.http.delete("/api/voice-agent/agents/"+t)}async listNumbers(){return await this.http.get("/api/voice-agent/numbers")}async getNumber(t){return this._validateRequired({phoneNumber:t},["phoneNumber"]),await this.http.get("/api/voice-agent/numbers/"+encodeURIComponent(t))}async listVoices(){return await this.http.get("/api/voice-agent/voices")}async getVoice(t){return this._validateRequired({voiceId:t},["voiceId"]),await this.http.get("/api/voice-agent/voices/"+t)}async listKnowledgeBases(){return await this.http.get("/api/voice-agent/knowledgebases")}async getKnowledgeBase(t){return this._validateRequired({knowledgeBaseId:t},["knowledgeBaseId"]),await this.http.get("/api/voice-agent/knowledgebases/"+t)}async deleteKnowledgeBase(t){return this._validateRequired({knowledgeBaseId:t},["knowledgeBaseId"]),await this.http.delete("/api/voice-agent/knowledgebases/"+t)}async listLLMs(){return await this.http.get("/api/voice-agent/llms")}async getLLM(t){return this._validateRequired({llmId:t},["llmId"]),await this.http.get("/api/voice-agent/llms/"+t)}async createLLM(t){return await this.http.post("/api/voice-agent/llms",t)}async updateLLM(t,e){return this._validateRequired({llmId:t},["llmId"]),await this.http.patch("/api/voice-agent/llms/"+t,e)}async deleteLLM(t){return this._validateRequired({llmId:t},["llmId"]),await this.http.delete("/api/voice-agent/llms/"+t)}}class g extends o{async get(t){return this._validateRequired({assetId:t},["assetId"]),await this.http.get("/api/assets/id/"+t)}getUrl(t){return t?"https://supsis-storage.s3.amazonaws.com/"+t:null}}class w extends o{async list(){return await this.http.get("/api/tables")}async get(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t)}async create(t){return this._validateRequired(t,["name"]),await this.http.put("/api/tables",t)}async update(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.post("/api/tables/"+t,e)}async delete(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.delete("/api/tables/"+t)}async duplicate(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.post("/api/tables/"+t+"/duplicate")}async export(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/export")}async import(t){return await this.http.post("/api/tables/import",t)}async listFields(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/fields")}async createField(t,e){return this._validateRequired({tableId:t},["tableId"]),this._validateRequired(e,["name","type"]),await this.http.put("/api/tables/"+t+"/fields",e)}async updateField(t,e,a){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.post("/api/tables/"+t+"/fields/"+e,a)}async deleteField(t,e){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.delete("/api/tables/"+t+"/fields/"+e)}async listRecords(t,e){this._validateRequired({tableId:t},["tableId"]),e=e||{};const a=this._normalizePagination(e);return await this.http.post("/api/tables/"+t+"/records",{filters:e.filters,sort:e.sort,page:a.page,limit:a.limit,viewId:e.viewId})}async getRecord(t,e){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.get("/api/tables/"+t+"/records/"+e)}async createRecord(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/records",e)}async createEmptyRecord(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/records/empty")}async createManyRecords(t,e){return this._validateRequired({tableId:t,records:e},["tableId","records"]),await this.http.put("/api/tables/"+t+"/records/multi",{records:e})}async updateRecord(t,e,a){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.post("/api/tables/"+t+"/records/"+e+"/update",a)}async updateManyRecords(t,e,a,i){return this._validateRequired({tableId:t,fieldId:e,recordIds:a},["tableId","fieldId","recordIds"]),await this.http.put("/api/tables/"+t+"/fields/"+e+"/records",{recordIds:a,value:i})}async deleteRecord(t,e){return this._validateRequired({tableId:t,recordId:e},["tableId","recordId"]),await this.http.delete("/api/tables/"+t+"/records/"+e)}async deleteManyRecords(t,e){return this._validateRequired({tableId:t,recordIds:e},["tableId","recordIds"]),await this.http.post("/api/tables/"+t+"/records/delete",{recordIds:e})}async duplicateRecords(t,e){return this._validateRequired({tableId:t,recordIds:e},["tableId","recordIds"]),await this.http.post("/api/tables/"+t+"/records/duplicate",{recordIds:e})}async searchFieldValues(t,e,a){return this._validateRequired({tableId:t,fieldId:e},["tableId","fieldId"]),await this.http.get("/api/tables/"+t+"/"+e+"/search",{query:{q:a}})}async listViews(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/views")}async createView(t,e){return this._validateRequired({tableId:t},["tableId"]),this._validateRequired(e,["name"]),await this.http.put("/api/tables/"+t+"/views",e)}async updateView(t,e,a){return this._validateRequired({tableId:t,viewId:e},["tableId","viewId"]),await this.http.post("/api/tables/"+t+"/views/"+e,a)}async deleteView(t,e){return this._validateRequired({tableId:t,viewId:e},["tableId","viewId"]),await this.http.delete("/api/tables/"+t+"/views/"+e)}async listPages(t){return this._validateRequired({tableId:t},["tableId"]),await this.http.get("/api/tables/"+t+"/pages")}async getPage(t,e){return this._validateRequired({tableId:t,pageId:e},["tableId","pageId"]),await this.http.get("/api/tables/"+t+"/pages/"+e)}async createPage(t,e){return this._validateRequired({tableId:t},["tableId"]),await this.http.put("/api/tables/"+t+"/pages",e)}async listWidgets(t,e){return this._validateRequired({tableId:t,pageId:e},["tableId","pageId"]),await this.http.get("/api/tables/"+t+"/pages/"+e+"/widgets")}async getWidgetChartData(t,e,a){return this._validateRequired({tableId:t,widgetId:e},["tableId","widgetId"]),await this.http.post("/api/tables/"+t+"/widgets/"+e+"/chart-data",a||{})}}class I extends o{async list(){return await this.http.get("/api/module")}async create(t){return this._validateRequired(t,["name","displayName"]),await this.http.post("/api/module",t)}async update(t,e){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.post("/api/module/"+t,e)}async delete(t){return this._validateRequired({moduleId:t},["moduleId"]),await this.http.delete("/api/module/"+t)}async listRecords(t,e){this._validateRequired({moduleName:t},["moduleName"]),e=e||{};const a=this._normalizePagination(e);return await this.http.post("/api/module/"+t+"/records",{filters:e.filters,sort:e.sort,page:a.page,limit:a.limit})}async listAllRecords(t){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.get("/api/module/"+t+"/records")}async searchRecords(t,e){return this._validateRequired({moduleName:t,query:e},["moduleName","query"]),await this.http.get("/api/module/"+t+"/records/search",{query:{q:e}})}async getRecord(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.get("/api/module/"+t+"/records/"+e)}async createRecord(t,e){return this._validateRequired({moduleName:t},["moduleName"]),await this.http.put("/api/module/"+t+"/records",e)}async createManyRecords(t,e){return this._validateRequired({moduleName:t,records:e},["moduleName","records"]),await this.http.put("/api/module/"+t+"/records/multi",{records:e})}async updateRecord(t,e,a){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.put("/api/module/"+t+"/records/"+e,a)}async deleteRecord(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.delete("/api/module/"+t+"/records/"+e)}async listContactRelatedRecords(t){return this._validateRequired({contactId:t},["contactId"]),await this.http.get("/api/module/records/contact-related-list",{query:{contactId:t}})}async listModuleRelatedRecords(t,e){return this._validateRequired({moduleName:t,recordId:e},["moduleName","recordId"]),await this.http.get("/api/module/records/module-related-list",{query:{moduleName:t,recordId:e}})}}class y extends o{async me(){return await this.http.get("/api/users/me")}async updateMe(t){return await this.http.put("/api/users/me",t)}async get(t){return this._validateRequired({userId:t},["userId"]),await this.http.get("/api/users/user/"+t)}async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.get("/api/users/pagination",{query:this._cleanObject({page:e.page,limit:e.limit,status:t.status})})}async listOnline(){return await this.http.get("/api/users/list-online-users")}async create(t){return this._validateRequired(t,["fullname","email","password"]),await this.http.post("/api/users",t)}async update(t,e){return this._validateRequired({userId:t},["userId"]),await this.http.put("/api/users/"+t,e)}async delete(t){return this._validateRequired({userId:t},["userId"]),await this.http.delete("/api/users/"+t)}async updatePassword(t,e){return this._validateRequired({userId:t,newPassword:e},["userId","newPassword"]),await this.http.put("/api/users/"+t+"/updatePassword",{password:e})}async updateOnlineStatus(t,e){return this._validateRequired({userId:t},["userId"]),await this.http.put("/api/users/"+t+"/onlineStatus",{isOnline:e})}async updateStatus(t,e){return this._validateRequired({userId:t,status:e},["userId","status"]),await this.http.put("/api/users/"+t+"/status",{status:e})}async getActiveCount(){return await this.http.get("/api/users/active-user-count")}async getNotificationSettings(){return await this.http.get("/api/users/me/notification-settings")}async completeTutorial(t){return this._validateRequired({tutorialKey:t},["tutorialKey"]),await this.http.post("/api/users/me/setup-guide/"+t)}async logout(){return await this.http.get("/api/users/logout")}}class v extends o{async list(t){const e=t?"/api/tags/"+t:"/api/tags";return await this.http.get(e)}async create(t){return this._validateRequired(t,["name"]),await this.http.post("/api/tags",t)}async update(t){return this._validateRequired(t,["_id"]),await this.http.patch("/api/tags",t)}async delete(t){return this._validateRequired({tagId:t},["tagId"]),await this.http.delete("/api/tags/"+t)}}class _ extends o{async getCurrentPlan(){return await this.http.get("/api/sites/current-plan")}async getFeatures(){return await this.http.get("/api/sites/features")}async getWallet(){return await this.http.get("/api/sites/wallet")}async getWalletActivities(t){return t=t||{},await this.http.get("/api/sites/wallet/activities",{query:this._cleanObject({walletType:t.walletType,startDate:this._toISODate(t.startDate),endDate:this._toISODate(t.endDate)})})}async depositWallet(t,e){return this._validateRequired({walletType:t,amount:e},["walletType","amount"]),await this.http.post("/api/sites/wallet/"+t,{amount:e})}async getAutoRebalanceSettings(t){return this._validateRequired({walletType:t},["walletType"]),await this.http.get("/api/sites/wallet/"+t+"/auto-rebalance")}async updateAutoRebalanceSettings(t,e){return this._validateRequired({walletType:t},["walletType"]),await this.http.put("/api/sites/wallet/"+t+"/auto-rebalance",e)}async getConversationUsage(){return await this.http.get("/api/sites/conversation-usages")}async getStorageUsage(t){return await this.http.post("/api/sites/storage-usages",t||{})}async checkIntegrationStatus(t){return await this.http.post("/api/public/sites/check-integration-status",t||{})}}class m extends o{async list(t){t=t||{};const e=this._normalizePagination(t);return await this.http.post("/api/cache/list",{pattern:t.pattern,type:t.type,actorType:t.actorType,page:e.page,limit:e.limit})}async write(t,e,a){this._validateRequired({key:t},["key"]);const i={key:t,value:e,type:(a=a||{}).type||"public",dataType:a.dataType||"mixed"};if(a.expiresIn){const t=new Date,e={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5,months:2592e6},s=a.expiresIn.value*(e[a.expiresIn.unit]||e.hours);i.expiresAt=new Date(t.getTime()+s).toISOString()}else a.expiresAt&&(i.expiresAt=this._toISODate(a.expiresAt));return await this.http.post("/api/cache/write",i)}async read(t,e){this._validateRequired({key:t},["key"]);try{const a=await this.http.post("/api/cache/list",{pattern:t,limit:1});return a&&a.data&&a.data.length>0?a.data[0].value:void 0!==e?e:null}catch(t){return void 0!==e?e:null}}async update(t,e){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.post("/api/cache/"+t+"/update",{value:e})}async extend(t,e){this._validateRequired({cacheId:t,expiresIn:e},["cacheId","expiresIn"]);const a={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5,months:2592e6},i=new Date,s=e.value*(a[e.unit]||a.hours),r=new Date(i.getTime()+s);return await this.http.post("/api/cache/"+t+"/extend",{expiresAt:r.toISOString()})}async makeNeverExpire(t){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.post("/api/cache/"+t+"/never-expire")}async delete(t){return this._validateRequired({cacheId:t},["cacheId"]),await this.http.delete("/api/cache/"+t)}async deleteMany(t){return this._validateRequired({cacheIds:t},["cacheIds"]),await this.http.post("/api/cache/bulk-delete",{cacheIds:t})}async deleteByActor(t,e){return this._validateRequired({actorType:t,actorId:e},["actorType","actorId"]),await this.http.post("/api/cache/delete-by-actor",{actorType:t,actorId:e})}async deleteByPattern(t){return this._validateRequired({pattern:t},["pattern"]),await this.http.post("/api/cache/delete-by-pattern",{pattern:t})}}class b{constructor(t){if(!t)throw new Error("Config is required");this._validateConfig(t),this._config=t,this._verbose=t.verbose||!1,this._http=new d({env:t.env||"production",baseApiAddress:t.baseApiAddress,siteId:t.siteId,timeout:t.timeout,retryCount:t.retryCount,verbose:t.verbose}),this._connected=!1,this._token=null,this._user=null,this._initModules(),this._log("info","SupsisJS initialized",{env:t.env||"production",baseApiAddress:t.baseApiAddress||"default",siteId:t.siteId})}_log(t){if(this._verbose){var e=Array.prototype.slice.call(arguments,1),a="[SupsisJS]",i=(new Date).toISOString();switch(t){case"info":console.log.apply(console,[a,i,"INFO:"].concat(e));break;case"warn":console.warn.apply(console,[a,i,"WARN:"].concat(e));break;case"error":console.error.apply(console,[a,i,"ERROR:"].concat(e));break;default:console.log.apply(console,[a,i].concat(e))}}}_validateConfig(t){if(!t.email)throw new Error("email is required");if(!t.password)throw new Error("password is required");if(!t.siteId)throw new Error("siteId is required")}_initModules(){this.chat=new l(this._http),this.contact=new c(this._http),this.message=new h(this._http),this.task=new p(this._http),this.aicall=new u(this._http),this.asset=new g(this._http),this.table=new w(this._http),this.module=new I(this._http),this.user=new y(this._http),this.tag=new v(this._http),this.site=new _(this._http),this.cache=new m(this._http)}async connect(){var t;if(this._connected)return this._log("info","Already connected"),this._user;this._log("info","Connecting to Supsis API..."),this._log("info","Base URL:",this._http.baseUrl);try{t=await this._http.post("/api/users/login",{email:this._config.email,password:this._config.password},{skipAuth:!0,retryCount:0})}catch(t){throw this._log("error","Login failed:",t.message),t}if(!t||!t.token){var e="Login failed: No token received";throw t&&t.message&&(e="Login failed: "+t.message),this._log("error",e),new n(e,401,t)}return this._token=t.token,this._user=t.user||t,this._http.setToken(this._token),this._connected=!0,this._log("info","Connected successfully as:",this._user.fullname||this._user.email),this._user}async disconnect(){if(this._connected){try{await this._http.get("/api/users/logout")}catch(t){}this._token=null,this._user=null,this._http.setToken(null),this._connected=!1}}get isConnected(){return this._connected}get currentUser(){return this._user}get token(){return this._token}get version(){return r}get http(){return this._http}setToken(t){this._token=t,this._http.setToken(t),this._connected=!0}}
10
10
  /**
11
11
  * Supsis JS SDK
12
12
  *