@yassirbenmoussa/aicommerce-sdk 1.9.1 → 1.9.3

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
  var AICommerceSDK=(function(exports){'use strict';/*! AI Commerce SDK v1.0.0 | MIT License | https://aicommerce.dev */
2
- var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var H=(a,r)=>()=>(a&&(r=a(a=0)),r);var G=(a,r)=>{for(var e in r)B(a,e,{get:r[e],enumerable:true});},ue=(a,r,e,d)=>{if(r&&typeof r=="object"||typeof r=="function")for(let h of le(r))!pe.call(a,h)&&h!==e&&B(a,h,{get:()=>r[h],enumerable:!(d=me(r,h))||d.enumerable});return a};var j=a=>ue(B({},"__esModule",{value:true}),a);var W={};G(W,{AICommerce:()=>exports.AICommerce,AICommerceError:()=>exports.AICommerceError});exports.AICommerce=void 0;exports.AICommerceError=void 0;var R=H(()=>{exports.AICommerce=class a{constructor(r){this.sessionToken=null;this.products={create:async r=>this.request("/api/v1/products",{method:"POST",body:JSON.stringify(r)}),batchUpsert:async r=>this.request("/api/v1/products",{method:"POST",body:JSON.stringify({products:r})}),list:async r=>{let e=new URLSearchParams;r?.page&&e.set("page",String(r.page)),r?.perPage&&e.set("perPage",String(r.perPage)),r?.search&&e.set("search",r.search),r?.categoryId&&e.set("categoryId",r.categoryId),r?.isActive!==void 0&&e.set("isActive",String(r.isActive));let d=e.toString();return this.request(`/api/v1/products${d?`?${d}`:""}`)},get:async r=>this.request(`/api/v1/products/${r}`),update:async(r,e)=>this.request(`/api/v1/products/${r}`,{method:"PUT",body:JSON.stringify(e)}),delete:async r=>this.request(`/api/v1/products/${r}`,{method:"DELETE"})};if(!r.apiKey)throw new Error("AICommerce: apiKey is required");this.apiKey=r.apiKey,this.storeId=r.storeId,this.baseUrl=this.normalizeUrl(r.baseUrl||this.detectBaseUrl()),this.timeout=r.timeout||3e4;}detectBaseUrl(){if(typeof window<"u"){let r=document.querySelector("script[data-aicommerce-url]");if(r)return r.getAttribute("data-aicommerce-url")||"https://api.aicommerce.dev"}return "https://api.aicommerce.dev"}normalizeUrl(r){return r.replace(/\/$/,"")}async request(r,e={}){let d=`${this.baseUrl}${r}`,h=new AbortController,s=setTimeout(()=>h.abort(),this.timeout);try{let g=await fetch(d,{...e,signal:h.signal,headers:{"Content-Type":"application/json","x-api-key":this.apiKey,...this.storeId&&{"x-store-id":this.storeId},...this.sessionToken&&{"X-Session-Token":this.sessionToken},...e.headers}});if(clearTimeout(s),!g.ok){let S=await g.json().catch(()=>({})),w={code:S.code||"UNKNOWN_ERROR",message:S.message||S.error||`HTTP ${g.status}`,status:g.status};throw new exports.AICommerceError(w.message,w.code,w.status)}return g.json()}catch(g){throw clearTimeout(s),g instanceof exports.AICommerceError?g:g instanceof Error&&g.name==="AbortError"?new exports.AICommerceError("Request timeout","TIMEOUT",408):new exports.AICommerceError(g instanceof Error?g.message:"Unknown error","NETWORK_ERROR",0)}}async chat(r,e){let d=typeof r=="string"?{message:r,context:e,sessionToken:this.sessionToken||void 0}:{...r,sessionToken:r.sessionToken||this.sessionToken||void 0},h=await this.request("/api/v1/chat",{method:"POST",body:JSON.stringify(d)});return h.sessionToken&&(this.sessionToken=h.sessionToken),h}async chatWithAudio(r,e){let d=await r.arrayBuffer(),s={audioBase64:btoa(new Uint8Array(d).reduce((S,w)=>S+String.fromCharCode(w),"")),audioMimeType:r.type||"audio/webm",context:e,sessionToken:this.sessionToken||void 0},g=await this.request("/api/v1/chat",{method:"POST",body:JSON.stringify(s)});return g.sessionToken&&(this.sessionToken=g.sessionToken),g}async createSession(){let r=await this.request("/api/v1/chat/session",{method:"POST"});return this.sessionToken=r.session.token,r.session}clearSession(){this.sessionToken=null;}getSessionToken(){return this.sessionToken}setSessionToken(r){this.sessionToken=r;}async upload(r,e){let d=new FormData;d.append("file",r),e?.folder&&d.append("folder",e.folder),e?.productId&&d.append("productId",e.productId),e?.isPrimary&&d.append("isPrimary","true");let h=`${this.baseUrl}/api/v1/upload`,s=await fetch(h,{method:"POST",headers:{"X-API-Key":this.apiKey},body:d});if(!s.ok){let g=await s.json().catch(()=>({}));throw new exports.AICommerceError(g.message||g.error||`HTTP ${s.status}`,g.code||"UPLOAD_ERROR",s.status)}return s.json()}static async quickChat(r){return new a({apiKey:r.apiKey,baseUrl:r.baseUrl}).chat(r.message,r.context)}},exports.AICommerceError=class a extends Error{constructor(r,e,d){super(r),this.name="AICommerceError",this.code=e,this.status=d,Object.setPrototypeOf(this,a.prototype);}};});function ge(a){let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16)}:{r:99,g:102,b:241}}function z(a){let r=a.primaryColor,e=ge(r),d=a.position==="bottom-left";return `
2
+ var O=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var B=(a,r)=>()=>(a&&(r=a(a=0)),r);var G=(a,r)=>{for(var e in r)O(a,e,{get:r[e],enumerable:true});},ue=(a,r,e,d)=>{if(r&&typeof r=="object"||typeof r=="function")for(let h of le(r))!pe.call(a,h)&&h!==e&&O(a,h,{get:()=>r[h],enumerable:!(d=me(r,h))||d.enumerable});return a};var j=a=>ue(O({},"__esModule",{value:true}),a);var W={};G(W,{AICommerce:()=>exports.AICommerce,AICommerceError:()=>exports.AICommerceError});exports.AICommerce=void 0;exports.AICommerceError=void 0;var M=B(()=>{exports.AICommerce=class a{constructor(r){this.sessionToken=null;this.products={create:async r=>this.request("/api/v1/products",{method:"POST",body:JSON.stringify(r)}),batchUpsert:async r=>this.request("/api/v1/products",{method:"POST",body:JSON.stringify({products:r})}),list:async r=>{let e=new URLSearchParams;r?.page&&e.set("page",String(r.page)),r?.perPage&&e.set("perPage",String(r.perPage)),r?.search&&e.set("search",r.search),r?.categoryId&&e.set("categoryId",r.categoryId),r?.isActive!==void 0&&e.set("isActive",String(r.isActive));let d=e.toString();return this.request(`/api/v1/products${d?`?${d}`:""}`)},get:async r=>this.request(`/api/v1/products/${r}`),update:async(r,e)=>this.request(`/api/v1/products/${r}`,{method:"PUT",body:JSON.stringify(e)}),delete:async r=>this.request(`/api/v1/products/${r}`,{method:"DELETE"})};if(!r.apiKey)throw new Error("AICommerce: apiKey is required");this.apiKey=r.apiKey,this.storeId=r.storeId,this.baseUrl=this.normalizeUrl(r.baseUrl||this.detectBaseUrl()),this.timeout=r.timeout||3e4;}detectBaseUrl(){if(typeof window<"u"){let r=document.querySelector("script[data-aicommerce-url]");if(r)return r.getAttribute("data-aicommerce-url")||"https://api.aicommerce.dev"}return "https://api.aicommerce.dev"}normalizeUrl(r){return r.replace(/\/$/,"")}async request(r,e={}){let d=`${this.baseUrl}${r}`,h=new AbortController,s=setTimeout(()=>h.abort(),this.timeout);try{let g=await fetch(d,{...e,signal:h.signal,headers:{"Content-Type":"application/json","x-api-key":this.apiKey,...this.storeId&&{"x-store-id":this.storeId},...this.sessionToken&&{"X-Session-Token":this.sessionToken},...e.headers}});if(clearTimeout(s),!g.ok){let L=await g.json().catch(()=>({})),w={code:L.code||"UNKNOWN_ERROR",message:L.message||L.error||`HTTP ${g.status}`,status:g.status};throw new exports.AICommerceError(w.message,w.code,w.status)}return g.json()}catch(g){throw clearTimeout(s),g instanceof exports.AICommerceError?g:g instanceof Error&&g.name==="AbortError"?new exports.AICommerceError("Request timeout","TIMEOUT",408):new exports.AICommerceError(g instanceof Error?g.message:"Unknown error","NETWORK_ERROR",0)}}async chat(r,e){let d=typeof r=="string"?{message:r,context:e,sessionToken:this.sessionToken||void 0}:{...r,sessionToken:r.sessionToken||this.sessionToken||void 0},h=await this.request("/api/v1/chat",{method:"POST",body:JSON.stringify(d)});return h.sessionToken&&(this.sessionToken=h.sessionToken),h}async chatWithAudio(r,e){let d=await r.arrayBuffer(),s={audioBase64:btoa(new Uint8Array(d).reduce((L,w)=>L+String.fromCharCode(w),"")),audioMimeType:r.type||"audio/webm",context:e,sessionToken:this.sessionToken||void 0},g=await this.request("/api/v1/chat",{method:"POST",body:JSON.stringify(s)});return g.sessionToken&&(this.sessionToken=g.sessionToken),g}async createSession(){let r=await this.request("/api/v1/chat/session",{method:"POST"});return this.sessionToken=r.session.token,r.session}clearSession(){this.sessionToken=null;}getSessionToken(){return this.sessionToken}setSessionToken(r){this.sessionToken=r;}async checkApiKey(){return this.request("/api/v1/api-key/check")}async getHistory(r){let e=new URLSearchParams;return e.set("sessionToken",r.sessionToken),r.page&&e.set("page",String(r.page)),r.limit&&e.set("limit",String(r.limit)),this.request(`/api/v1/chat/history?${e.toString()}`)}async upload(r,e){let d=new FormData;d.append("file",r),e?.folder&&d.append("folder",e.folder),e?.productId&&d.append("productId",e.productId),e?.isPrimary&&d.append("isPrimary","true");let h=`${this.baseUrl}/api/v1/upload`,s=await fetch(h,{method:"POST",headers:{"X-API-Key":this.apiKey},body:d});if(!s.ok){let g=await s.json().catch(()=>({}));throw new exports.AICommerceError(g.message||g.error||`HTTP ${s.status}`,g.code||"UPLOAD_ERROR",s.status)}return s.json()}static async quickChat(r){return new a({apiKey:r.apiKey,baseUrl:r.baseUrl}).chat(r.message,r.context)}},exports.AICommerceError=class a extends Error{constructor(r,e,d){super(r),this.name="AICommerceError",this.code=e,this.status=d,Object.setPrototypeOf(this,a.prototype);}};});function ge(a){let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16)}:{r:99,g:102,b:241}}function z(a){let r=a.primaryColor,e=ge(r),d=a.position==="bottom-left";return `
3
3
  /* AI Commerce Widget Styles */
4
4
  #aicommerce-widget {
5
5
  --aic-primary: ${r};
@@ -855,7 +855,7 @@ var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object
855
855
  .aicommerce-spinner {
856
856
  animation: aicommerce-spin 1s linear infinite;
857
857
  }
858
- `}function _(a){let r=document.createElement("style");r.id="aicommerce-widget-styles",r.textContent=a;let e=document.getElementById("aicommerce-widget-styles");return e&&e.remove(),document.head.appendChild(r),r}var Q=H(()=>{});var Z={};G(Z,{AICommerceWidget:()=>exports.AICommerceWidget,createWidget:()=>D});function D(a){if(!a.apiKey)throw new Error("AICommerceWidget: apiKey is required");let r=new exports.AICommerce({apiKey:a.apiKey,storeId:a.storeId,baseUrl:a.baseUrl}),e={isOpen:false,isLoading:true,isRecording:false,messages:[],storeConfig:null},d=null,h=[],s=null,w=null,m;async function ee(){try{let o=a.baseUrl||N(),i=await fetch(`${o}/api/v1/store`,{headers:{"x-api-key":a.apiKey}});return i.ok?(await i.json()).store:null}catch(o){return console.error("Failed to fetch store config:",o),null}}function N(){if(typeof window<"u"){let o=document.querySelector("script[data-aicommerce-url]");if(o)return o.getAttribute("data-aicommerce-url")||""}return "https://api.aicommerce.dev"}async function re(){e.storeConfig=await ee();let o=a.displayMode||"widget",i=o==="embedded";m={apiKey:a.apiKey,storeId:a.storeId,baseUrl:a.baseUrl||N(),displayMode:o,container:a.container,maxHeight:a.maxHeight||"600px",placeholder:a.placeholder||"Ask me anything about our products...",position:a.position||"bottom-right",theme:a.theme||"auto",primaryColor:a.primaryColor||e.storeConfig?.primaryColor||"#6366f1",welcomeMessage:a.welcomeMessage||e.storeConfig?.welcomeMessage||"Hi! How can I help you find the perfect product today?",botName:a.botName||e.storeConfig?.chatBotName||"Shopping Assistant",zIndex:a.zIndex||9999,buttonText:a.buttonText||"\u{1F4AC}",hideLauncher:a.hideLauncher||false,addToCartText:a.addToCartText,onOpen:a.onOpen,onClose:a.onClose,onProductClick:a.onProductClick,onAddToCart:a.onAddToCart,onMessage:a.onMessage};let c=z(m);if(w=_(c),i){let b=null;if(typeof a.container=="string"?b=document.querySelector(a.container):a.container instanceof HTMLElement&&(b=a.container),!b){console.error("[AI Commerce] Embedded mode requires a valid container element or selector");return}s=document.createElement("div"),s.id="aicommerce-widget",s.className=`aicommerce-widget aicommerce-embedded aicommerce-theme-${m.theme}`,s.style.setProperty("--aic-max-height",m.maxHeight),b.appendChild(s),e.isOpen=true;}else s=document.createElement("div"),s.id="aicommerce-widget",s.className=`aicommerce-widget aicommerce-${m.position} aicommerce-theme-${m.theme}`,document.body.appendChild(s);k(),i||e.messages.push({role:"assistant",content:m.welcomeMessage}),e.isLoading=false,k();}async function te(o,i=1){let c=o;if(o.includes("gid://")){let u=o.match(/\/(\d+)$/);u&&(c=u[1]);}if(!(await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:c,quantity:i})})).ok)throw new Error("Failed to add to cart");document.dispatchEvent(new CustomEvent("cart:refresh"));}function k(){if(!s)return;let o=m.displayMode==="embedded",i=e.messages.some(l=>l.role==="user");o&&(s.classList.remove("aicommerce-no-messages","aicommerce-has-messages"),s.classList.add(i?"aicommerce-has-messages":"aicommerce-no-messages"));let c=m.placeholder||"Ask me anything about our products...",b=`
858
+ `}function _(a){let r=document.createElement("style");r.id="aicommerce-widget-styles",r.textContent=a;let e=document.getElementById("aicommerce-widget-styles");return e&&e.remove(),document.head.appendChild(r),r}var Q=B(()=>{});var Z={};G(Z,{AICommerceWidget:()=>exports.AICommerceWidget,createWidget:()=>D});function D(a){if(!a.apiKey)throw new Error("AICommerceWidget: apiKey is required");let r=new exports.AICommerce({apiKey:a.apiKey,storeId:a.storeId,baseUrl:a.baseUrl}),e={isOpen:false,isLoading:true,isRecording:false,messages:[],storeConfig:null},d=null,h=[],s=null,w=null,m;async function ee(){try{let o=a.baseUrl||N(),i=await fetch(`${o}/api/v1/store`,{headers:{"x-api-key":a.apiKey}});return i.ok?(await i.json()).store:null}catch(o){return console.error("Failed to fetch store config:",o),null}}function N(){if(typeof window<"u"){let o=document.querySelector("script[data-aicommerce-url]");if(o)return o.getAttribute("data-aicommerce-url")||""}return "https://api.aicommerce.dev"}async function re(){e.storeConfig=await ee();let o=a.displayMode||"widget",i=o==="embedded";m={apiKey:a.apiKey,storeId:a.storeId,baseUrl:a.baseUrl||N(),displayMode:o,container:a.container,maxHeight:a.maxHeight||"600px",placeholder:a.placeholder||"Ask me anything about our products...",position:a.position||"bottom-right",theme:a.theme||"auto",primaryColor:a.primaryColor||e.storeConfig?.primaryColor||"#6366f1",welcomeMessage:a.welcomeMessage||e.storeConfig?.welcomeMessage||"Hi! How can I help you find the perfect product today?",botName:a.botName||e.storeConfig?.chatBotName||"Shopping Assistant",zIndex:a.zIndex||9999,buttonText:a.buttonText||"\u{1F4AC}",hideLauncher:a.hideLauncher||false,addToCartText:a.addToCartText,onOpen:a.onOpen,onClose:a.onClose,onProductClick:a.onProductClick,onAddToCart:a.onAddToCart,onMessage:a.onMessage};let c=z(m);if(w=_(c),i){let b=null;if(typeof a.container=="string"?b=document.querySelector(a.container):a.container instanceof HTMLElement&&(b=a.container),!b){console.error("[AI Commerce] Embedded mode requires a valid container element or selector");return}s=document.createElement("div"),s.id="aicommerce-widget",s.className=`aicommerce-widget aicommerce-embedded aicommerce-theme-${m.theme}`,s.style.setProperty("--aic-max-height",m.maxHeight),b.appendChild(s),e.isOpen=true;}else s=document.createElement("div"),s.id="aicommerce-widget",s.className=`aicommerce-widget aicommerce-${m.position} aicommerce-theme-${m.theme}`,document.body.appendChild(s);k(),i||e.messages.push({role:"assistant",content:m.welcomeMessage}),e.isLoading=false,k();}async function te(o,i=1){let c=o;if(o.includes("gid://")){let u=o.match(/\/(\d+)$/);u&&(c=u[1]);}if(!(await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:c,quantity:i})})).ok)throw new Error("Failed to add to cart");document.dispatchEvent(new CustomEvent("cart:refresh"));}function k(){if(!s)return;let o=m.displayMode==="embedded",i=e.messages.some(l=>l.role==="user");o&&(s.classList.remove("aicommerce-no-messages","aicommerce-has-messages"),s.classList.add(i?"aicommerce-has-messages":"aicommerce-no-messages"));let c=m.placeholder||"Ask me anything about our products...",b=`
859
859
  <div class="aicommerce-input-container">
860
860
  ${o?`
861
861
  <textarea
@@ -917,10 +917,10 @@ var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object
917
917
 
918
918
  ${o&&i?`
919
919
  <div class="aicommerce-messages">
920
- ${e.messages.map((l,L)=>{let A=J(l.content),n=l.role==="user";return `
920
+ ${e.messages.map((l,S)=>{let A=J(l.content),n=l.role==="user";return `
921
921
  <div class="aicommerce-message aicommerce-${l.role}">
922
922
  <div class="aicommerce-message-content ${A?"aicommerce-rtl":"aicommerce-ltr"}">
923
- ${l.audioUrl?Y(l,L,n):T(l.content)}
923
+ ${l.audioUrl?Y(l,S,n):T(l.content)}
924
924
  </div>
925
925
  ${l.products&&l.products.length>0?`
926
926
  <div class="aicommerce-products">
@@ -961,10 +961,10 @@ var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object
961
961
 
962
962
  ${o?"":`
963
963
  <div class="aicommerce-messages">
964
- ${e.messages.map((l,L)=>{let A=J(l.content),n=l.role==="user";return `
964
+ ${e.messages.map((l,S)=>{let A=J(l.content),n=l.role==="user";return `
965
965
  <div class="aicommerce-message aicommerce-${l.role}">
966
966
  <div class="aicommerce-message-content ${A?"aicommerce-rtl":"aicommerce-ltr"}">
967
- ${l.audioUrl?Y(l,L,n):T(l.content)}
967
+ ${l.audioUrl?Y(l,S,n):T(l.content)}
968
968
  </div>
969
969
  ${l.products&&l.products.length>0?`
970
970
  <div class="aicommerce-products">
@@ -1027,7 +1027,7 @@ var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object
1027
1027
  </div>
1028
1028
  <audio src="${o.audioUrl}" preload="metadata"></audio>
1029
1029
  </div>
1030
- `}function oe(){if(!s)return;let o=s.querySelector(".aicommerce-launcher");o&&o.addEventListener("click",()=>q());let i=s.querySelector(".aicommerce-close");i&&i.addEventListener("click",()=>O());let c=s.querySelector(".aicommerce-input"),b=s.querySelector(".aicommerce-send");c&&(c.addEventListener("keydown",n=>{let t=n;if(t.key==="Enter"){let p=c instanceof HTMLTextAreaElement;if(p&&t.shiftKey)return;n.preventDefault();let f=c.value.trim();f&&(U(f),c.value="",p&&(c.style.height="auto"));}}),c instanceof HTMLTextAreaElement&&c.addEventListener("input",()=>{c.style.height="auto",c.style.height=Math.min(c.scrollHeight,150)+"px";})),b&&c&&b.addEventListener("click",()=>{let n=c.value.trim();n&&(U(n),c.value="",c instanceof HTMLTextAreaElement&&(c.style.height="auto"));});let u=s.querySelector(".aicommerce-mic");u&&u.addEventListener("click",()=>ae()),s.querySelectorAll(".aicommerce-product-card").forEach(n=>{n.addEventListener("click",t=>{if(t.target.closest(".aicommerce-add-to-cart"))return;let p=n.getAttribute("data-product-id"),f=e.messages.flatMap(y=>y.products||[]).find(y=>y.id===p);f&&(m.onProductClick?m.onProductClick(f):f.url&&window.open(f.url,"_blank","noopener,noreferrer"));});}),s.querySelectorAll(".aicommerce-add-to-cart").forEach(n=>{n.addEventListener("click",async t=>{t.stopPropagation();let p=n,f=p.closest(".aicommerce-product-card"),y=f?.getAttribute("data-product-id"),x=f?.getAttribute("data-variant-id"),C=e.messages.flatMap($=>$.products||[]).find($=>$.id===y);if(!C)return;let v=p.innerHTML;p.disabled=true,p.innerHTML=`
1030
+ `}function oe(){if(!s)return;let o=s.querySelector(".aicommerce-launcher");o&&o.addEventListener("click",()=>q());let i=s.querySelector(".aicommerce-close");i&&i.addEventListener("click",()=>H());let c=s.querySelector(".aicommerce-input"),b=s.querySelector(".aicommerce-send");c&&(c.addEventListener("keydown",n=>{let t=n;if(t.key==="Enter"){let p=c instanceof HTMLTextAreaElement;if(p&&t.shiftKey)return;n.preventDefault();let f=c.value.trim();f&&(U(f),c.value="",p&&(c.style.height="auto"));}}),c instanceof HTMLTextAreaElement&&c.addEventListener("input",()=>{c.style.height="auto",c.style.height=Math.min(c.scrollHeight,150)+"px";})),b&&c&&b.addEventListener("click",()=>{let n=c.value.trim();n&&(U(n),c.value="",c instanceof HTMLTextAreaElement&&(c.style.height="auto"));});let u=s.querySelector(".aicommerce-mic");u&&u.addEventListener("click",()=>ae()),s.querySelectorAll(".aicommerce-product-card").forEach(n=>{n.addEventListener("click",t=>{if(t.target.closest(".aicommerce-add-to-cart"))return;let p=n.getAttribute("data-product-id"),f=e.messages.flatMap(y=>y.products||[]).find(y=>y.id===p);f&&(m.onProductClick?m.onProductClick(f):f.url&&window.open(f.url,"_blank","noopener,noreferrer"));});}),s.querySelectorAll(".aicommerce-add-to-cart").forEach(n=>{n.addEventListener("click",async t=>{t.stopPropagation();let p=n,f=p.closest(".aicommerce-product-card"),y=f?.getAttribute("data-product-id"),x=f?.getAttribute("data-variant-id"),C=e.messages.flatMap(P=>P.products||[]).find(P=>P.id===y);if(!C)return;let v=p.innerHTML;p.disabled=true,p.innerHTML=`
1031
1031
  <svg class="aicommerce-spinner" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1032
1032
  <circle cx="12" cy="12" r="10" stroke-dasharray="32" stroke-dashoffset="32"/>
1033
1033
  </svg>
@@ -1037,5 +1037,5 @@ var B=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var le=Object
1037
1037
  <polyline points="20 6 9 17 4 12"/>
1038
1038
  </svg>
1039
1039
  Added!
1040
- `,setTimeout(()=>{p.innerHTML=v,p.disabled=!1;},2e3);}catch($){console.error("[AI Commerce] Add to cart failed:",$),p.innerHTML=v,p.disabled=false;}});}),s.querySelectorAll(".aicommerce-products").forEach(n=>{let t=false,p=0,f=0;n.addEventListener("mousedown",y=>{t=true,n.style.cursor="grabbing",p=y.pageX-n.offsetLeft,f=n.scrollLeft;}),n.addEventListener("mouseleave",()=>{t=false,n.style.cursor="grab";}),n.addEventListener("mouseup",()=>{t=false,n.style.cursor="grab";}),n.addEventListener("mousemove",y=>{if(!t)return;y.preventDefault();let C=(y.pageX-n.offsetLeft-p)*2;n.scrollLeft=f-C;});}),s.querySelectorAll(".aicommerce-audio-player").forEach(n=>{let t=n.querySelector("audio"),p=n.querySelector(".aicommerce-audio-btn"),f=n.querySelectorAll(".aicommerce-waveform-bar"),y=n.querySelector(".aicommerce-current-time");if(!t||!p)return;p.addEventListener("click",()=>{!t.paused?(t.pause(),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>'):(s?.querySelectorAll("audio").forEach(v=>{if(v!==t&&!v.paused){v.pause();let M=v.closest(".aicommerce-audio-player")?.querySelector(".aicommerce-audio-btn");M&&(M.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>');}}),t.play(),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect></svg>');}),t.addEventListener("timeupdate",()=>{if(y&&(y.textContent=V(t.currentTime)),t.duration){let C=t.currentTime/t.duration*100;f.forEach((v,$)=>{$/f.length*100<=C?v.style.backgroundColor=n.closest(".aicommerce-user")?"rgba(255,255,255,1)":"var(--aic-primary)":v.style.backgroundColor=n.closest(".aicommerce-user")?"rgba(255,255,255,0.4)":"rgba(99,102,241,0.3)";});}}),t.addEventListener("ended",()=>{p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>';});let x=n.querySelector(".aicommerce-waveform-bars");x&&x.addEventListener("click",C=>{let v=x.getBoundingClientRect(),M=(C.clientX-v.left)/v.width;t.duration&&(t.currentTime=M*t.duration);});});}async function ae(){if(e.isRecording)d&&d.state!=="inactive"&&d.stop();else try{let o=await navigator.mediaDevices.getUserMedia({audio:!0});h=[],d=new MediaRecorder(o,{mimeType:MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4"}),d.ondataavailable=i=>{i.data.size>0&&h.push(i.data);},d.onstop=async()=>{if(o.getTracks().forEach(i=>i.stop()),h.length>0){let i=new Blob(h,{type:d?.mimeType||"audio/webm"});await ie(i);}e.isRecording=!1,k();},d.start(),e.isRecording=!0,k();}catch(o){console.error("Failed to start recording:",o),e.messages.push({role:"assistant",content:"Unable to access microphone. Please check your permissions."}),k();}}async function ie(o){let i=URL.createObjectURL(o),c=Array(40).fill(10),b=0;try{c=await se(o);let u=new Audio(i);await new Promise(E=>{u.onloadedmetadata=()=>{b=u.duration,E();},u.onerror=()=>E();});}catch(u){console.error("Audio analysis failed",u);}e.messages.push({role:"user",content:"Voice message",audioUrl:i,audioDuration:b,waveformBars:c}),e.isLoading=true,k();try{let u=await r.chatWithAudio(o);return e.messages.push({role:"assistant",content:u.reply,products:u.products}),m.onMessage&&m.onMessage("Voice message",u),u}catch(u){throw e.messages.push({role:"assistant",content:"Sorry, I encountered an error processing your voice message. Please try again."}),u}finally{e.isLoading=false,k();}}function J(o){return /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/.test(o)}function V(o){let i=Math.floor(o/60),c=Math.floor(o%60);return `${i}:${c.toString().padStart(2,"0")}`}async function se(o){try{let i=new(window.AudioContext||window.webkitAudioContext),c=await o.arrayBuffer(),u=(await i.decodeAudioData(c)).getChannelData(0),E=40,l=Math.floor(u.length/E),L=[];for(let A=0;A<E;A++){let n=A*l,t=n+l,p=0;for(let x=n;x<t;x++)u[x]&&(p+=u[x]*u[x]);let f=Math.sqrt(p/l),y=Math.min(100,Math.max(10,f*400));L.push(y);}return L}catch(i){return console.error("Analysis error",i),Array.from({length:40},()=>20+Math.random()*60)}}async function U(o){e.messages.push({role:"user",content:o}),e.isLoading=true,k();try{let i=await r.chat(o);return e.messages.push({role:"assistant",content:i.reply,products:i.products}),m.onMessage&&m.onMessage(o,i),i}catch(i){throw e.messages.push({role:"assistant",content:"Sorry, I encountered an error. Please try again."}),i}finally{e.isLoading=false,k();}}function q(){e.isOpen=true,k(),m.onOpen?.(),setTimeout(()=>{s?.querySelector(".aicommerce-input")?.focus();},100);}function O(){e.isOpen=false,k(),m.onClose?.();}function ne(){e.isOpen?O():q();}function ce(){s&&(s.remove(),s=null),w&&(w.remove(),w=null);}function de(o){if(Object.assign(m,o),o.primaryColor){let i=z(m);w&&(w.textContent=i);}k();}function T(o){let i=document.createElement("div");return i.textContent=o,i.innerHTML}function X(o,i){let b={USD:"$",EUR:"\u20AC",GBP:"\xA3",MAD:"DH",SAR:"SAR",AED:"AED",JPY:"\xA5",CNY:"\xA5"}[i||"USD"]||i||"$";return `${o.toFixed(2)} ${b}`}return re(),{open:q,close:O,toggle:ne,destroy:ce,sendMessage:U,updateConfig:de}}exports.AICommerceWidget=void 0;var K=H(()=>{R();Q();exports.AICommerceWidget={init:D,VERSION:"1.0.0"};typeof window<"u"&&(window.AICommerceWidget=exports.AICommerceWidget);});R();K();var xe="1.0.0";typeof window<"u"&&(window.AICommerce=(R(),j(W)).AICommerce,window.AICommerceError=(R(),j(W)).AICommerceError,window.AICommerceWidget=(K(),j(Z)).AICommerceWidget);exports.VERSION=xe;exports.createWidget=D;return exports;})({});//# sourceMappingURL=index.min.js.map
1040
+ `,setTimeout(()=>{p.innerHTML=v,p.disabled=!1;},2e3);}catch(P){console.error("[AI Commerce] Add to cart failed:",P),p.innerHTML=v,p.disabled=false;}});}),s.querySelectorAll(".aicommerce-products").forEach(n=>{let t=false,p=0,f=0;n.addEventListener("mousedown",y=>{t=true,n.style.cursor="grabbing",p=y.pageX-n.offsetLeft,f=n.scrollLeft;}),n.addEventListener("mouseleave",()=>{t=false,n.style.cursor="grab";}),n.addEventListener("mouseup",()=>{t=false,n.style.cursor="grab";}),n.addEventListener("mousemove",y=>{if(!t)return;y.preventDefault();let C=(y.pageX-n.offsetLeft-p)*2;n.scrollLeft=f-C;});}),s.querySelectorAll(".aicommerce-audio-player").forEach(n=>{let t=n.querySelector("audio"),p=n.querySelector(".aicommerce-audio-btn"),f=n.querySelectorAll(".aicommerce-waveform-bar"),y=n.querySelector(".aicommerce-current-time");if(!t||!p)return;p.addEventListener("click",()=>{!t.paused?(t.pause(),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>'):(s?.querySelectorAll("audio").forEach(v=>{if(v!==t&&!v.paused){v.pause();let I=v.closest(".aicommerce-audio-player")?.querySelector(".aicommerce-audio-btn");I&&(I.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>');}}),t.play(),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect></svg>');}),t.addEventListener("timeupdate",()=>{if(y&&(y.textContent=V(t.currentTime)),t.duration){let C=t.currentTime/t.duration*100;f.forEach((v,P)=>{P/f.length*100<=C?v.style.backgroundColor=n.closest(".aicommerce-user")?"rgba(255,255,255,1)":"var(--aic-primary)":v.style.backgroundColor=n.closest(".aicommerce-user")?"rgba(255,255,255,0.4)":"rgba(99,102,241,0.3)";});}}),t.addEventListener("ended",()=>{p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>';});let x=n.querySelector(".aicommerce-waveform-bars");x&&x.addEventListener("click",C=>{let v=x.getBoundingClientRect(),I=(C.clientX-v.left)/v.width;t.duration&&(t.currentTime=I*t.duration);});});}async function ae(){if(e.isRecording)d&&d.state!=="inactive"&&d.stop();else try{let o=await navigator.mediaDevices.getUserMedia({audio:!0});h=[],d=new MediaRecorder(o,{mimeType:MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4"}),d.ondataavailable=i=>{i.data.size>0&&h.push(i.data);},d.onstop=async()=>{if(o.getTracks().forEach(i=>i.stop()),h.length>0){let i=new Blob(h,{type:d?.mimeType||"audio/webm"});await ie(i);}e.isRecording=!1,k();},d.start(),e.isRecording=!0,k();}catch(o){console.error("Failed to start recording:",o),e.messages.push({role:"assistant",content:"Unable to access microphone. Please check your permissions."}),k();}}async function ie(o){let i=URL.createObjectURL(o),c=Array(40).fill(10),b=0;try{c=await se(o);let u=new Audio(i);await new Promise(E=>{u.onloadedmetadata=()=>{b=u.duration,E();},u.onerror=()=>E();});}catch(u){console.error("Audio analysis failed",u);}e.messages.push({role:"user",content:"Voice message",audioUrl:i,audioDuration:b,waveformBars:c}),e.isLoading=true,k();try{let u=await r.chatWithAudio(o);return e.messages.push({role:"assistant",content:u.reply,products:u.products}),m.onMessage&&m.onMessage("Voice message",u),u}catch(u){throw e.messages.push({role:"assistant",content:"Sorry, I encountered an error processing your voice message. Please try again."}),u}finally{e.isLoading=false,k();}}function J(o){return /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/.test(o)}function V(o){let i=Math.floor(o/60),c=Math.floor(o%60);return `${i}:${c.toString().padStart(2,"0")}`}async function se(o){try{let i=new(window.AudioContext||window.webkitAudioContext),c=await o.arrayBuffer(),u=(await i.decodeAudioData(c)).getChannelData(0),E=40,l=Math.floor(u.length/E),S=[];for(let A=0;A<E;A++){let n=A*l,t=n+l,p=0;for(let x=n;x<t;x++)u[x]&&(p+=u[x]*u[x]);let f=Math.sqrt(p/l),y=Math.min(100,Math.max(10,f*400));S.push(y);}return S}catch(i){return console.error("Analysis error",i),Array.from({length:40},()=>20+Math.random()*60)}}async function U(o){e.messages.push({role:"user",content:o}),e.isLoading=true,k();try{let i=await r.chat(o);return e.messages.push({role:"assistant",content:i.reply,products:i.products}),m.onMessage&&m.onMessage(o,i),i}catch(i){throw e.messages.push({role:"assistant",content:"Sorry, I encountered an error. Please try again."}),i}finally{e.isLoading=false,k();}}function q(){e.isOpen=true,k(),m.onOpen?.(),setTimeout(()=>{s?.querySelector(".aicommerce-input")?.focus();},100);}function H(){e.isOpen=false,k(),m.onClose?.();}function ne(){e.isOpen?H():q();}function ce(){s&&(s.remove(),s=null),w&&(w.remove(),w=null);}function de(o){if(Object.assign(m,o),o.primaryColor){let i=z(m);w&&(w.textContent=i);}k();}function T(o){let i=document.createElement("div");return i.textContent=o,i.innerHTML}function X(o,i){let b={USD:"$",EUR:"\u20AC",GBP:"\xA3",MAD:"DH",SAR:"SAR",AED:"AED",JPY:"\xA5",CNY:"\xA5"}[i||"USD"]||i||"$";return `${o.toFixed(2)} ${b}`}return re(),{open:q,close:H,toggle:ne,destroy:ce,sendMessage:U,updateConfig:de}}exports.AICommerceWidget=void 0;var F=B(()=>{M();Q();exports.AICommerceWidget={init:D,VERSION:"1.0.0"};typeof window<"u"&&(window.AICommerceWidget=exports.AICommerceWidget);});M();F();var xe="1.0.0";typeof window<"u"&&(window.AICommerce=(M(),j(W)).AICommerce,window.AICommerceError=(M(),j(W)).AICommerceError,window.AICommerceWidget=(F(),j(Z)).AICommerceWidget);exports.VERSION=xe;exports.createWidget=D;return exports;})({});//# sourceMappingURL=index.min.js.map
1041
1041
  //# sourceMappingURL=index.min.js.map
package/dist/index.cjs CHANGED
@@ -269,6 +269,36 @@ var init_client = __esm({
269
269
  setSessionToken(token) {
270
270
  this.sessionToken = token;
271
271
  }
272
+ /**
273
+ * Check if the API key is valid
274
+ */
275
+ async checkApiKey() {
276
+ return this.request("/api/v1/api-key/check");
277
+ }
278
+ /**
279
+ * Get conversation history for a session
280
+ *
281
+ * @param options - History options with sessionToken, page, and limit
282
+ * @returns Paginated messages (newest first)
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * const history = await client.getHistory({
287
+ * sessionToken: 'your-session-token',
288
+ * page: 1,
289
+ * limit: 20
290
+ * });
291
+ * console.log(history.messages);
292
+ * console.log(history.pagination.hasMore);
293
+ * ```
294
+ */
295
+ async getHistory(options) {
296
+ const params = new URLSearchParams();
297
+ params.set("sessionToken", options.sessionToken);
298
+ if (options.page) params.set("page", String(options.page));
299
+ if (options.limit) params.set("limit", String(options.limit));
300
+ return this.request(`/api/v1/chat/history?${params.toString()}`);
301
+ }
272
302
  // ============================================
273
303
  // Upload API
274
304
  // ============================================