@maxaiagent/widget-sdk 1.2.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -11
package/dist/index.global.js
CHANGED
|
@@ -41,4 +41,4 @@
|
|
|
41
41
|
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
42
|
`,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function S(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let y=!1,m=!1,b=!1,ie=0,se=0,Y=0,J=0;function M(d,u){let v=window.innerWidth-a.offsetWidth,ee=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(ee,u))+"px",a.style.bottom="auto",a.style.right="auto"}function re(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}V()}function V(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,ee=window.innerHeight-u.bottom;v<d+8&&ee>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&M(u,v)}catch(d){}}Je(),V(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,ie=d.clientX,se=d.clientY;let u=a.getBoundingClientRect();Y=u.left,J=u.top,M(Y,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-ie,v=d.clientY-se;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(Y+u,J+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,re(),m=!1))});let C=!1,w=!1,oe=0,ae=0,Q=0,Z=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,oe=d.clientX,ae=d.clientY;let u=a.getBoundingClientRect();Q=u.left,Z=u.top,M(Q,Z),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-oe,v=d.clientY-ae;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(Q+u,Z+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(re(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?gt:mt,document.body.appendChild(x);let le=!1;function Ve(){le=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(le){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(V(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var z=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=q(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var F=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
|
|
43
43
|
`)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
|
|
44
|
-
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;this.debug=new W;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new B(this.transport),this.pointAndAsk=new $(this.transport),this.spaDetector=new X(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen(Se,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(D,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(K,()=>{this.clearSessionToken()}),this.transport.listen(_e,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=q();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ne={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new j(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ne.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ne);return rt(yt);})();
|
|
44
|
+
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;this.debug=new W;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new B(this.transport),this.pointAndAsk=new $(this.transport),this.spaDetector=new X(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(Se,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(D,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(K,()=>{this.clearSessionToken()}),this.transport.listen(_e,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=q();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ne={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new j(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ne.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ne);return rt(yt);})();
|
package/dist/index.js
CHANGED
|
@@ -41,4 +41,4 @@
|
|
|
41
41
|
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
42
|
`,ut='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var gt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',mt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Ne(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function De(n,e){let t=Ne(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function S(n,e){let t=Ne(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ft(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ke(n,e,t,i){let s=vt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=De(s,.08),l=De(s,-.06);r.style.background=`linear-gradient(180deg, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function vt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ft(n):"":""}function Be(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=pt,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=ut,a.appendChild(p);let y=!1,m=!1,b=!1,ie=0,se=0,Y=0,J=0;function M(d,u){let v=window.innerWidth-a.offsetWidth,ee=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(ee,u))+"px",a.style.bottom="auto",a.style.right="auto"}function re(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}V()}function V(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,ee=window.innerHeight-u.bottom;v<d+8&&ee>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function Je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&M(u,v)}catch(d){}}Je(),V(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,ie=d.clientX,se=d.clientY;let u=a.getBoundingClientRect();Y=u.left,J=u.top,M(Y,J),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-ie,v=d.clientY-se;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(Y+u,J+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,re(),m=!1))});let C=!1,w=!1,oe=0,ae=0,Q=0,Z=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,oe=d.clientX,ae=d.clientY;let u=a.getBoundingClientRect();Q=u.left,Z=u.top,M(Q,Z),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-oe,v=d.clientY-ae;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(Q+u,Z+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(re(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?gt:mt,document.body.appendChild(x);let le=!1;function Ve(){le=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(le){Ve();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(V(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,style:r}}function We(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function $e(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Xe(n){n.container.remove(),n.tab.remove(),n.style.remove()}function qe(n){n.shell.classList.add("open")}function ze(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var z=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=q(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(O(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var F=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(O(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Fe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function bt(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
|
|
43
43
|
`)}if(r.length>e.join(" ").length)return Fe(r.trim(),3e3)}return Fe(e.join(`
|
|
44
|
-
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;this.debug=new W;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new B(this.transport),this.pointAndAsk=new $(this.transport),this.spaDetector=new X(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen(Se,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(D,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(K,()=>{this.clearSessionToken()}),this.transport.listen(_e,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=q();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ne={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new j(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ne.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ne);
|
|
44
|
+
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(P,{features:e.config}),o()}),s.listen(N,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(D,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(K,()=>{}),s.listen(U,()=>{o()}),n.appendChild(i);function o(){let a=bt(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(R,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function je(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function Ye(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var j=class{constructor(e){this.emitter=new A;this.debug=new W;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new B(this.transport),this.pointAndAsk=new $(this.transport),this.spaDetector=new X(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=Be(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(P,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=je(t),this.inlineObserver=Ye(t)}setupMessageHandlers(){this.transport.listen(fe,e=>{this.ui&&We(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ve,()=>{this.ui&&$e(this.ui)}),this.transport.listen(be,()=>{this.close()}),this.transport.listen(U,()=>{this.sendPageContext()}),this.transport.listen(ye,()=>{this.pointAndAsk.start()}),this.transport.listen(xe,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(Se,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(we,()=>{this.transport.send(me,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(Te,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Ee,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(Me,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(ke,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ie,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(N,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(D,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(K,()=>{this.clearSessionToken()}),this.transport.listen(_e,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(Ce,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Le,{text:e})})}startIntelligence(e){this.presence||(this.presence=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new F({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ke(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=He(this.key),t=Pe(e,this.explicitContext);this.transport.send(R,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=q();this.transport.send(Ae,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(Oe,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(qe(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&(ze(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Xe(this.ui),this.ui=null}};var c=null,ne={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new j(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&ne.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=ne);
|
package/dist/index.mjs
CHANGED
|
@@ -41,4 +41,4 @@ var Je=Object.defineProperty,Ve=Object.defineProperties;var Qe=Object.getOwnProp
|
|
|
41
41
|
.max-widget-shell .max-widget-frame{height:calc(100% - 18px)}
|
|
42
42
|
`,lt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>';var dt='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>',ct='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/></svg>';function Pe(n){if(!n||n.charAt(0)!=="#")return null;let e=n.replace("#","");return e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),e.length!==6?null:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16)}}function He(n,e){let t=Pe(n);if(!t)return n;let i=Math.max(0,Math.min(255,Math.round(t.r+255*e))),s=Math.max(0,Math.min(255,Math.round(t.g+255*e))),o=Math.max(0,Math.min(255,Math.round(t.b+255*e))),r=a=>{let l=a.toString(16);return l.length===1?"0"+l:l};return"#"+r(i)+r(s)+r(o)}function S(n,e){let t=Pe(n);return t?`rgba(${t.r},${t.g},${t.b},${e})`:`rgba(99,102,241,${e})`}function ht(n){let e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(!e)return"";let t=i=>{let s=i.toString(16);return s.length===1?"0"+s:s};return"#"+t(+e[1])+t(+e[2])+t(+e[3])}function Ue(n,e,t,i){let s=pt(t)||i||"#6366f1",o=[n.btn,n.tab];for(let r of o)if(r)if(r.style.background="",r.style.backgroundColor="",r.style.border="none",r.style.backdropFilter="",r.style.webkitBackdropFilter="",r.style.boxShadow="",e==="glassmorphism")r.style.background="linear-gradient(180deg, rgba(24, 30, 48, 0.56), rgba(10, 14, 24, 0.44))",r.style.border="1px solid rgba(255, 255, 255, 0.18)",r.style.backdropFilter="blur(18px) saturate(180%)",r.style.webkitBackdropFilter="blur(18px) saturate(180%)",r.style.boxShadow="0 14px 34px rgba(0, 0, 0, 0.28)";else if(e==="auto-adaptive"){let a=He(s,.08),l=He(s,-.06);r.style.background=`linear-gradient(180deg, ${S(a,.96)}, ${S(l,.92)})`,r.style.border=`1px solid ${S(s,.24)}`,r.style.boxShadow=`0 12px 30px rgba(0, 0, 0, 0.24), 0 0 0 1px ${S(s,.22)}`}else r.style.background=`linear-gradient(180deg, ${S(s,.55)}, ${S(s,.4)})`,r.style.border=`1px solid ${S(s,.25)}`,r.style.backdropFilter="blur(16px) saturate(160%)",r.style.webkitBackdropFilter="blur(16px) saturate(160%)",r.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)";n.shell&&(n.shell.classList.remove("glassmorphism","auto-adaptive"),e==="glassmorphism"?n.shell.classList.add("glassmorphism"):e==="auto-adaptive"&&n.shell.classList.add("auto-adaptive"))}function pt(n){return n?n.startsWith("#")?n:n.startsWith("rgb")?ht(n):"":""}function De(n,e,t,i,s,o){if(document.querySelector(".max-widget-container"))return null;let r=document.createElement("style");s&&(r.nonce=s),r.textContent=at,document.head.appendChild(r);let a=document.createElement("div");a.className="max-widget-container "+(t?"right":"left"),document.body.appendChild(a);let l=document.createElement("div");l.className="max-widget-shell "+(t?"right":"left"),a.appendChild(l);let h=document.createElement("div");h.className="max-widget-drag-handle",l.appendChild(h);let g=document.createElement("iframe");g.className="max-widget-frame",g.src=n+"/widget/"+e,g.setAttribute("allow","clipboard-write"),g.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),g.setAttribute("allowtransparency","true"),l.appendChild(g);let p=document.createElement("button");p.className="max-widget-btn",p.style.backgroundColor=i,p.innerHTML=lt,a.appendChild(p);let y=!1,m=!1,b=!1,te=0,ne=0,j=0,Y=0;function M(d,u){let v=window.innerWidth-a.offsetWidth,Z=window.innerHeight-a.offsetHeight;a.style.left=Math.max(0,Math.min(v,d))+"px",a.style.top=Math.max(0,Math.min(Z,u))+"px",a.style.bottom="auto",a.style.right="auto"}function ie(){try{localStorage.setItem("max-widget-pos",JSON.stringify({left:parseInt(a.style.left),top:parseInt(a.style.top)}))}catch(d){}J()}function J(){let d=l.offsetHeight||600,u=a.getBoundingClientRect(),v=u.top,Z=window.innerHeight-u.bottom;v<d+8&&Z>=d+8?(l.style.bottom="auto",l.style.top=a.offsetHeight+8+"px"):(l.style.top="auto",l.style.bottom="0")}function je(){try{let d=localStorage.getItem("max-widget-pos");if(!d)return;let{left:u,top:v}=JSON.parse(d);typeof u=="number"&&typeof v=="number"&&M(u,v)}catch(d){}}je(),J(),p.addEventListener("pointerdown",d=>{if(d.button!==0)return;y=!0,m=!1,te=d.clientX,ne=d.clientY;let u=a.getBoundingClientRect();j=u.left,Y=u.top,M(j,Y),p.setPointerCapture(d.pointerId),d.preventDefault()}),p.addEventListener("pointermove",d=>{if(!y)return;let u=d.clientX-te,v=d.clientY-ne;!m&&(Math.abs(u)>4||Math.abs(v)>4)&&(m=!0,p.classList.add("dragging")),m&&M(j+u,Y+v)}),p.addEventListener("pointerup",()=>{y&&(y=!1,p.classList.remove("dragging"),m&&(b=!0,ie(),m=!1))});let C=!1,w=!1,se=0,re=0,V=0,Q=0;h.addEventListener("pointerdown",d=>{if(d.button!==0)return;C=!0,w=!1,se=d.clientX,re=d.clientY;let u=a.getBoundingClientRect();V=u.left,Q=u.top,M(V,Q),h.setPointerCapture(d.pointerId),d.preventDefault()}),h.addEventListener("pointermove",d=>{if(!C)return;let u=d.clientX-se,v=d.clientY-re;!w&&(Math.abs(u)>4||Math.abs(v)>4)&&(w=!0,h.classList.add("dragging")),w&&M(V+u,Q+v)}),h.addEventListener("pointerup",()=>{C&&(C=!1,h.classList.remove("dragging"),w&&(ie(),w=!1))});let x=document.createElement("button");x.className="max-widget-tab "+(t?"right":"left"),x.style.backgroundColor=i,x.innerHTML=t?dt:ct,document.body.appendChild(x);let oe=!1;function Ye(){oe=!1,l.classList.remove("expanded","panel-hidden"),a.classList.remove("panel-expanded","panel-hidden-state"),x.classList.remove("visible"),document.body.style.overflow=""}return p.addEventListener("click",()=>{if(b){b=!1;return}if(oe){Ye();return}l.classList.contains("open")?(l.classList.remove("open"),o.onClose()):(J(),l.classList.add("open"),o.onOpen())}),x.addEventListener("click",()=>{l.classList.remove("panel-hidden"),a.classList.remove("panel-hidden-state"),x.classList.remove("visible")}),{container:a,shell:l,iframe:g,btn:p,tab:x,style:r}}function Ne(n,e,t){let{container:i,shell:s,tab:o}=n;e?(s.classList.contains("open")||s.classList.add("open"),s.classList.add("expanded"),i.classList.add("panel-expanded"),s.classList.remove("panel-hidden"),i.classList.remove("panel-hidden-state"),o.classList.remove("visible"),window.innerWidth<=420&&(document.body.style.overflow="hidden")):(s.classList.remove("expanded","panel-hidden"),i.classList.remove("panel-expanded","panel-hidden-state"),o.classList.remove("visible"),document.body.style.overflow="")}function Ke(n){n.shell.classList.add("panel-hidden"),n.container.classList.add("panel-hidden-state"),n.tab.classList.add("visible")}function Be(n){n.container.remove(),n.tab.remove(),n.style.remove()}function We(n){n.shell.classList.add("open")}function $e(n){n.shell.classList.contains("expanded")&&(n.shell.classList.remove("expanded","panel-hidden"),n.container.classList.remove("panel-expanded","panel-hidden-state"),n.tab.classList.remove("visible"),document.body.style.overflow=""),n.shell.classList.remove("open")}var q=class{constructor(e){this.timer=null;this.tabVisible=!0;this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:!1,input:!1};this.lastInteractionAt=null;this.destroyed=!1;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.intervalMs=(t=e.intervalMs)!=null?t:3e4,this.browserMeta=X(),this.handleVisibility=()=>{this.tabVisible=!document.hidden,this.tabVisible&&this.markInteraction()},this.handleScroll=()=>{this.signals.scroll=!0,this.markInteraction()},this.handleClick=()=>{this.signals.click=!0,this.markInteraction()},this.handleKeydown=()=>{this.signals.input=!0,this.markInteraction()},this.handleBeforeUnload=()=>{this.sendBeacon()}}start(){this.destroyed||(document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("click",this.handleClick),document.addEventListener("keydown",this.handleKeydown),window.addEventListener("beforeunload",this.handleBeforeUnload),this.sendHeartbeat(),this.timer=setInterval(()=>this.sendHeartbeat(),this.intervalMs))}setWidgetOpen(e){this.signals.widgetOpen=e,e&&this.markInteraction()}notifyPageChange(){this.sendHeartbeat()}updateSessionToken(e){this.sessionToken=e}destroy(){this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}markInteraction(){this.lastInteractionAt=Date.now()}buildPayload(){return{visitor_id:this.visitorId,session_token:this.sessionToken,page_url:location.href.slice(0,2048),page_title:(document.title||"").slice(0,512),tab_visible:this.tabVisible,engagement_signals:f({},this.signals),last_interaction_at:this.lastInteractionAt?new Date(this.lastInteractionAt).toISOString():null,browser_meta:this.browserMeta}}resetSignals(){this.signals={scroll:!1,click:!1,focus:!1,widgetOpen:this.signals.widgetOpen,input:!1}}async sendHeartbeat(){if(this.destroyed)return;let e=this.buildPayload();this.resetSignals();try{await fetch(`${this.baseUrl}/api/widget/presence`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(e),keepalive:!0})}catch(t){}}sendBeacon(){if(!this.destroyed)try{let e=this.buildPayload();e.is_unload=!0,navigator.sendBeacon(`${this.baseUrl}/api/widget/presence`,new Blob([JSON.stringify(L(f({},e),{_key:this.widgetKey}))],{type:"application/json"}))}catch(e){}}};var z=class{constructor(e){this.buffer=[];this.flushTimer=null;this.destroyed=!1;this.scrollMilestones=new Set;this.maxScrollDepth=0;this.clickTimestamps=[];this.lastClickX=0;this.lastClickY=0;this.firstCharRecorded=!1;this.widgetImpressed=!1;this.impressionObserver=null;var t;this.baseUrl=e.baseUrl,this.widgetKey=e.widgetKey,this.visitorId=e.visitorId,this.sessionToken=e.sessionToken,this.consentLevel=e.consentLevel,this.flushIntervalMs=(t=e.flushIntervalMs)!=null?t:1e4,this.handleScroll=this.onScroll.bind(this),this.handleClick=this.onClick.bind(this),this.handleCopy=this.onCopy.bind(this),this.handleKeydown=this.onKeydown.bind(this),this.handleBeforeUnload=()=>this.flush(!0)}start(){this.destroyed||(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.consentLevel==="behavioral"&&this.attachBehavioralListeners(),document.addEventListener("click",this.handleClick),window.addEventListener("beforeunload",this.handleBeforeUnload),this.flushTimer=setInterval(()=>this.flush(!1),this.flushIntervalMs))}upgradeConsent(e){e==="behavioral"&&this.consentLevel==="basic"&&(this.consentLevel=e,this.attachBehavioralListeners())}trackWidgetOpen(){this.push({type:"widget_open",data:{},ts:Date.now()})}trackWidgetClose(){this.push({type:"widget_close",data:{},ts:Date.now()})}observeWidgetButton(e){if(!(this.widgetImpressed||this.destroyed))try{this.impressionObserver=new IntersectionObserver(t=>{var i;for(let s of t)s.isIntersecting&&!this.widgetImpressed&&(this.widgetImpressed=!0,this.push({type:"widget_impression",data:{},ts:Date.now()}),(i=this.impressionObserver)==null||i.disconnect())},{threshold:.5}),this.impressionObserver.observe(e)}catch(t){}}updateSessionToken(e){this.sessionToken=e}resetForNavigation(){this.flush(!1),this.scrollMilestones.clear(),this.maxScrollDepth=0,this.firstCharRecorded=!1,this.widgetImpressed=!1,this.clickTimestamps=[]}destroy(){var e;this.destroyed=!0,this.flush(!0),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),(e=this.impressionObserver)==null||e.disconnect(),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("click",this.handleClick),document.removeEventListener("copy",this.handleCopy),document.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("beforeunload",this.handleBeforeUnload)}attachBehavioralListeners(){document.addEventListener("copy",this.handleCopy),document.addEventListener("keydown",this.handleKeydown)}push(e){this.destroyed||(this.buffer.push(e),this.buffer.length>=50&&this.flush(!1))}onScroll(){let e=document.documentElement.scrollHeight-window.innerHeight;if(e<=0)return;let t=Math.round(window.scrollY/e*100);this.maxScrollDepth=Math.max(this.maxScrollDepth,t);for(let i of[25,50,75,100])t>=i&&!this.scrollMilestones.has(i)&&(this.scrollMilestones.add(i),this.push({type:"scroll_milestone",data:{depth:i},ts:Date.now()}))}onClick(e){if(this.consentLevel!=="behavioral")return;let t=e.target;t&&!this.isInteractive(t)&&this.push({type:"dead_click",data:{tag:t.tagName.toLowerCase(),text:(t.textContent||"").slice(0,50)},ts:Date.now()});let i=Date.now(),s=Math.abs(e.clientX-this.lastClickX),o=Math.abs(e.clientY-this.lastClickY);if(s<100&&o<100?(this.clickTimestamps.push(i),this.clickTimestamps=this.clickTimestamps.filter(r=>i-r<500),this.clickTimestamps.length>=3&&(this.push({type:"rage_click",data:{count:this.clickTimestamps.length},ts:i}),this.clickTimestamps=[])):this.clickTimestamps=[i],this.lastClickX=e.clientX,this.lastClickY=e.clientY,t.closest("a")){let r=t.closest("a");r.href&&r.hostname!==location.hostname&&this.push({type:"outbound_link",data:{href:r.href.slice(0,512)},ts:i})}}onCopy(){this.consentLevel==="behavioral"&&this.push({type:"copy_event",data:{},ts:Date.now()})}onKeydown(e){if(this.consentLevel!=="behavioral"||this.firstCharRecorded)return;let t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)&&e.key.length===1&&(this.firstCharRecorded=!0,this.push({type:"first_typed_char",data:{element:t.tagName.toLowerCase()},ts:Date.now()}))}isInteractive(e){let t=e.tagName.toLowerCase();return!!(["a","button","input","select","textarea","label"].includes(t)||e.getAttribute("role")==="button"||e.getAttribute("tabindex")||e.onclick||e.getAttribute("data-action"))}async flush(e){if(this.buffer.length===0)return;let t=this.buffer.splice(0),i={visitor_id:this.visitorId,session_token:this.sessionToken,consent_level:this.consentLevel,page_url:location.href.slice(0,2048),scroll_depth:this.maxScrollDepth,events:t};if(e){try{navigator.sendBeacon(`${this.baseUrl}/api/widget/events`,new Blob([JSON.stringify(L(f({},i),{_key:this.widgetKey}))],{type:"application/json"}))}catch(s){}return}try{await fetch(`${this.baseUrl}/api/widget/events`,{method:"POST",headers:{"Content-Type":"application/json","X-Widget-Key":this.widgetKey},body:JSON.stringify(i),keepalive:!0})}catch(s){this.buffer.unshift(...t)}}};function Xe(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function ut(n){var s,o;let e=[],t=n.previousElementSibling,i=5;for(;t&&i-- >0;){if(t.tagName&&!t.classList.contains("maxai-inline")){let r=(s=t.innerText)==null?void 0:s.trim();r&&e.unshift(r)}t=t.previousElementSibling}if(e.join(" ").length<100&&n.parentElement){let r="",a=n.parentElement.children;for(let l=0;l<a.length&&a[l]!==n;l++)if(!a[l].classList.contains("maxai-inline")){let h=(o=a[l].innerText)==null?void 0:o.trim();h&&(r+=h+`
|
|
43
43
|
`)}if(r.length>e.join(" ").length)return Xe(r.trim(),3e3)}return Xe(e.join(`
|
|
44
|
-
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(H,{features:e.config}),o()}),s.listen(D,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(U,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(N,()=>{}),s.listen(P,()=>{o()}),n.appendChild(i);function o(){let a=ut(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(A,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function qe(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function ze(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var F=class{constructor(e){this.emitter=new O;this.debug=new B;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new K(this.transport),this.pointAndAsk=new W(this.transport),this.spaDetector=new $(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=De(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(H,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=qe(t),this.inlineObserver=ze(t)}setupMessageHandlers(){this.transport.listen(ue,e=>{this.ui&&Ne(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ge,()=>{this.ui&&Ke(this.ui)}),this.transport.listen(me,()=>{this.close()}),this.transport.listen(P,()=>{this.sendPageContext()}),this.transport.listen(fe,()=>{this.pointAndAsk.start()}),this.transport.listen(ve,()=>{this.pointAndAsk.stop()}),this.transport.listen(be,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(ye,()=>{this.transport.send(pe,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(xe,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Se,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(we,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(Te,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ee,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(D,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(U,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(N,()=>{this.clearSessionToken()}),this.transport.listen(Me,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(ke,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Ie,{text:e})})}startIntelligence(e){this.presence||(this.presence=new q({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ue(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=Ae(this.key),t=Re(e,this.explicitContext);this.transport.send(A,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=X();this.transport.send(Ce,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(_e,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(We(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&($e(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Be(this.ui),this.ui=null}};var c=null,Fe={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new F(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&Fe.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=Fe);export{Fe as MaxAI};
|
|
44
|
+
`),3e3)}function _(n,e){if(n._maxaiMounted)return null;n._maxaiMounted=!0;let t=n.getAttribute("data-key")||e.key;if(!t)return console.warn("[MaxAI SDK] Inline mount skipped: no data-key and no global key"),null;console.log("[MaxAI SDK] Mounting inline widget",{key:t.slice(0,8)+"...",container:n}),n.style.position||(n.style.position="relative"),n.style.overflow="hidden",n.style.minHeight||(n.style.minHeight="300px");let i=document.createElement("iframe");i.style.display="block",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.background="transparent",i.style.borderRadius="inherit",i.setAttribute("allow","clipboard-write"),i.setAttribute("sandbox","allow-same-origin allow-scripts allow-popups allow-forms"),i.setAttribute("allowtransparency","true"),i.src=`${e.baseUrl}/widget/${t}?inline=true`;let s=new T(e.baseUrl);s.attach(i),i.addEventListener("load",()=>{s.markReady(),e.config&&s.send(H,{features:e.config}),o()}),s.listen(D,()=>{s.send(I,{visitorId:e.visitorId,sessionToken:e.sessionToken})}),s.listen(U,a=>{a.sessionToken&&e.onSessionUpdate(a.sessionToken)}),s.listen(N,()=>{}),s.listen(P,()=>{o()}),n.appendChild(i);function o(){let a=ut(n),l={url:window.location.href,title:document.title||"",mainContent:a,customContext:{inline_mode:"true",content_above:a},lang:document.documentElement.lang||""},h=n.attributes;for(let g=0;g<h.length;g++){let p=h[g].name;if(p.startsWith("data-context-")){let y=p.replace("data-context-","").replace(/-/g,"_");l.customContext||(l.customContext={}),l.customContext[y]=h[g].value}}s.send(A,{context:l})}function r(){s.destroy(),i.remove(),n._maxaiMounted=!1}return{container:n,iframe:i,transport:s,destroy:r}}function qe(n){let e=document.querySelectorAll(".maxai-inline");console.log("[MaxAI SDK] Scanning for .maxai-inline elements:",e.length,"found");let t=[];return e.forEach(i=>{let s=_(i,n);s&&t.push(s)}),t}function ze(n){if(typeof MutationObserver=="undefined")return null;let e=new MutationObserver(t=>{var i;for(let s of t)for(let o of Array.from(s.addedNodes)){if(o.nodeType!==1)continue;let r=o;if((i=r.classList)!=null&&i.contains("maxai-inline")&&(console.log("[MaxAI SDK] MutationObserver: detected .maxai-inline",r),_(r,n)),r.querySelectorAll){let a=r.querySelectorAll(".maxai-inline");a.length>0&&console.log("[MaxAI SDK] MutationObserver: found",a.length,".maxai-inline in descendants"),a.forEach(l=>_(l,n))}}});return e.observe(document.body,{childList:!0,subtree:!0}),e}var F=class{constructor(e){this.emitter=new O;this.debug=new B;this.ui=null;this.explicitContext=null;this.consentGiven=!1;this.config=null;this.primaryColor="#6366f1";this.presence=null;this.behavioralTracker=null;this.inlineInstances=[];this.inlineObserver=null;this.storedSessionToken=null;this.storedIdentity=null;this.key=e.key,this.isRight=e.position!=="bottom-left",this.nonce=e.nonce||null;let t=document.querySelector(`script[data-key="${e.key}"]`);t&&t.src?this.baseUrl=t.src.replace(/\/(widget-embed\.js|sdk\.js).*$/,""):e.baseUrl?this.baseUrl=e.baseUrl:this.baseUrl="https://maxaiagent.app",this.visitorId=this.readOrCreateVisitorId(),this.storedSessionToken=this.readSessionToken(),this.storedIdentity=this.readStoredIdentity(),this.transport=new T(this.baseUrl),this.tools=new K(this.transport),this.pointAndAsk=new W(this.transport),this.spaDetector=new $(()=>{var i,s,o;if(this.sendPageContext(),(i=this.config)!=null&&i.autoTheme&&this.ui){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}(s=this.presence)==null||s.notifyPageChange(),(o=this.behavioralTracker)==null||o.resetForNavigation()}),this.init()}readOrCreateVisitorId(){let e=`maxai_vid_${this.key}`;try{let i=localStorage.getItem(e);if(i)return i}catch(i){}let t=this.getCookie(e);if(t){try{localStorage.setItem(e,t)}catch(i){}return t}return this.generateUUID()}persistVisitorId(e){let t=`maxai_vid_${this.key}`;try{localStorage.setItem(t,e)}catch(i){}this.setCookie(t,e,30)}readSessionToken(){try{return localStorage.getItem(`maxai_st_${this.key}`)}catch(e){}return null}saveSessionToken(e){this.storedSessionToken=e;try{localStorage.setItem(`maxai_st_${this.key}`,e)}catch(t){}}clearSessionToken(){this.storedSessionToken=null;try{localStorage.removeItem(`maxai_st_${this.key}`)}catch(e){}}readStoredIdentity(){try{let e=localStorage.getItem(`maxai_identity_${this.key}`);if(e)return JSON.parse(e)}catch(e){}return null}saveIdentity(e){this.storedIdentity=e;try{localStorage.setItem(`maxai_identity_${this.key}`,JSON.stringify(e))}catch(t){}}generateUUID(){return typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}setCookie(e,t,i){try{let s=new Date;s.setTime(s.getTime()+i*864e5),document.cookie=`${e}=${t};expires=${s.toUTCString()};path=/;SameSite=Lax;Secure`}catch(s){}}getCookie(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?t[1]:null}catch(t){return null}}async fetchWithRetry(e,t=3,i=1e3){for(let s=0;s<t;s++)try{let o=await fetch(e);if(o.ok)return o;s<t-1&&await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}catch(o){if(s===t-1)throw new Error(`Failed to fetch ${e} after ${t} attempts`);await new Promise(r=>setTimeout(r,i*Math.pow(2,s)))}throw new Error(`Failed to fetch ${e}`)}async init(){let e;try{e=await(await this.fetchWithRetry(`${this.baseUrl}/api/widget/config/${this.key}`)).json()}catch(i){e={}}if(this.config={pageContext:e.enable_page_context||!1,pointAndAsk:e.enable_point_and_ask||!1,debugMode:e.enable_debug_mode||!1,bugReport:e.enable_bug_reports||!1,clientTools:e.enable_client_tools||!1,autoTheme:e.theme_mode!=="manual",themeMode:e.theme_mode||"manual",gdprRequired:e.gdpr_consent_required||!1},(!this.config.gdprRequired||this.consentGiven)&&this.persistVisitorId(this.visitorId),this.config.pageContext&&this.spaDetector.start(),(!this.config.gdprRequired||this.consentGiven)&&this.startIntelligence("basic"),this.config.debugMode&&(!this.config.gdprRequired||this.consentGiven)&&this.debug.init(),this.primaryColor=e.primary_color||"#6366f1",this.ui=De(this.baseUrl,this.key,this.isRight,this.primaryColor,this.nonce,{onOpen:()=>this.emitter.emit("open"),onClose:()=>this.emitter.emit("close")}),!this.ui)return;this.applyTheme(this.config.autoTheme?E().primaryColor:void 0),this.transport.attach(this.ui.iframe),this.ui.iframe.addEventListener("load",()=>{var i,s,o;if(this.transport.markReady(),this.config&&this.transport.send(H,{features:this.config}),(!((i=this.config)!=null&&i.gdprRequired)||this.consentGiven)&&(this.sendPageContext(),this.sendBrowserMetadata(),(s=this.config)!=null&&s.autoTheme)){let r=E();this.applyTheme(r.primaryColor),this.transport.send(k,{styles:r})}this.tools.hasTools()&&this.tools.sendList(),this.emitter.emit("ready"),(o=this.ui)!=null&&o.button&&this.behavioralTracker&&this.behavioralTracker.observeWidgetButton(this.ui.button)}),this.setupMessageHandlers();let t=this.getInlineMountContext();this.inlineInstances=qe(t),this.inlineObserver=ze(t)}setupMessageHandlers(){this.transport.listen(ue,e=>{this.ui&&Ne(this.ui,!!e.expanded,this.isRight)}),this.transport.listen(ge,()=>{this.ui&&Ke(this.ui)}),this.transport.listen(me,()=>{this.close()}),this.transport.listen(P,()=>{this.sendPageContext()}),this.transport.listen(fe,()=>{this.pointAndAsk.start()}),this.transport.listen(ve,()=>{this.pointAndAsk.stop()}),this.transport.listen("max-widget:request-tools",()=>{this.tools.hasTools()&&this.tools.sendList()}),this.transport.listen(be,e=>{let t=e.toolCallId,i=e.slug||e.name,s=e.args;this.emitter.emit("tool:call",{id:t,name:i,args:s}),this.tools.execute(t,i,s).then(o=>{this.emitter.emit("tool:result",{id:t,name:i,ok:o.ok,error:o.error})})}),this.transport.listen(ye,()=>{this.transport.send(pe,{snapshot:this.debug.getSnapshot()})}),this.transport.listen(xe,()=>{let e=E();this.applyTheme(e.primaryColor),this.transport.send(k,{styles:e})}),this.transport.listen(Se,()=>{var e,t,i;if(this.consentGiven=!0,this.persistVisitorId(this.visitorId),this.sendPageContext(),this.sendBrowserMetadata(),(e=this.config)!=null&&e.debugMode&&this.debug.init(),(t=this.config)!=null&&t.autoTheme){let s=E();this.applyTheme(s.primaryColor),this.transport.send(k,{styles:s})}this.presence?(i=this.behavioralTracker)==null||i.upgradeConsent("behavioral"):this.startIntelligence("behavioral")}),this.transport.listen(we,e=>{if(e.url)try{window.location.href=e.url}catch(t){}}),this.transport.listen(Te,e=>{this.emitter.emit("message",e.message)}),this.transport.listen(Ee,e=>{this.emitter.emit("error",{message:e.error})}),this.transport.listen(D,()=>{this.transport.send(I,{visitorId:this.visitorId,sessionToken:this.storedSessionToken,identityPayload:this.storedIdentity||void 0})}),this.transport.listen(U,e=>{var t,i;e.sessionToken&&(this.saveSessionToken(e.sessionToken),(t=this.presence)==null||t.updateSessionToken(e.sessionToken),(i=this.behavioralTracker)==null||i.updateSessionToken(e.sessionToken))}),this.transport.listen(N,()=>{this.clearSessionToken()}),this.transport.listen(Me,e=>{try{localStorage.setItem(`maxai_draft_${this.key}`,e.text||"")}catch(t){}}),this.transport.listen(ke,()=>{let e="";try{e=localStorage.getItem(`maxai_draft_${this.key}`)||""}catch(t){}this.transport.send(Ie,{text:e})})}startIntelligence(e){this.presence||(this.presence=new q({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken}),this.presence.start(),this.behavioralTracker=new z({baseUrl:this.baseUrl,widgetKey:this.key,visitorId:this.visitorId,sessionToken:this.storedSessionToken,consentLevel:e}),this.behavioralTracker.start())}applyTheme(e){!this.ui||!this.config||Ue(this.ui,this.config.themeMode,e,this.primaryColor)}sendPageContext(){var i;if(!this.consentGiven&&((i=this.config)!=null&&i.gdprRequired))return;let e=Ae(this.key),t=Re(e,this.explicitContext);this.transport.send(A,{context:t})}sendBrowserMetadata(){var t;if(!this.consentGiven&&((t=this.config)!=null&&t.gdprRequired))return;let e=X();this.transport.send(Ce,{metadata:e})}getInlineMountContext(){return{baseUrl:this.baseUrl,key:this.key,config:this.config,visitorId:this.visitorId,sessionToken:this.storedSessionToken,onSessionUpdate:e=>{this.saveSessionToken(e),this.transport.send(I,{visitorId:this.visitorId,sessionToken:e})}}}mountInline(e){let t=typeof e=="string"?document.querySelector(e):e;if(!t)return console.error("[MaxAI SDK] mountInline: target not found"),null;let i=_(t,this.getInlineMountContext());return i&&this.inlineInstances.push(i),i}setPageContext(e){this.explicitContext=e,this.sendPageContext()}setIdentity(e){this.saveIdentity(e),this.transport.send(_e,{identityPayload:e})}registerTool(e){return this.tools.register(e)}unregisterTool(e){this.tools.unregister(e)}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}open(){var e,t;this.ui&&(We(this.ui),this.emitter.emit("open"),(e=this.presence)==null||e.setWidgetOpen(!0),(t=this.behavioralTracker)==null||t.trackWidgetOpen())}close(){var e,t;this.ui&&($e(this.ui),this.emitter.emit("close"),(e=this.presence)==null||e.setWidgetOpen(!1),(t=this.behavioralTracker)==null||t.trackWidgetClose())}destroy(){var e,t,i;(e=this.presence)==null||e.destroy(),(t=this.behavioralTracker)==null||t.destroy(),this.spaDetector.destroy(),this.debug.destroy(),this.tools.destroy(),this.transport.destroy(),this.emitter.removeAll(),(i=this.inlineObserver)==null||i.disconnect(),this.inlineObserver=null;for(let s of this.inlineInstances)s.destroy();this.inlineInstances=[],this.ui&&Be(this.ui),this.ui=null}};var c=null,Fe={init(n){return c?(console.warn("[MaxAI SDK] Already initialized. Call destroy() first to reinitialize."),c):(c=new F(n),c)},setPageContext(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setPageContext(n)},setIdentity(n){if(!c){console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first.");return}c.setIdentity(n)},registerTool(n){return c?c.registerTool(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),()=>{})},unregisterTool(n){c&&c.unregisterTool(n)},on(n,e){return c?c.on(n,e):(console.warn("[MaxAI SDK] Not initialized."),()=>{})},mountInline(n){return c?c.mountInline(n):(console.warn("[MaxAI SDK] Not initialized. Call MaxAI.init() first."),null)},open(){c==null||c.open()},close(){c==null||c.close()},destroy(){c==null||c.destroy(),c=null},_initialized:!1};if(typeof document!="undefined"){let n=document.currentScript;if(n){let e=n.getAttribute("data-key");e&&Fe.init({key:e,position:n.getAttribute("data-position")||"bottom-right",nonce:n.getAttribute("data-nonce")||void 0,lazy:n.getAttribute("data-lazy")==="true",baseUrl:n.src?n.src.replace(/\/(sdk|widget-embed)\.js.*$/,""):void 0})}}typeof window!="undefined"&&(window.MaxAI=Fe);export{Fe as MaxAI};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxaiagent/widget-sdk",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"description": "MaxAI Widget SDK — embed AI chat with page context, client-side tools, and event system",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -12,20 +12,12 @@
|
|
|
12
12
|
"require": "./dist/index.js"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist"
|
|
17
|
-
],
|
|
15
|
+
"files": ["dist"],
|
|
18
16
|
"scripts": {
|
|
19
17
|
"build": "tsup",
|
|
20
18
|
"postbuild": "cp dist/index.global.js ../../public/sdk.js"
|
|
21
19
|
},
|
|
22
|
-
"keywords": [
|
|
23
|
-
"maxai",
|
|
24
|
-
"widget",
|
|
25
|
-
"chat",
|
|
26
|
-
"ai",
|
|
27
|
-
"sdk"
|
|
28
|
-
],
|
|
20
|
+
"keywords": ["maxai", "widget", "chat", "ai", "sdk"],
|
|
29
21
|
"license": "MIT",
|
|
30
22
|
"devDependencies": {
|
|
31
23
|
"tsup": "^8.0.0",
|