UNPKG

@paperlinkai/chat

Version:

PaperLink AI Chat Widget - Easy integration for any website

1 lines 75.4 kB
var __defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,n)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))__hasOwnProp.call(t,n)&&__defNormalProp(e,n,t[n]);if(__getOwnPropSymbols)for(var n of __getOwnPropSymbols(t))__propIsEnum.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__objRest=(e,t)=>{var n={};for(var o in e)__hasOwnProp.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&__getOwnPropSymbols)for(var o of __getOwnPropSymbols(e))t.indexOf(o)<0&&__propIsEnum.call(e,o)&&(n[o]=e[o]);return n},__publicField=(e,t,n)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,n),__async=(e,t,n)=>new Promise((o,i)=>{var s=e=>{try{a(n.next(e))}catch(t){i(t)}},r=e=>{try{a(n.throw(e))}catch(t){i(t)}},a=e=>e.done?o(e.value):Promise.resolve(e.value).then(s,r);a((n=n.apply(e,t)).next())});this.PaperlinkChat=function(){"use strict";var e,t,n,o,i,s,r,a,l,c,d,h={},u=[],p=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function m(e,t){for(var n in t)e[n]=t[n];return e}function f(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function _(e,o,i,s,r){var a={type:e,props:o,key:i,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++n:r,__i:-1,__u:0};return null==r&&null!=t.vnode&&t.vnode(a),a}function b(e){return e.children}function y(e,t){this.props=e,this.context=t}function w(e,t){if(null==t)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?w(e):null}function x(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return x(e)}}function v(e){(!e.__d&&(e.__d=!0)&&o.push(e)&&!k.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||s)(k)}function k(){for(var e,n,i,s,a,l,c,d=1;o.length;)o.length>d&&o.sort(r),e=o.shift(),d=o.length,e.__d&&(i=void 0,a=(s=(n=e).__v).__e,l=[],c=[],n.__P&&((i=m({},s)).__v=s.__v+1,t.vnode&&t.vnode(i),T(n.__P,i,s,n.__n,n.__P.namespaceURI,32&s.__u?[a]:null,l,null==a?w(s):a,!!(32&s.__u),c),i.__v=s.__v,i.__.__k[i.__i]=i,R(l,i,c),i.__e!=a&&x(i)));k.__r=0}function S(e,t,n,o,i,s,r,a,l,c,d){var p,m,f,y,x,v,k=o&&o.__k||u,S=t.length;for(l=function(e,t,n,o,i){var s,r,a,l,c,d=n.length,h=d,u=0;for(e.__k=new Array(i),s=0;s<i;s++)null!=(r=t[s])&&"boolean"!=typeof r&&"function"!=typeof r?(l=s+u,(r=e.__k[s]="string"==typeof r||"number"==typeof r||"bigint"==typeof r||r.constructor==String?_(null,r,null,null,null):g(r)?_(b,{children:r},null,null,null):null==r.constructor&&r.__b>0?_(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=e,r.__b=e.__b+1,a=null,-1!=(c=r.__i=I(r,n,l,h))&&(h--,(a=n[c])&&(a.__u|=2)),null==a||null==a.__v?(-1==c&&(i>d?u--:i<d&&u++),"function"!=typeof r.type&&(r.__u|=4)):c!=l&&(c==l-1?u--:c==l+1?u++:(c>l?u--:u++,r.__u|=4))):e.__k[s]=null;if(h)for(s=0;s<d;s++)null!=(a=n[s])&&!(2&a.__u)&&(a.__e==o&&(o=w(a)),N(a,a));return o}(n,t,k,l,S),p=0;p<S;p++)null!=(f=n.__k[p])&&(m=-1==f.__i?h:k[f.__i]||h,f.__i=p,v=T(e,f,m,i,s,r,a,l,c,d),y=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&P(m.ref,null,f),d.push(f.ref,f.__c||y,f)),null==x&&null!=y&&(x=y),4&f.__u||m.__k===f.__k?l=C(f,l,e):"function"==typeof f.type&&void 0!==v?l=v:y&&(l=y.nextSibling),f.__u&=-7);return n.__e=x,l}function C(e,t,n){var o,i;if("function"==typeof e.type){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=C(o[i],t,n));return t}e.__e!=t&&(t&&e.type&&!n.contains(t)&&(t=w(e)),n.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function I(e,t,n,o){var i,s,r,a=e.key,l=e.type,c=t[n],d=null!=c&&!(2&c.__u);if(null===c&&null==e.key||d&&a==c.key&&l==c.type)return n;if(o>(d?1:0))for(i=n-1,s=n+1;i>=0||s<t.length;)if(null!=(c=t[r=i>=0?i--:s++])&&!(2&c.__u)&&a==c.key&&l==c.type)return r;return-1}function M(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||p.test(t)?n:n+"px"}function z(e,t,n,o,i){var s,r;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof o&&(e.style.cssText=o=""),o)for(t in o)n&&t in n||M(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||M(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(a,"$1")),r=t.toLowerCase(),t=r in e||"onFocusOut"==t||"onFocusIn"==t?r.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?o?n.u=o.u:(n.u=l,e.addEventListener(t,s?d:c,s)):e.removeEventListener(t,s?d:c,s);else{if("http://www.w3.org/2000/svg"==i)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(h){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function E(e){return function(n){if(this.l){var o=this.l[n.type+e];if(null==n.t)n.t=l++;else if(n.t<o.u)return;return o(t.event?t.event(n):n)}}}function T(n,o,i,s,r,a,l,c,d,u){var p,_,x,v,k,C,I,M,E,T,R,P,N,F,D,O,U,W=o.type;if(null!=o.constructor)return null;128&i.__u&&(d=!!(32&i.__u),a=[c=o.__e=i.__e]),(p=t.__b)&&p(o);e:if("function"==typeof W)try{if(M=o.props,E="prototype"in W&&W.prototype.render,T=(p=W.contextType)&&s[p.__c],R=p?T?T.props.value:p.__:s,i.__c?I=(_=o.__c=i.__c).__=_.__E:(E?o.__c=_=new W(M,R):(o.__c=_=new y(M,R),_.constructor=W,_.render=$),T&&T.sub(_),_.props=M,_.state||(_.state={}),_.context=R,_.__n=s,x=_.__d=!0,_.__h=[],_._sb=[]),E&&null==_.__s&&(_.__s=_.state),E&&null!=W.getDerivedStateFromProps&&(_.__s==_.state&&(_.__s=m({},_.__s)),m(_.__s,W.getDerivedStateFromProps(M,_.__s))),v=_.props,k=_.state,_.__v=o,x)E&&null==W.getDerivedStateFromProps&&null!=_.componentWillMount&&_.componentWillMount(),E&&null!=_.componentDidMount&&_.__h.push(_.componentDidMount);else{if(E&&null==W.getDerivedStateFromProps&&M!==v&&null!=_.componentWillReceiveProps&&_.componentWillReceiveProps(M,R),!_.__e&&null!=_.shouldComponentUpdate&&!1===_.shouldComponentUpdate(M,_.__s,R)||o.__v==i.__v){for(o.__v!=i.__v&&(_.props=M,_.state=_.__s,_.__d=!1),o.__e=i.__e,o.__k=i.__k,o.__k.some(function(e){e&&(e.__=o)}),P=0;P<_._sb.length;P++)_.__h.push(_._sb[P]);_._sb=[],_.__h.length&&l.push(_);break e}null!=_.componentWillUpdate&&_.componentWillUpdate(M,_.__s,R),E&&null!=_.componentDidUpdate&&_.__h.push(function(){_.componentDidUpdate(v,k,C)})}if(_.context=R,_.props=M,_.__P=n,_.__e=!1,N=t.__r,F=0,E){for(_.state=_.__s,_.__d=!1,N&&N(o),p=_.render(_.props,_.state,_.context),D=0;D<_._sb.length;D++)_.__h.push(_._sb[D]);_._sb=[]}else do{_.__d=!1,N&&N(o),p=_.render(_.props,_.state,_.context),_.state=_.__s}while(_.__d&&++F<25);_.state=_.__s,null!=_.getChildContext&&(s=m(m({},s),_.getChildContext())),E&&!x&&null!=_.getSnapshotBeforeUpdate&&(C=_.getSnapshotBeforeUpdate(v,k)),O=p,null!=p&&p.type===b&&null==p.key&&(O=B(p.props.children)),c=S(n,g(O)?O:[O],o,i,s,r,a,l,c,d,u),_.base=o.__e,o.__u&=-161,_.__h.length&&l.push(_),I&&(_.__E=_.__=null)}catch(H){if(o.__v=null,d||null!=a)if(H.then){for(o.__u|=d?160:128;c&&8==c.nodeType&&c.nextSibling;)c=c.nextSibling;a[a.indexOf(c)]=null,o.__e=c}else{for(U=a.length;U--;)f(a[U]);L(o)}else o.__e=i.__e,o.__k=i.__k,H.then||L(o);t.__e(H,o,i)}else null==a&&o.__v==i.__v?(o.__k=i.__k,o.__e=i.__e):c=o.__e=function(n,o,i,s,r,a,l,c,d){var u,p,m,_,b,y,x,v=i.props,k=o.props,C=o.type;if("svg"==C?r="http://www.w3.org/2000/svg":"math"==C?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=a)for(u=0;u<a.length;u++)if((b=a[u])&&"setAttribute"in b==!!C&&(C?b.localName==C:3==b.nodeType)){n=b,a[u]=null;break}if(null==n){if(null==C)return document.createTextNode(k);n=document.createElementNS(r,C,k.is&&k),c&&(t.__m&&t.__m(o,a),c=!1),a=null}if(null==C)v===k||c&&n.data==k||(n.data=k);else{if(a=a&&e.call(n.childNodes),v=i.props||h,!c&&null!=a)for(v={},u=0;u<n.attributes.length;u++)v[(b=n.attributes[u]).name]=b.value;for(u in v)if(b=v[u],"children"==u);else if("dangerouslySetInnerHTML"==u)m=b;else if(!(u in k)){if("value"==u&&"defaultValue"in k||"checked"==u&&"defaultChecked"in k)continue;z(n,u,null,b,r)}for(u in k)b=k[u],"children"==u?_=b:"dangerouslySetInnerHTML"==u?p=b:"value"==u?y=b:"checked"==u?x=b:c&&"function"!=typeof b||v[u]===b||z(n,u,b,v[u],r);if(p)c||m&&(p.__html==m.__html||p.__html==n.innerHTML)||(n.innerHTML=p.__html),o.__k=[];else if(m&&(n.innerHTML=""),S("template"==o.type?n.content:n,g(_)?_:[_],o,i,s,"foreignObject"==C?"http://www.w3.org/1999/xhtml":r,a,l,a?a[0]:i.__k&&w(i,0),c,d),null!=a)for(u=a.length;u--;)f(a[u]);c||(u="value","progress"==C&&null==y?n.removeAttribute("value"):null!=y&&(y!==n[u]||"progress"==C&&!y||"option"==C&&y!=v[u])&&z(n,u,y,v[u],r),u="checked",null!=x&&x!=n[u]&&z(n,u,x,v[u],r))}return n}(i.__e,o,i,s,r,a,l,d,u);return(p=t.diffed)&&p(o),128&o.__u?void 0:c}function L(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(L)}function R(e,n,o){for(var i=0;i<o.length;i++)P(o[i],o[++i],o[++i]);t.__c&&t.__c(n,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(e){e.call(n)})}catch(o){t.__e(o,n.__v)}})}function B(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:g(e)?e.map(B):m({},e)}function P(e,n,o){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==n||(e.__u=e(n))}else e.current=n}catch(s){t.__e(s,o)}}function N(e,n,o){var i,s;if(t.unmount&&t.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||P(i,null,n)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){t.__e(r,n)}i.base=i.__P=null}if(i=e.__k)for(s=0;s<i.length;s++)i[s]&&N(i[s],n,o||"function"!=typeof e.type);o||f(e.__e),e.__c=e.__=e.__e=void 0}function $(e,t,n){return this.constructor(e,n)}function F(n,o,i){var s,r,a;o==document&&(o=document.documentElement),t.__&&t.__(n,o),s=!1?null:o.__k,r=[],a=[],T(o,n=o.__k=function(t,n,o){var i,s,r,a={};for(r in n)"key"==r?i=n[r]:"ref"==r?s=n[r]:a[r]=n[r];if(arguments.length>2&&(a.children=arguments.length>3?e.call(arguments,2):o),"function"==typeof t&&null!=t.defaultProps)for(r in t.defaultProps)void 0===a[r]&&(a[r]=t.defaultProps[r]);return _(t,a,i,s,null)}(b,null,[n]),s||h,h,o.namespaceURI,s?null:o.firstChild?e.call(o.childNodes):null,r,s?s.__e:o.firstChild,false,a),R(r,n,a)}e=u.slice,t={__e:function(e,t,n,o){for(var i,s,r;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&null!=s.getDerivedStateFromError&&(i.setState(s.getDerivedStateFromError(e)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,o||{}),r=i.__d),r)return i.__E=i}catch(a){e=a}throw e}},n=0,y.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),"function"==typeof e&&(e=e(m({},n),this.props)),e&&m(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),v(this))},y.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),v(this))},y.prototype.render=b,o=[],s="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,r=function(e,t){return e.__v.__b-t.__v.__b},k.__r=0,a=/(PointerCapture)$|Capture$/i,l=0,c=E(!1),d=E(!0);var D=0;function O(e,n,o,i,s,r){n||(n={});var a,l,c=n;if("ref"in c)for(l in c={},n)"ref"==l?a=n[l]:c[l]=n[l];var d={type:e,props:c,key:o,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--D,__i:-1,__u:0,__source:s,__self:r};if("function"==typeof e&&(a=e.defaultProps))for(l in a)void 0===c[l]&&(c[l]=a[l]);return t.vnode&&t.vnode(d),d}var U=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(U||{});const W=new class{constructor(){__publicField(this,"logLevel",1),__publicField(this,"prefix","[PaperlinkWidget]")}setLevel(e){this.logLevel=e}log(e,t,...n){if(e<this.logLevel||"undefined"==typeof console)return;const o=(new Date).toISOString(),i=U[e],s=`${this.prefix} [${o}] ${i}: ${t}`;switch(e){case 0:console.debug(s,...n);break;case 1:console.info(s,...n);break;case 2:console.warn(s,...n);break;case 3:console.error(s,...n)}}debug(e,...t){this.log(0,e,...t)}info(e,...t){this.log(1,e,...t)}warn(e,...t){this.log(2,e,...t)}error(e,...t){this.log(3,e,...t)}group(e){this.logLevel<=0&&"undefined"!=typeof console&&console.group(`${this.prefix} ${e}`)}groupEnd(){this.logLevel<=0&&"undefined"!=typeof console&&console.groupEnd()}};class H extends Error{constructor(e,t,n,o){super(t),this.code=e,this.status=n,this.details=o,this.name="ApiError"}}class A{constructor(e){__publicField(this,"baseUrl"),__publicField(this,"organizationId"),__publicField(this,"defaultTimeout",6e4),__publicField(this,"defaultRetries",3),__publicField(this,"defaultRetryDelay",3e3),this.baseUrl="https://dev-api.paperlinkai.com/api/v1",this.organizationId=e.apiKey&&"demo-api-key"!==e.apiKey?e.apiKey:"f24ee8c8-cfdf-4dfb-bbb6-e26e9149a26c"}request(e){return __async(this,arguments,function*(e,t={}){const n=t,{timeout:o=this.defaultTimeout,retries:i=this.defaultRetries,retryDelay:s=this.defaultRetryDelay}=n,r=__objRest(n,["timeout","retries","retryDelay"]),a=`${this.baseUrl}${e}`,l=__spreadValues({"Content-Type":"application/json"},r.headers),c=__spreadProps(__spreadValues({},r),{headers:l});let d=null;for(let u=0;u<=i;u++)try{const e=new AbortController,t=setTimeout(()=>e.abort(),o),n=yield fetch(a,__spreadProps(__spreadValues({},c),{signal:e.signal}));clearTimeout(t);const i=yield n.json().catch(()=>null);if(!n.ok)throw new H("HTTP_ERROR",(null==i?void 0:i.message)||`HTTP ${n.status}: ${n.statusText}`,n.status,i);return i}catch(h){if(d=h instanceof Error?h:new Error(String(h)),h instanceof H&&h.status&&h.status>=400&&h.status<500&&429!==h.status)throw h;if(u<i){const e=s*Math.pow(2,u);W.warn(`API request failed, retrying in ${e}ms`,{url:a,attempt:u+1,error:d.message}),yield this.sleep(e)}}throw W.error("API request failed after all retries",{url:a,error:d}),d||new H("REQUEST_FAILED","Request failed after all retries")})}sleep(e){return new Promise(t=>setTimeout(t,e))}startSession(e){return __async(this,null,function*(){const t={message:e.trim(),organizationId:this.organizationId},n=yield this.request("/chat/session/start",{method:"POST",body:JSON.stringify(t)});if(!n.success||!n.data)throw new H("SESSION_START_FAILED",n.message||"Failed to start session",n.status);return n.data})}continueSession(e,t){return __async(this,null,function*(){const n={sessionId:e,message:t.trim(),organizationId:this.organizationId},o=yield this.request("/chat/session/continue",{method:"POST",body:JSON.stringify(n)});if(!o.success||!o.data)throw new H("SESSION_CONTINUE_FAILED",o.message||"Failed to continue session",o.status);return o.data})}getSessionHistory(e,t=50){return __async(this,null,function*(){const n=`/chat/session/${e}/history?organizationId=${this.organizationId}&limit=${t}`,o=yield this.request(n,{method:"GET"});if(!o.success||!o.data)throw new H("HISTORY_FETCH_FAILED",o.message||"Failed to fetch session history",o.status);return o.data})}sendMessage(e,t){return __async(this,null,function*(){try{if(!e||""===e.trim()){const e=yield this.startSession(t),n={id:`user-${Date.now()}`,role:"USER",content:t,timestamp:(new Date).toISOString(),sources:null},o={id:`assistant-${Date.now()}`,role:"ASSISTANT",content:e.message,timestamp:(new Date).toISOString(),sources:null,processing_time:e.processing_time};return{sessionId:e.session_id,assistantMessage:o,userMessage:n,followupQuestions:e.followup_questions||[]}}const n=yield this.continueSession(e,t),o={id:`user-${Date.now()}`,role:"USER",content:t,timestamp:(new Date).toISOString(),sources:null},i={id:`assistant-${Date.now()}`,role:"ASSISTANT",content:n.message,timestamp:(new Date).toISOString(),sources:null,processing_time:n.processing_time};return{sessionId:n.session_id,assistantMessage:i,userMessage:o,followupQuestions:n.followup_questions||[]}}catch(n){throw W.error("Failed to send message",{error:n,sessionId:e,message:t}),n}})}healthCheck(){return __async(this,null,function*(){try{return yield this.request("/chat/session/start",{method:"POST",body:JSON.stringify({message:"test",organizationId:this.organizationId}),timeout:5e3,retries:0}),!0}catch(e){return W.warn("Health check failed",{error:e}),!1}})}}const j=new class{constructor(e="sessionStorage"){__publicField(this,"prefix","paperlink_widget_"),this.storageType=e}getStorage(){try{const e="localStorage"===this.storageType?window.localStorage:window.sessionStorage,t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),e}catch(e){return W.warn("Storage not available",{type:this.storageType,error:e}),null}}getKey(e){return`${this.prefix}${e}`}set(e,t){try{const n=this.getStorage();if(!n)return!1;const o=JSON.stringify({value:t,timestamp:Date.now(),type:typeof t});return n.setItem(this.getKey(e),o),W.debug("Storage set",{key:e,type:typeof t}),!0}catch(n){return W.error("Failed to set storage item",{key:e,error:n}),!1}}get(e,t){try{const n=this.getStorage();if(!n)return t||null;const o=n.getItem(this.getKey(e));if(!o)return t||null;const i=JSON.parse(o);return W.debug("Storage get",{key:e,type:i.type}),i.value}catch(n){return W.error("Failed to get storage item",{key:e,error:n}),t||null}}remove(e){try{const t=this.getStorage();return!!t&&(t.removeItem(this.getKey(e)),W.debug("Storage remove",{key:e}),!0)}catch(t){return W.error("Failed to remove storage item",{key:e,error:t}),!1}}clear(){try{const e=this.getStorage();if(!e)return!1;const t=[];for(let n=0;n<e.length;n++){const o=e.key(n);o&&o.startsWith(this.prefix)&&t.push(o)}return t.forEach(t=>e.removeItem(t)),W.debug("Storage cleared",{removedKeys:t.length}),!0}catch(e){return W.error("Failed to clear storage",{error:e}),!1}}has(e){try{const t=this.getStorage();return!!t&&null!==t.getItem(this.getKey(e))}catch(t){return W.error("Failed to check storage key",{key:e,error:t}),!1}}getAllKeys(){try{const e=this.getStorage();if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const o=e.key(n);o&&o.startsWith(this.prefix)&&t.push(o.replace(this.prefix,""))}return t}catch(e){return W.error("Failed to get all keys",{error:e}),[]}}getSize(){try{const e=this.getStorage();if(!e)return 0;let t=0;for(let n=0;n<e.length;n++){const o=e.key(n);if(o&&o.startsWith(this.prefix)){const n=e.getItem(o);n&&(t+=o.length+n.length)}}return t}catch(e){return W.error("Failed to get storage size",{error:e}),0}}setWithExpiry(e,t,n){const o=Date.now()+n;return this.set(e,{value:t,expiry:o})}getWithExpiry(e,t){const n=this.get(e);return n&&n.expiry?Date.now()>n.expiry?(this.remove(e),t||null):n.value:t||null}}("sessionStorage"),V={bot:{width:20,height:20,maxSize:512e3},send:{width:24,height:24,maxSize:512e3},minimize:{width:24,height:24,maxSize:512e3},scrollDown:{width:24,height:24,maxSize:512e3},chatButton:{width:25,height:25,maxSize:512e3}},K=["svg","png","jpg","jpeg","webp"],q="paperlink_icon_";const J=new class{constructor(){__publicField(this,"cache",new Map),__publicField(this,"loadingPromises",new Map),this.loadCacheFromStorage()}loadIcon(e,t){return __async(this,null,function*(){const n=`${e}_${t}`,o=this.getCachedIcon(n);if(o)return W.info(`Using cached icon for ${e}`,{url:t}),{success:!0,dataUrl:o.dataUrl};if(this.loadingPromises.has(n))return W.info(`Icon already loading for ${e}, waiting...`,{url:t}),yield this.loadingPromises.get(n);const i=this.loadIconInternal(e,t,n);this.loadingPromises.set(n,i);try{return yield i}finally{this.loadingPromises.delete(n)}})}loadIconInternal(e,t,n){return __async(this,null,function*(){const o=Date.now();try{const i=new URL(t);if(!["http:","https:"].includes(i.protocol))throw new Error(`Invalid protocol: ${i.protocol}. Only HTTP and HTTPS are supported.`);const s=this.getFileExtension(t);if(!K.includes(s.toLowerCase()))throw new Error(`Unsupported format: ${s}. Supported formats: ${K.join(", ")}`);0;const r=yield Promise.race([this.loadImageWithValidation(t,e),this.timeoutPromise(5e3)]),a=Date.now()-o;0;const l={url:t,dataUrl:r.dataUrl,timestamp:Date.now(),dimensions:r.dimensions};return this.cache.set(n,l),this.saveCacheToStorage(),W.info(`Successfully loaded custom icon for ${e}`,{url:t,loadTime:a+"ms",dimensions:r.dimensions,size:Math.round(3*r.dataUrl.length/4)+" bytes"}),{success:!0,dataUrl:r.dataUrl}}catch(i){const n=Date.now()-o,s=i instanceof Error?i.message:"Unknown error";return W.error(`Custom icon loading failed for '${e}': ${s}. Using default icon.`,{url:t,error:s,loadTime:n+"ms",troubleshooting:this.getTroubleshootingTips(s)}),{success:!1,error:s}}})}loadImageWithValidation(e,t){return __async(this,null,function*(){return new Promise((n,o)=>{const i=new Image,s=V[t];i.onload=()=>{try{const{width:a,height:l}=i;W.info(`Loaded image dimensions for ${t}:`,{width:a,height:l,expected:s});const c=document.createElement("canvas"),d=c.getContext("2d");if(!d)return void o(new Error("Canvas context not available"));c.width=a,c.height=l,d.drawImage(i,0,0);try{const o=c.toDataURL(),i=Math.round(3*o.length/4);i>s.maxSize&&W.warn(`Icon size warning for ${t}: ${Math.round(i/1024)}KB exceeds recommended ${Math.round(s.maxSize/1024)}KB`,{url:e,sizeBytes:i,maxSize:s.maxSize}),n({dataUrl:o,dimensions:{width:a,height:l}})}catch(r){o(new Error(`Failed to convert image to data URL: ${r}`))}}catch(a){o(a)}},i.onerror=()=>{o(new Error("Failed to load image. Check that the URL is accessible and returns a valid image."))},i.crossOrigin="anonymous",i.src=e})})}timeoutPromise(e){return new Promise((t,n)=>{setTimeout(()=>{n(new Error(`Loading timeout after ${e}ms. The image took too long to load.`))},e)})}getFileExtension(e){try{const t=new URL(e).pathname;return t.split(".").pop()||""}catch(t){return""}}getCachedIcon(e){const t=this.cache.get(e);return t||null}loadCacheFromStorage(){if("undefined"!=typeof window)try{Object.keys(sessionStorage).forEach(e=>{if(e.startsWith(q)){const t=e.substring(15),n=JSON.parse(sessionStorage.getItem(e)||"");this.cache.set(t,n)}})}catch(e){W.warn("Failed to load icon cache from sessionStorage:",e)}}saveCacheToStorage(){if("undefined"!=typeof window)try{this.cache.forEach((e,t)=>{sessionStorage.setItem(q+t,JSON.stringify(e))})}catch(e){W.warn("Failed to save icon cache to sessionStorage:",e)}}getTroubleshootingTips(e){const t=[];return e.includes("CORS")&&(t.push("Enable CORS headers on your image server"),t.push("Ensure the image server allows cross-origin requests")),(e.includes("404")||e.includes("Failed to load"))&&(t.push("Verify the image URL is accessible"),t.push("Check that the image exists at the specified URL")),e.includes("timeout")&&(t.push("Check your internet connection"),t.push("Ensure the image server is responsive"),t.push("Consider using a smaller image file")),e.includes("format")&&t.push(`Use supported formats: ${K.join(", ")}`),0===t.length&&(t.push("Verify the image URL is correct and accessible"),t.push("Check browser console for additional error details")),t}clearCache(){this.cache.clear(),"undefined"!=typeof window&&Object.keys(sessionStorage).forEach(e=>{e.startsWith(q)&&sessionStorage.removeItem(e)}),W.info("Icon cache cleared")}};var Q,Z,G,Y,X=0,ee=[],te=t,ne=te.__b,oe=te.__r,ie=te.diffed,se=te.__c,re=te.unmount,ae=te.__;function le(e,t){te.__h&&te.__h(Z,e,X||t),X=0;var n=Z.__H||(Z.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function ce(e){return X=1,function(e,t){var n=le(Q++,2);if(n.t=e,!n.__c&&(n.__=[me(void 0,t),function(e){var t=n.__N?n.__N[0]:n.__[0],o=n.t(t,e);t!==o&&(n.__N=[o,n.__[1]],n.__c.setState({}))}],n.__c=Z,!Z.__f)){var o=function(e,t,o){if(!n.__c.__H)return!0;var s=n.__c.__H.__.filter(function(e){return!!e.__c});if(s.every(function(e){return!e.__N}))return!i||i.call(this,e,t,o);var r=n.__c.props!==e;return s.forEach(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(r=!0)}}),i&&i.call(this,e,t,o)||r};Z.__f=!0;var i=Z.shouldComponentUpdate,s=Z.componentWillUpdate;Z.componentWillUpdate=function(e,t,n){if(this.__e){var r=i;i=void 0,o(e,t,n),i=r}s&&s.call(this,e,t,n)},Z.shouldComponentUpdate=o}return n.__N||n.__}(me,e)}function de(){for(var e;e=ee.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(pe),e.__H.__h.forEach(ge),e.__H.__h=[]}catch(t){e.__H.__h=[],te.__e(t,e.__v)}}te.__b=function(e){Z=null,ne&&ne(e)},te.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ae&&ae(e,t)},te.__r=function(e){oe&&oe(e),Q=0;var t=(Z=e.__c).__H;t&&(G===Z?(t.__h=[],Z.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(pe),t.__h.forEach(ge),t.__h=[],Q=0)),G=Z},te.diffed=function(e){ie&&ie(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==ee.push(t)&&Y===te.requestAnimationFrame||((Y=te.requestAnimationFrame)||ue)(de)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),G=Z=null},te.__c=function(e,t){t.some(function(e){try{e.__h.forEach(pe),e.__h=e.__h.filter(function(e){return!e.__||ge(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],te.__e(n,e.__v)}}),se&&se(e,t)},te.unmount=function(e){re&&re(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{pe(e)}catch(n){t=n}}),n.__H=void 0,t&&te.__e(t,n.__v))};var he="function"==typeof requestAnimationFrame;function ue(e){var t,n=function(){clearTimeout(o),he&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);he&&(t=requestAnimationFrame(n))}function pe(e){var t=Z,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Z=t}function ge(e){var t=Z;e.__c=e.__(),Z=t}function me(e,t){return"function"==typeof t?t(e):t}const fe=({icon:e,className:t=""})=>O("span",{className:`material-icons ${t}`,children:e}),_e={bot:function(e){const t=e,{width:n=24,height:o=24,fill:i="#2563eb"}=t,s=__objRest(t,["width","height","fill"]);return O("svg",__spreadProps(__spreadValues({xmlns:"http://www.w3.org/2000/svg",width:n,height:o,viewBox:"0 0 24 24",fill:i,style:{marginTop:"5px"}},s),{children:O("path",{d:"M20,9V7c0-1.1-0.9-2-2-2h-3c0-1.66-1.34-3-3-3S9,3.34,9,5H6C4.9,5,4,5.9,4,7v2\n c-1.66,0-3,1.34-3,3c0,1.66,1.34,3,3,3v4c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2v-4\n c1.66,0,3-1.34,3-3C23,10.34,21.66,9,20,9z\n M7.5,11.5C7.5,10.67,8.17,10,9,10s1.5,0.67,1.5,1.5S9.83,13,9,13S7.5,12.33,7.5,11.5z\n M16,17H8v-2h8V17z\n M15,13c-0.83,0-1.5-0.67-1.5-1.5S14.17,10,15,10\n s1.5,0.67,1.5,1.5S15.83,13,15,13z"})}))},send:()=>O(fe,{icon:"send"}),minimize:()=>O(fe,{icon:"remove"}),scrollDown:()=>O(fe,{icon:"keyboard_arrow_down"}),chatButton:()=>O("svg",{fill:"white",stroke:"white",strokeWidth:"0",viewBox:"0 0 24 24",height:"25px",width:"25px",xmlns:"http://www.w3.org/2000/svg",children:O("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"})})},be=({type:e,customUrl:t,className:n="",fill:o,style:i={}})=>{const[s,r]=ce({isLoading:!1,customIcon:null,error:null});var a,l,c;if(a=()=>{if(!t)return void r({isLoading:!1,customIcon:null,error:null});let n=!0;return(()=>{__async(this,null,function*(){r(e=>__spreadProps(__spreadValues({},e),{isLoading:!0,error:null}));try{const o=yield J.loadIcon(e,t);if(!n)return;o.success&&o.dataUrl?r({isLoading:!1,customIcon:o.dataUrl,error:null}):r({isLoading:!1,customIcon:null,error:o.error||"Failed to load icon"})}catch(o){if(!n)return;r({isLoading:!1,customIcon:null,error:o instanceof Error?o.message:"Unknown error"})}})})(),()=>{n=!1}},l=[t,e],c=le(Q++,3),!te.__s&&function(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}(c.__H,l)&&(c.__=a,c.u=l,Z.__H.__h.push(c)),s.isLoading){return O("div",{className:`dynamic-icon loading ${n}`,style:i,title:"Loading custom icon...",children:O(_e[e],{className:n,fill:o})})}if(s.customIcon){const t=(()=>{switch(e){case"bot":default:return{width:"20px",height:"20px"};case"send":case"minimize":case"scrollDown":return{width:"24px",height:"24px"};case"chatButton":return{width:"25px",height:"25px"}}})();return O("img",{src:s.customIcon,alt:`Custom ${e} icon`,className:`dynamic-icon custom ${n}`,style:__spreadValues({display:"inline-block",verticalAlign:"middle",width:t.width,height:t.height,objectFit:"contain"},i),onError:()=>{r(e=>__spreadProps(__spreadValues({},e),{customIcon:null,error:"Failed to render custom icon"}))}})}return O("div",{className:`dynamic-icon default ${n}`,style:i,children:O(_e[e],{className:n,fill:o})})};class ye extends y{constructor(e){super(e),this.handleClick=this.handleClick.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}handleClick(e){e.preventDefault(),e.stopPropagation(),this.props.onClick()}handleKeyDown(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.props.onClick())}render(){var e;const{isOpen:t,hasNewMessage:n,config:o}=this.props;if(t)return null;const i={};!1!==o.showChatButtonBackground&&o.chatButtonBackgroundColor&&(i["--chat-button-bg"]=o.chatButtonBackgroundColor,i["--chat-button-hover-bg"]=this.darkenColor(o.chatButtonBackgroundColor,.1));try{console.info("[PaperlinkWidget] ChatButton render",{showChatButtonBackground:o.showChatButtonBackground,chatButtonBackgroundColor:o.chatButtonBackgroundColor,applyingStyles:i})}catch(s){}return O("button",{className:`chat-button ${n?"has-notification":""} ${!1===o.showChatButtonBackground?"no-background":""}`,onClick:this.handleClick,onKeyDown:this.handleKeyDown,title:"Open chat","aria-label":"Open chat","aria-expanded":!1,type:"button",style:i,children:O(be,{type:"chatButton",customUrl:null==(e=o.customIcons)?void 0:e.chatButton,className:"chat-button-icon",style:{width:"25px",height:"25px"}})})}darkenColor(e,t){if(e.startsWith("#")){const n=e.slice(1),o=parseInt(n,16);return`#${(Math.max(0,Math.floor((o>>16)*(1-t)))<<16|Math.max(0,Math.floor((o>>8&255)*(1-t)))<<8|Math.max(0,Math.floor((255&o)*(1-t)))).toString(16).padStart(6,"0")}`}return e}}class we extends y{constructor(e){super(e),this.handleMinimizeClick=this.handleMinimizeClick.bind(this)}handleMinimizeClick(e){e.preventDefault(),e.stopPropagation(),this.props.onClose()}render(){var e;const{config:t}=this.props;return O("div",{className:"chat-header",children:[O("h3",{children:t.title}),t.features.minimizable&&O("button",{className:"minimize-button",onClick:this.handleMinimizeClick,title:"Minimize chat","aria-label":"Minimize chat",type:"button",children:O(be,{type:"minimize",customUrl:null==(e=t.customIcons)?void 0:e.minimize,className:"minimize-icon"})})]})}}class xe extends y{constructor(e){super(e),__publicField(this,"inputRef",{current:null}),__publicField(this,"maxLength",2e3),this.state={message:"",isComposing:!1},this.handleInputChange=this.handleInputChange.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleSubmit=this.handleSubmit.bind(this),this.handleCompositionStart=this.handleCompositionStart.bind(this),this.handleCompositionEnd=this.handleCompositionEnd.bind(this)}handleInputChange(e){const t=e.target.value;t.length<=this.maxLength&&this.setState({message:t})}handleKeyDown(e){this.state.isComposing||"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.handleSubmit())}handleCompositionStart(){this.setState({isComposing:!0})}handleCompositionEnd(){this.setState({isComposing:!1})}handleSubmit(){return __async(this,null,function*(){const e=this.state.message.trim();if(e&&!this.props.isLoading){W.debug("Sending message",{length:e.length}),this.setState({message:""});try{yield this.props.onSendMessage(e),this.inputRef.current&&this.inputRef.current.focus()}catch(t){W.error("Failed to send message",{error:t}),this.setState({message:e})}}})}render(){var e;const{config:t,isLoading:n}=this.props,{message:o}=this.state,i=!n&&o.trim().length>0;return O("div",{children:[O("div",{className:"input-container",children:[O("div",{className:"input-wrapper",children:[O("input",{ref:this.inputRef,className:"message-input",type:"text",value:o,placeholder:t.placeholder,disabled:n,onInput:this.handleInputChange,onKeyDown:this.handleKeyDown,onCompositionStart:this.handleCompositionStart,onCompositionEnd:this.handleCompositionEnd,"aria-label":"Type your message",maxLength:this.maxLength}),O("button",{className:"send-button",onClick:this.handleSubmit,disabled:!i,title:n?"Sending...":"Send message",type:"button",children:n?O("div",{style:{width:"16px",height:"16px",border:"2px solid rgba(255, 255, 255, 0.3)",borderTop:"2px solid white",borderRadius:"50%",animation:"spin 1s linear infinite"}}):O(be,{type:"send",customUrl:null==(e=this.props.config.customIcons)?void 0:e.send,className:"send-icon"})})]}),O("style",{children:"\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n\n @media (max-width: 480px) {\n .message-input {\n font-size: 16px !important;\n }\n }\n "})]}),O("div",{style:{textAlign:"center",fontSize:"14px",fontWeight:600,paddingBottom:"16px"},className:"powered-by",children:["Powered by ",O("a",{href:"https://paperlinkai.com/",target:"_blank",rel:"noopener noreferrer",children:"PaperlinkAi"})]})]})}}class ve{static querySelector(e,t=document){try{return t.querySelector(e)}catch(n){return W.error("Query selector failed",{selector:e,error:n}),null}}static createElement(e,t={}){const n=document.createElement(e);return t.id&&(n.id=t.id),t.className&&(n.className=t.className),t.textContent&&(n.textContent=t.textContent),t.innerHTML&&(n.innerHTML=t.innerHTML),t.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t.styles&&Object.assign(n.style,t.styles),n}static isElementVisible(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}static scrollIntoView(e,t="smooth"){try{e.scrollIntoView({behavior:t,block:"nearest",inline:"start"})}catch(n){e.scrollIntoView()}}static debounce(e,t){let n;return(...o)=>{clearTimeout(n),n=setTimeout(()=>e.apply(null,o),t)}}static throttle(e,t){let n,o=0;return(...i)=>{const s=Date.now();s-o>t?(e.apply(null,i),o=s):n||(n=setTimeout(()=>{e.apply(null,i),o=Date.now(),n=null},t-(s-o)))}}static generateId(e="pl"){return`${e}_${Math.random().toString(36).substr(2,9)}_${Date.now()}`}static hasClass(e,t){return e.classList.contains(t)}static addEventListener(e,t,n,o){return e.addEventListener(t,n,o),()=>e.removeEventListener(t,n,o)}static getComputedStyle(e,t){return window.getComputedStyle(e).getPropertyValue(t)}static isMobileDevice(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}static getViewportDimensions(){return{width:Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),height:Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)}}}class ke extends y{render(){const{config:e,message:t="Loading chat history..."}=this.props;return O("div",{className:"loading-indicator",style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px",flex:"1"},children:[O("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:`${e.theme.textColor}80`,fontSize:"14px"},children:[O("div",{style:{width:"16px",height:"16px",border:`2px solid ${e.theme.textColor}20`,borderTop:`2px solid ${e.theme.textColor}80`,borderRadius:"50%",animation:"spin 1s linear infinite"}}),O("span",{children:t})]}),O("style",{children:"\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n "})]})}}class Se extends y{constructor(e){super(e),this.state={showSources:!1},this.handleToggleSources=this.handleToggleSources.bind(this)}formatMessageContent(e){return e.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>").replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/`(.*?)`/g,"<code>$1</code>").replace(/\n/g,"<br>")}handleToggleSources(){this.setState(e=>({showSources:!e.showSources}))}renderSources(){const{message:e}=this.props,{showSources:t}=this.state;return e.sources&&0!==e.sources.length?O("div",{className:"message-sources",children:[O("button",{className:"sources-toggle",onClick:this.handleToggleSources,type:"button",children:[O("span",{className:"material-icons toggle-icon "+(t?"expanded":""),children:"chevron_right"}),e.sources.length," source",e.sources.length>1?"s":""]}),t&&O("div",{className:"sources-list",children:e.sources.map((e,t)=>O("div",{className:"source-item",children:[O("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"source-link",children:e.title}),O("div",{className:"source-snippet",children:e.snippet})]},t))})]}):null}render(){var e;const{message:t}=this.props,n="USER"===t.role.toUpperCase();return O("div",{className:"message "+(n?"user":"bot"),children:[!n&&O("div",{className:"bot-avatar",children:O(be,{type:"bot",customUrl:null==(e=this.props.config.customIcons)?void 0:e.bot,className:"bot-icon"})}),O("div",{className:"message-content",children:[O("p",{dangerouslySetInnerHTML:{__html:this.formatMessageContent(t.content)}}),this.renderSources()]})]})}}class Ce extends y{render(){var e;const{config:t}=this.props;return O("div",{className:"typing-indicator",children:[O("div",{className:"bot-avatar",children:O(be,{type:"bot",customUrl:null==(e=t.customIcons)?void 0:e.bot,className:"bot-icon"})}),O("div",{className:"typing-dots",children:[O("div",{className:"typing-dot"}),O("div",{className:"typing-dot"}),O("div",{className:"typing-dot"})]})]})}}class Ie extends y{constructor(e){super(e),__publicField(this,"listRef",{current:null}),__publicField(this,"scrollThreshold"),__publicField(this,"autoScrollDebounced"),this.scrollThreshold=e.config.features.scrollToBottomThreshold||100,this.state={shouldAutoScroll:!0,showScrollButton:!1},this.handleScroll=this.handleScroll.bind(this),this.scrollToBottom=this.scrollToBottom.bind(this),this.autoScrollDebounced=ve.debounce(this.scrollToBottom,100)}componentDidMount(){W.debug("MessageList mounted"),this.scrollToBottom(!1),this.listRef.current&&this.listRef.current.addEventListener("scroll",this.handleScroll,{passive:!0})}componentDidUpdate(e){const{session:t}=this.props;t.messages.length>e.session.messages.length&&this.state.shouldAutoScroll&&setTimeout(()=>this.autoScrollDebounced(),50)}componentWillUnmount(){this.listRef.current&&this.listRef.current.removeEventListener("scroll",this.handleScroll)}handleScroll(){const e=this.listRef.current;if(!e)return;const{scrollTop:t,scrollHeight:n,clientHeight:o}=e,i=n-t-o<=this.scrollThreshold,s=i,r=!i&&this.props.config.features.scrollToBottom;s===this.state.shouldAutoScroll&&r===this.state.showScrollButton||this.setState({shouldAutoScroll:s,showScrollButton:r})}scrollToBottom(e=!0){const t=this.listRef.current;if(t)try{t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})}catch(n){t.scrollTop=t.scrollHeight}}renderWelcomeMessage(){var e;if(this.props.session.messages.length>0||this.props.isInitialLoading)return null;const{config:t}=this.props;return O("div",{className:"message",children:[O("div",{className:"bot-avatar",children:O(be,{type:"bot",customUrl:null==(e=t.customIcons)?void 0:e.bot,className:"bot-icon"})}),O("div",{className:"message-content",children:O("p",{children:t.greeting})})]})}renderScrollToBottomButton(){var e;return this.state.showScrollButton?O("button",{onClick:()=>this.scrollToBottom(!0),title:"abc","aria-label":"Scroll to bottom",type:"button",style:"\n position: sticky;\n bottom: 16px;\n left: calc(100% - 32px);\n width: 40px;\n height: 40px;\n padding: 20px;\n box-sizing: border-box;\n border: none;\n border-radius: 50%;\n background: #ffffff00;\n backdrop-filter: blur(6px);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n color: #333333;\n box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.08);\n transition: background-color 0.2s ease, transform 0.15s ease;\n z-index: 10;\n ",children:O(be,{type:"scrollDown",customUrl:null==(e=this.props.config.customIcons)?void 0:e.scrollDown,className:"scroll-down-icon"})}):null}render(){const{config:e,session:t,isInitialLoading:n}=this.props;return O("div",{className:"messages-container",ref:this.listRef,children:[n?O(ke,{config:e,message:"Loading chat history..."}):O(b,{children:[this.renderWelcomeMessage(),t.messages.map((n,o)=>O(Se,{message:n,config:e,isLastMessage:o===t.messages.length-1},n.id)),t.isLoading&&e.features.typing&&O(Ce,{config:e})]}),this.renderScrollToBottomButton()]})}}class Me extends y{constructor(e){super(e),__publicField(this,"windowRef",{current:null}),this.state={isClosing:!1}}getPositionClass(){switch(this.props.config.position){case"bottom-left":return"position-bottom-left";case"top-right":return"position-top-right";case"top-left":return"position-top-left";default:return""}}render(){const{config:e,session:t,isInitialLoading:n,onSendMessage:o,onMinimize:i,onClose:s}=this.props,{isClosing:r}=this.state,a=`chat-window ${this.getPositionClass()} ${r?"closing":""}`;return O("div",{ref:this.windowRef,className:a,children:[O(we,{config:e,onMinimize:i,onClose:s}),O(Ie,{config:e,session:t,isInitialLoading:n}),O(xe,{config:e,isLoading:t.isLoading,onSendMessage:o})]})}}class ze extends y{constructor(e){super(e),this.state={isHovered:!1},this.handleMouseEnter=this.handleMouseEnter.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleRetryClick=this.handleRetryClick.bind(this)}handleMouseEnter(){this.setState({isHovered:!0})}handleMouseLeave(){this.setState({isHovered:!1})}handleRetryClick(){this.props.isRetrying||this.props.onRetry()}render(){const{config:e,error:t,isRetrying:n=!1}=this.props,{isHovered:o}=this.state,i={backgroundColor:n?"#d1d5db":o?"#dc2626":"#ef4444",color:"#ffffff",border:"none",borderRadius:"6px",padding:"6px 12px",fontSize:"12px",fontWeight:"500",cursor:n?"not-allowed":"pointer",transition:"all 0.2s ease",display:"flex",alignItems:"center",gap:"4px"};return O("div",{className:"error-message",style:{padding:"16px 20px",margin:"12px 16px",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",display:"flex",alignItems:"center",gap:"12px",fontFamily:"inherit"},children:[O("svg",{style:{width:"20px",height:"20px",flexShrink:"0",color:"#dc2626"},fill:"currentColor",viewBox:"0 0 20 20",children:O("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})}),O("div",{style:{flex:"1",display:"flex",flexDirection:"column",gap:"8px"},children:[O("p",{style:{color:"#991b1b",fontSize:"14px",lineHeight:"1.4",margin:"0"},children:t||"Something went wrong. Please try again."}),O("button",{style:i,onClick:this.handleRetryClick,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,disabled:n,title:n?"Retrying...":"Try again","aria-label":n?"Retrying...":"Try again",children:O(b,n?{children:[O("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:O("path",{d:"M12,4V2C6.48,2 2,6.48 2,12s4.48,10 10,10s10-4.48 10-10c0-1.57-0.36-3.05-1.01-4.37l-1.45,1.45C19.83,10.15 20,11.05 20,12c0,4.41-3.59,8-8,8s-8-3.59-8-8s3.59-8 8-8V6l4-2L12,4z"})}),"Retrying..."]}:{children:[O("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:O("path",{d:"M17.65,6.35C16.2,4.9 14.21,4 12,4c-4.42,0 -7.99,3.58 -7.99,8s3.57,8 7.99,8c3.73,0 6.84,-2.55 7.73,-6h-2.08c-0.82,2.33 -3.04,4 -5.65,4 -3.31,0 -6,-2.69 -6,-6s2.69,-6 6,-6c1.66,0 3.14,0.69 4.22,1.78L13,11h7V4L17.65,6.35z"})}),"Try Again"]})})]}),O("style",{children:`\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n \n .error-message button:disabled svg:first-child {\n animation: spin 1s linear infinite;\n }\n \n .error-message button:focus-visible {\n outline: 2px solid ${e.theme.primaryColor}66;\n outline-offset: 2px;\n }\n `})]})}}class Ee extends y{constructor(e){super(e),__publicField(this,"apiClient"),this.apiClient=new A(e.config),this.state={isOpen:e.config.autoOpen||!1,isLoading:!1,session:{sessionId:"",messages:[],isLoading:!1,error:null},error:null,isMinimized:!1,hasNewMessage:!1,isRetrying:!1,lastFailedMessage:void 0},this.handleToggleWidget=this.handleToggleWidget.bind(this),this.handleSendMessage=this.handleSendMessage.bind(this),this.handleMinimize=this.handleMinimize.bind(this),this.handleClose=this.handleClose.bind(this),this.handleRetryLastMessage=this.handleRetryLastMessage.bind(this)}componentDidMount(){return __async(this,null,function*(){W.info("Widget mounted",{config:this.props.config}),document.addEventListener("paperlink-widget-open",()=>this.openWidget()),document.addEventListener("paperlink-widget-close",()=>this.closeWidget()),document.addEventListener("paperlink-widget-toggle",()=>this.toggleWidget()),window.addEventListener("beforeunload",()=>this.handleBeforeUnload()),yield this.initializeSession(),this.sendAnalytics("widget_opened")})}componentWillUnmount(){W.info("Widget unmounting"),document.removeEventListener("paperlink-widget-open",()=>this.openWidget()),document.removeEventListener("paperlink-widget-close",()=>this.closeWidget()),document.removeEventListener("paperlink-widget-toggle",()=>this.toggleWidget()),window.removeEventListener("beforeunload",()=>this.handleBeforeUnload()),this.sendAnalytics("widget_closed")}initializeSession(){return __async(this,null,function*(){try{this.setState({isLoading:!0,error:null});const e=j.get("sessionId"),t=j.get("messages")||[];if(e&&t.length>0)return W.info("Restoring session from storage",{sessionId:e}),void this.setState({session:{sessionId:e,messages:t,isLoading:!1,error:null},isLoading:!1});W.info("Ready for new session - will be created with first message"),this.setState({session:{sessionId:"",messages:[],isLoading:!1,error:null},isLoading:!1})}catch(e){W.error("Failed to initialize session",{error:e}),this.setState({session:{sessionId:"",messages:[],isLoading:!1,error:"Failed to initialize chat session. Please try again."},isLoading:!1,error:"Session initialization failed"})}})}handleSendMessage(e){return __async(this,null,function*(){if(!e.trim())return;const t={id:`user-${Date.now()}`,role:"USER",content:e,timestamp:(new Date).toISOString(),sources:null};this.setState(e=>({session:__spreadProps(__spreadValues({},e.session),{messages:[...e.session.messages,t],isLoading:!0,error:null}),error:null,lastFailedMessage:void 0}));try{const t=yield this.apiClient.sendMessage(this.state.session.sessionId||null,e);this.setState(e=>({session:__spreadProps(__spreadValues({},e.session),{sessionId:t.sessionId,messages:[...e.session.messages,t.assistantMessage],isLoading:!1})})),j.set("sessionId",t.sessionId),this.saveMessagesToStorage([...this.state.session.messages,t.assistantMessage]),this.sendAnalytics("message_sent",{messageLength:e.length,hasFollowups:t.followupQuestions.length>0}),this.state.isOpen||this.setState({hasNewMessage:!0})}catch(n){W.error("Failed to send message",{error:n});const t=n instanceof Error?n.message:"Failed to send message";this.setState(n=>({session:__spreadProps(__spreadValues({},n.session),{messages:n.session.messages.slice(0,-1),isLoading:!1,error:null}),error:t,lastFailedMessage:e,isRetrying:!1})),this.sendAnalytics("message_error",{errorType:n instanceof Error?n.name:"Unknown",errorMessage:t})}})}handleRetryLastMessage(){return __async(this,null,function*(){if(this.state.lastFailedMessage&&!this.state.isRetrying){this.setState({isRetrying:!0,error:null});try{yield this.handleSendMessage(this.state.lastFailedMessage),this.setState({lastFailedMessage:void 0,isRetrying:!1})}catch(e){this.setState({isRetrying:!1})}}})}saveMessagesToStorage(e){j.set("messages",e.slice(-this.props.config.maxMessages))}handleToggleWidget(){this.setState(e=>({isOpen:!e.isOpen,hasNewMessage:!1}))}handleMinimize(){this.setState({isMinimized:!0})}handleClose(){this.setState({isOpen:!1,isMinimized:!1,hasNewMessage:!1})}openWidget(){this.setState({isOpen:!0,isMinimized:!1,hasNewMessage:!1})}closeWidget(){this.setState({isOpen:!1,isMinimized:!1})}toggleWidget(){this.handleToggleWidget()}handleBeforeUnload(){this.state.session.messages.length>0&&this.saveMessagesToStorage(this.state.session.messages)}sendAnalytics(e,t){W.debug("Analytics event",{event:e,metadata:t})}render(){const{config:e}=this.props,{isOpen:t,isLoading:n,session:o,error:i,isMinimized:s,hasNewMessage:r,isRetrying:a}=this.state;return W.info("Widget render",{isOpen:t,isLoading:n,isMinimized:s,hasNewMessage:r,sessionId:o.sessionId,error:!!i}),n&&!o.sessionId?O("div",{className:"widget-loading",children:O("div",{className:"loading-spinner"})}):i&&!o.sessionId?O("div",{className:"widget-error",children:O(ze,{config:e,error:"Unable to load chat widget. Please check your connection and try again.",onRetry:()=>this.initializeSession(),isRetrying:n})}):O("div",{className:"paperlink-widget",children:[t&&!s&&O(Me,{config:e,session:o,isInitialLoading:n&&!o.sessionId,onSendMessage:this.handleSendMessage,onMinimize:this.handleMinimize,onClose:this.handleClose}),t&&!s&&i&&O("div",{style:{position:"fixed",bottom:"80px",right:"20px",zIndex:"999997",maxWidth:"380px"},children:O(ze,{config:e,error:i,onRetry:this.handleRetryLastMessage,isRetrying:a})}),O(ye,{config:e,isOpen:t,hasNewMessage:r,onClick:this.handleToggleWidget})]})}}const Te={apiKey:"",apiUrl:"https://api.paperlinkAI.com/widget",title:"AI Assistant",greeting:"Hi! How can I help you today?",placeholder:"Type your message...",position:"bottom-right",width:384,height:600,theme:{primaryColor:"#2563eb",primaryHoverColor:"#1d4ed8",lightPrimaryColor:"#dbeafe",backgroundColor:"#ffffff",headerB