@paperlinkai/chat
Version:
PaperLink AI Chat Widget - Easy integration for any website
1 lines • 74.4 kB
JavaScript
"use strict";var e,t,n,o,i,s,r,a,l,c,d,h=Object.defineProperty,u=Object.defineProperties,p=Object.getOwnPropertyDescriptors,g=Object.getOwnPropertySymbols,m=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable,_=(e,t,n)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))m.call(t,n)&&_(e,n,t[n]);if(g)for(var n of g(t))f.call(t,n)&&_(e,n,t[n]);return e},y=(e,t)=>u(e,p(t)),w=(e,t)=>{var n={};for(var o in e)m.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&g)for(var o of g(e))t.indexOf(o)<0&&f.call(e,o)&&(n[o]=e[o]);return n},x=(e,t,n)=>_(e,"symbol"!=typeof t?t+"":t,n),v=(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())}),k={},S=[],C=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,I=Array.isArray;function M(e,t){for(var n in t)e[n]=t[n];return e}function z(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function E(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 T(e){return e.children}function L(e,t){this.props=e,this.context=t}function R(e,t){if(null==t)return e.__?R(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?R(e):null}function B(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 B(e)}}function $(e){(!e.__d&&(e.__d=!0)&&o.push(e)&&!N.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||s)(N)}function N(){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),H(n.__P,i,s,n.__n,n.__P.namespaceURI,32&s.__u?[a]:null,l,null==a?R(s):a,!!(32&s.__u),c),i.__v=s.__v,i.__.__k[i.__i]=i,j(l,i,c),i.__e!=a&&B(i)));N.__r=0}function D(e,t,n,o,i,s,r,a,l,c,d){var h,u,p,g,m,f,_=o&&o.__k||S,b=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?E(null,r,null,null,null):I(r)?E(T,{children:r},null,null,null):null==r.constructor&&r.__b>0?E(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=P(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=R(a)),V(a,a));return o}(n,t,_,l,b),h=0;h<b;h++)null!=(p=n.__k[h])&&(u=-1==p.__i?k:_[p.__i]||k,p.__i=h,f=H(e,p,u,i,s,r,a,l,c,d),g=p.__e,p.ref&&u.ref!=p.ref&&(u.ref&&q(u.ref,null,p),d.push(p.ref,p.__c||g,p)),null==m&&null!=g&&(m=g),4&p.__u||u.__k===p.__k?l=U(p,l,e):"function"==typeof p.type&&void 0!==f?l=f:g&&(l=g.nextSibling),p.__u&=-7);return n.__e=m,l}function U(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=U(o[i],t,n));return t}e.__e!=t&&(t&&e.type&&!n.contains(t)&&(t=R(e)),n.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function P(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 O(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||C.test(t)?n:n+"px"}function W(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||O(e.style,t,"");if(n)for(t in n)o&&n[t]==o[t]||O(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 F(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 H(n,o,i,s,r,a,l,c,d,h){var u,p,g,m,f,_,b,y,w,x,v,S,C,E,B,$,N,U=o.type;if(null!=o.constructor)return null;128&i.__u&&(d=!!(32&i.__u),a=[c=o.__e=i.__e]),(u=t.__b)&&u(o);e:if("function"==typeof U)try{if(y=o.props,w="prototype"in U&&U.prototype.render,x=(u=U.contextType)&&s[u.__c],v=u?x?x.props.value:u.__:s,i.__c?b=(p=o.__c=i.__c).__=p.__E:(w?o.__c=p=new U(y,v):(o.__c=p=new L(y,v),p.constructor=U,p.render=J),x&&x.sub(p),p.props=y,p.state||(p.state={}),p.context=v,p.__n=s,g=p.__d=!0,p.__h=[],p._sb=[]),w&&null==p.__s&&(p.__s=p.state),w&&null!=U.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=M({},p.__s)),M(p.__s,U.getDerivedStateFromProps(y,p.__s))),m=p.props,f=p.state,p.__v=o,g)w&&null==U.getDerivedStateFromProps&&null!=p.componentWillMount&&p.componentWillMount(),w&&null!=p.componentDidMount&&p.__h.push(p.componentDidMount);else{if(w&&null==U.getDerivedStateFromProps&&y!==m&&null!=p.componentWillReceiveProps&&p.componentWillReceiveProps(y,v),!p.__e&&null!=p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(y,p.__s,v)||o.__v==i.__v){for(o.__v!=i.__v&&(p.props=y,p.state=p.__s,p.__d=!1),o.__e=i.__e,o.__k=i.__k,o.__k.some(function(e){e&&(e.__=o)}),S=0;S<p._sb.length;S++)p.__h.push(p._sb[S]);p._sb=[],p.__h.length&&l.push(p);break e}null!=p.componentWillUpdate&&p.componentWillUpdate(y,p.__s,v),w&&null!=p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(m,f,_)})}if(p.context=v,p.props=y,p.__P=n,p.__e=!1,C=t.__r,E=0,w){for(p.state=p.__s,p.__d=!1,C&&C(o),u=p.render(p.props,p.state,p.context),B=0;B<p._sb.length;B++)p.__h.push(p._sb[B]);p._sb=[]}else do{p.__d=!1,C&&C(o),u=p.render(p.props,p.state,p.context),p.state=p.__s}while(p.__d&&++E<25);p.state=p.__s,null!=p.getChildContext&&(s=M(M({},s),p.getChildContext())),w&&!g&&null!=p.getSnapshotBeforeUpdate&&(_=p.getSnapshotBeforeUpdate(m,f)),$=u,null!=u&&u.type===T&&null==u.key&&($=K(u.props.children)),c=D(n,I($)?$:[$],o,i,s,r,a,l,c,d,h),p.base=o.__e,o.__u&=-161,p.__h.length&&l.push(p),b&&(p.__E=p.__=null)}catch(P){if(o.__v=null,d||null!=a)if(P.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(N=a.length;N--;)z(a[N]);A(o)}else o.__e=i.__e,o.__k=i.__k,P.then||A(o);t.__e(P,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 h,u,p,g,m,f,_,b=i.props,y=o.props,w=o.type;if("svg"==w?r="http://www.w3.org/2000/svg":"math"==w?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=a)for(h=0;h<a.length;h++)if((m=a[h])&&"setAttribute"in m==!!w&&(w?m.localName==w:3==m.nodeType)){n=m,a[h]=null;break}if(null==n){if(null==w)return document.createTextNode(y);n=document.createElementNS(r,w,y.is&&y),c&&(t.__m&&t.__m(o,a),c=!1),a=null}if(null==w)b===y||c&&n.data==y||(n.data=y);else{if(a=a&&e.call(n.childNodes),b=i.props||k,!c&&null!=a)for(b={},h=0;h<n.attributes.length;h++)b[(m=n.attributes[h]).name]=m.value;for(h in b)if(m=b[h],"children"==h);else if("dangerouslySetInnerHTML"==h)p=m;else if(!(h in y)){if("value"==h&&"defaultValue"in y||"checked"==h&&"defaultChecked"in y)continue;W(n,h,null,m,r)}for(h in y)m=y[h],"children"==h?g=m:"dangerouslySetInnerHTML"==h?u=m:"value"==h?f=m:"checked"==h?_=m:c&&"function"!=typeof m||b[h]===m||W(n,h,m,b[h],r);if(u)c||p&&(u.__html==p.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),o.__k=[];else if(p&&(n.innerHTML=""),D("template"==o.type?n.content:n,I(g)?g:[g],o,i,s,"foreignObject"==w?"http://www.w3.org/1999/xhtml":r,a,l,a?a[0]:i.__k&&R(i,0),c,d),null!=a)for(h=a.length;h--;)z(a[h]);c||(h="value","progress"==w&&null==f?n.removeAttribute("value"):null!=f&&(f!==n[h]||"progress"==w&&!f||"option"==w&&f!=b[h])&&W(n,h,f,b[h],r),h="checked",null!=_&&_!=n[h]&&W(n,h,_,b[h],r))}return n}(i.__e,o,i,s,r,a,l,d,h);return(u=t.diffed)&&u(o),128&o.__u?void 0:c}function A(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(A)}function j(e,n,o){for(var i=0;i<o.length;i++)q(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 K(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:I(e)?e.map(K):M({},e)}function q(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 V(e,n,o){var i,s;if(t.unmount&&t.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||q(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]&&V(i[s],n,o||"function"!=typeof e.type);o||z(e.__e),e.__c=e.__=e.__e=void 0}function J(e,t,n){return this.constructor(e,n)}function Q(n,o,i){var s,r,a;o==document&&(o=document.documentElement),t.__&&t.__(n,o),s=!1?null:o.__k,r=[],a=[],H(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 E(t,a,i,s,null)}(T,null,[n]),s||k,k,o.namespaceURI,s?null:o.firstChild?e.call(o.childNodes):null,r,s?s.__e:o.firstChild,false,a),j(r,n,a)}e=S.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,L.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),$(this))},L.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),$(this))},L.prototype.render=T,o=[],s="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,r=function(e,t){return e.__v.__b-t.__v.__b},N.__r=0,a=/(PointerCapture)$|Capture$/i,l=0,c=F(!1),d=F(!0);var Z=0;function G(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:--Z,__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 Y=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Y||{});const X=new class{constructor(){x(this,"logLevel",1),x(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=Y[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 ee extends Error{constructor(e,t,n,o){super(t),this.code=e,this.status=n,this.details=o,this.name="ApiError"}}class te{constructor(e){x(this,"baseUrl"),x(this,"organizationId"),x(this,"defaultTimeout",6e4),x(this,"defaultRetries",3),x(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 v(this,arguments,function*(e,t={}){const n=t,{timeout:o=this.defaultTimeout,retries:i=this.defaultRetries,retryDelay:s=this.defaultRetryDelay}=n,r=w(n,["timeout","retries","retryDelay"]),a=`${this.baseUrl}${e}`,l=b({"Content-Type":"application/json"},r.headers),c=y(b({},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,y(b({},c),{signal:e.signal}));clearTimeout(t);const i=yield n.json().catch(()=>null);if(!n.ok)throw new ee("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 ee&&h.status&&h.status>=400&&h.status<500&&429!==h.status)throw h;if(u<i){const e=s*Math.pow(2,u);X.warn(`API request failed, retrying in ${e}ms`,{url:a,attempt:u+1,error:d.message}),yield this.sleep(e)}}throw X.error("API request failed after all retries",{url:a,error:d}),d||new ee("REQUEST_FAILED","Request failed after all retries")})}sleep(e){return new Promise(t=>setTimeout(t,e))}startSession(e){return v(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 ee("SESSION_START_FAILED",n.message||"Failed to start session",n.status);return n.data})}continueSession(e,t){return v(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 ee("SESSION_CONTINUE_FAILED",o.message||"Failed to continue session",o.status);return o.data})}getSessionHistory(e,t=50){return v(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 ee("HISTORY_FETCH_FAILED",o.message||"Failed to fetch session history",o.status);return o.data})}sendMessage(e,t){return v(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 X.error("Failed to send message",{error:n,sessionId:e,message:t}),n}})}healthCheck(){return v(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 X.warn("Health check failed",{error:e}),!1}})}}const ne=new class{constructor(e="sessionStorage"){x(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 X.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),X.debug("Storage set",{key:e,type:typeof t}),!0}catch(n){return X.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 X.debug("Storage get",{key:e,type:i.type}),i.value}catch(n){return X.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)),X.debug("Storage remove",{key:e}),!0)}catch(t){return X.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)),X.debug("Storage cleared",{removedKeys:t.length}),!0}catch(e){return X.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 X.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 X.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 X.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"),oe={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}},ie=["svg","png","jpg","jpeg","webp"],se="paperlink_icon_";const re=new class{constructor(){x(this,"cache",new Map),x(this,"loadingPromises",new Map),this.loadCacheFromStorage()}loadIcon(e,t){return v(this,null,function*(){const n=`${e}_${t}`,o=this.getCachedIcon(n);if(o)return X.info(`Using cached icon for ${e}`,{url:t}),{success:!0,dataUrl:o.dataUrl};if(this.loadingPromises.has(n))return X.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 v(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(!ie.includes(s.toLowerCase()))throw new Error(`Unsupported format: ${s}. Supported formats: ${ie.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(),X.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 X.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 v(this,null,function*(){return new Promise((n,o)=>{const i=new Image,s=oe[t];i.onload=()=>{try{const{width:a,height:l}=i;X.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&&X.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(se)){const t=e.substring(15),n=JSON.parse(sessionStorage.getItem(e)||"");this.cache.set(t,n)}})}catch(e){X.warn("Failed to load icon cache from sessionStorage:",e)}}saveCacheToStorage(){if("undefined"!=typeof window)try{this.cache.forEach((e,t)=>{sessionStorage.setItem(se+t,JSON.stringify(e))})}catch(e){X.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: ${ie.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(se)&&sessionStorage.removeItem(e)}),X.info("Icon cache cleared")}};var ae,le,ce,de,he=0,ue=[],pe=t,ge=pe.__b,me=pe.__r,fe=pe.diffed,_e=pe.__c,be=pe.unmount,ye=pe.__;function we(e,t){pe.__h&&pe.__h(le,e,he||t),he=0;var n=le.__H||(le.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function xe(e){return he=1,function(e,t){var n=we(ae++,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=le,!le.__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};le.__f=!0;var i=le.shouldComponentUpdate,s=le.componentWillUpdate;le.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)},le.shouldComponentUpdate=o}return n.__N||n.__}(Me,e)}function ve(){for(var e;e=ue.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ce),e.__H.__h.forEach(Ie),e.__H.__h=[]}catch(t){e.__H.__h=[],pe.__e(t,e.__v)}}pe.__b=function(e){le=null,ge&&ge(e)},pe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ye&&ye(e,t)},pe.__r=function(e){me&&me(e),ae=0;var t=(le=e.__c).__H;t&&(ce===le?(t.__h=[],le.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Ce),t.__h.forEach(Ie),t.__h=[],ae=0)),ce=le},pe.diffed=function(e){fe&&fe(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==ue.push(t)&&de===pe.requestAnimationFrame||((de=pe.requestAnimationFrame)||Se)(ve)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),ce=le=null},pe.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Ce),e.__h=e.__h.filter(function(e){return!e.__||Ie(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],pe.__e(n,e.__v)}}),_e&&_e(e,t)},pe.unmount=function(e){be&&be(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Ce(e)}catch(n){t=n}}),n.__H=void 0,t&&pe.__e(t,n.__v))};var ke="function"==typeof requestAnimationFrame;function Se(e){var t,n=function(){clearTimeout(o),ke&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(n,35);ke&&(t=requestAnimationFrame(n))}function Ce(e){var t=le,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),le=t}function Ie(e){var t=le;e.__c=e.__(),le=t}function Me(e,t){return"function"==typeof t?t(e):t}const ze=({icon:e,className:t=""})=>G("span",{className:`material-icons ${t}`,children:e}),Ee={bot:function(e){const t=e,{width:n=24,height:o=24,fill:i="#2563eb"}=t,s=w(t,["width","height","fill"]);return G("svg",y(b({xmlns:"http://www.w3.org/2000/svg",width:n,height:o,viewBox:"0 0 24 24",fill:i,style:{marginTop:"5px"}},s),{children:G("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:()=>G(ze,{icon:"send"}),minimize:()=>G(ze,{icon:"remove"}),scrollDown:()=>G(ze,{icon:"keyboard_arrow_down"}),chatButton:()=>G("svg",{fill:"white",stroke:"white",strokeWidth:"0",viewBox:"0 0 24 24",height:"25px",width:"25px",xmlns:"http://www.w3.org/2000/svg",children:G("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"})})},Te=({type:e,customUrl:t,className:n="",fill:o,style:i={}})=>{const[s,r]=xe({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 v(exports,null,function*(){r(e=>y(b({},e),{isLoading:!0,error:null}));try{const o=yield re.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=we(ae++,3),!pe.__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,le.__H.__h.push(c)),s.isLoading){return G("div",{className:`dynamic-icon loading ${n}`,style:i,title:"Loading custom icon...",children:G(Ee[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 G("img",{src:s.customIcon,alt:`Custom ${e} icon`,className:`dynamic-icon custom ${n}`,style:b({display:"inline-block",verticalAlign:"middle",width:t.width,height:t.height,objectFit:"contain"},i),onError:()=>{r(e=>y(b({},e),{customIcon:null,error:"Failed to render custom icon"}))}})}return G("div",{className:`dynamic-icon default ${n}`,style:i,children:G(Ee[e],{className:n,fill:o})})};class Le extends L{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 G("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:G(Te,{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 Re extends L{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 G("div",{className:"chat-header",children:[G("h3",{children:t.title}),t.features.minimizable&&G("button",{className:"minimize-button",onClick:this.handleMinimizeClick,title:"Minimize chat","aria-label":"Minimize chat",type:"button",children:G(Te,{type:"minimize",customUrl:null==(e=t.customIcons)?void 0:e.minimize,className:"minimize-icon"})})]})}}class Be extends L{constructor(e){super(e),x(this,"inputRef",{current:null}),x(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 v(this,null,function*(){const e=this.state.message.trim();if(e&&!this.props.isLoading){X.debug("Sending message",{length:e.length}),this.setState({message:""});try{yield this.props.onSendMessage(e),this.inputRef.current&&this.inputRef.current.focus()}catch(t){X.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 G("div",{children:[G("div",{className:"input-container",children:[G("div",{className:"input-wrapper",children:[G("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}),G("button",{className:"send-button",onClick:this.handleSubmit,disabled:!i,title:n?"Sending...":"Send message",type:"button",children:n?G("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"}}):G(Te,{type:"send",customUrl:null==(e=this.props.config.customIcons)?void 0:e.send,className:"send-icon"})})]}),G("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 "})]}),G("div",{style:{textAlign:"center",fontSize:"14px",fontWeight:600,paddingBottom:"16px"},className:"powered-by",children:["Powered by ",G("a",{href:"https://paperlinkai.com/",target:"_blank",rel:"noopener noreferrer",children:"PaperlinkAi"})]})]})}}class $e{static querySelector(e,t=document){try{return t.querySelector(e)}catch(n){return X.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 Ne extends L{render(){const{config:e,message:t="Loading chat history..."}=this.props;return G("div",{className:"loading-indicator",style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"32px",flex:"1"},children:[G("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:`${e.theme.textColor}80`,fontSize:"14px"},children:[G("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"}}),G("span",{children:t})]}),G("style",{children:"\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n "})]})}}class De extends L{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?G("div",{className:"message-sources",children:[G("button",{className:"sources-toggle",onClick:this.handleToggleSources,type:"button",children:[G("span",{className:"material-icons toggle-icon "+(t?"expanded":""),children:"chevron_right"}),e.sources.length," source",e.sources.length>1?"s":""]}),t&&G("div",{className:"sources-list",children:e.sources.map((e,t)=>G("div",{className:"source-item",children:[G("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"source-link",children:e.title}),G("div",{className:"source-snippet",children:e.snippet})]},t))})]}):null}render(){var e;const{message:t}=this.props,n="USER"===t.role.toUpperCase();return G("div",{className:"message "+(n?"user":"bot"),children:[!n&&G("div",{className:"bot-avatar",children:G(Te,{type:"bot",customUrl:null==(e=this.props.config.customIcons)?void 0:e.bot,className:"bot-icon"})}),G("div",{className:"message-content",children:[G("p",{dangerouslySetInnerHTML:{__html:this.formatMessageContent(t.content)}}),this.renderSources()]})]})}}class Ue extends L{render(){var e;const{config:t}=this.props;return G("div",{className:"typing-indicator",children:[G("div",{className:"bot-avatar",children:G(Te,{type:"bot",customUrl:null==(e=t.customIcons)?void 0:e.bot,className:"bot-icon"})}),G("div",{className:"typing-dots",children:[G("div",{className:"typing-dot"}),G("div",{className:"typing-dot"}),G("div",{className:"typing-dot"})]})]})}}class Pe extends L{constructor(e){super(e),x(this,"listRef",{current:null}),x(this,"scrollThreshold"),x(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=$e.debounce(this.scrollToBottom,100)}componentDidMount(){X.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 G("div",{className:"message",children:[G("div",{className:"bot-avatar",children:G(Te,{type:"bot",customUrl:null==(e=t.customIcons)?void 0:e.bot,className:"bot-icon"})}),G("div",{className:"message-content",children:G("p",{children:t.greeting})})]})}renderScrollToBottomButton(){var e;return this.state.showScrollButton?G("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:G(Te,{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 G("div",{className:"messages-container",ref:this.listRef,children:[n?G(Ne,{config:e,message:"Loading chat history..."}):G(T,{children:[this.renderWelcomeMessage(),t.messages.map((n,o)=>G(De,{message:n,config:e,isLastMessage:o===t.messages.length-1},n.id)),t.isLoading&&e.features.typing&&G(Ue,{config:e})]}),this.renderScrollToBottomButton()]})}}class Oe extends L{constructor(e){super(e),x(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 G("div",{ref:this.windowRef,className:a,children:[G(Re,{config:e,onMinimize:i,onClose:s}),G(Pe,{config:e,session:t,isInitialLoading:n}),G(Be,{config:e,isLoading:t.isLoading,onSendMessage:o})]})}}class We extends L{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 G("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:[G("svg",{style:{width:"20px",height:"20px",flexShrink:"0",color:"#dc2626"},fill:"currentColor",viewBox:"0 0 20 20",children:G("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"})}),G("div",{style:{flex:"1",display:"flex",flexDirection:"column",gap:"8px"},children:[G("p",{style:{color:"#991b1b",fontSize:"14px",lineHeight:"1.4",margin:"0"},children:t||"Something went wrong. Please try again."}),G("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:G(T,n?{children:[G("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:G("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:[G("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:G("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"]})})]}),G("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 Fe extends L{constructor(e){super(e),x(this,"apiClient"),this.apiClient=new te(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 v(this,null,function*(){X.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(){X.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 v(this,null,function*(){try{this.setState({isLoading:!0,error:null});const e=ne.get("sessionId"),t=ne.get("messages")||[];if(e&&t.length>0)return X.info("Restoring session from storage",{sessionId:e}),void this.setState({session:{sessionId:e,messages:t,isLoading:!1,error:null},isLoading:!1});X.info("Ready for new session - will be created with first message"),this.setState({session:{sessionId:"",messages:[],isLoading:!1,error:null},isLoading:!1})}catch(e){X.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 v(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:y(b({},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:y(b({},e.session),{sessionId:t.sessionId,messages:[...e.session.messages,t.assistantMessage],isLoading:!1})})),ne.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){X.error("Failed to send message",{error:n});const t=n instanceof Error?n.message:"Failed to send message";this.setState(n=>({session:y(b({},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 v(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){ne.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){X.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 X.info("Widget render",{isOpen:t,isLoading:n,isMinimized:s,hasNewMessage:r,sessionId:o.sessionId,error:!!i}),n&&!o.sessionId?G("div",{className:"widget-loading",children:G("div",{className:"loading-spinner"})}):i&&!o.sessionId?G("div",{className:"widget-error",children:G(We,{config:e,error:"Unable to load chat widget. Please check your connection and try again.",onRetry:()=>this.initializeSession(),isRetrying:n})}):G("div",{className:"paperlink-widget",children:[t&&!s&&G(Oe,{config:e,session:o,isInitialLoading:n&&!o.sessionId,onSendMessage:this.handleSendMessage,onMinimize:this.handleMinimize,onClose:this.handleClose}),t&&!s&&i&&G("div",{style:{position:"fixed",bottom:"80px",right:"20px",zIndex:"999997",maxWidth:"380px"},children:G(We,{config:e,error:i,onRetry:this.handleRetryLastMessage,isRetrying:a})}),G(Le,{config:e,isOpen:t,hasNewMessage:r,onClick:this.handleToggleWidget})]})}}const He={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",headerBackgroundColor:"#f9fafb",textColor:"#1f2937",secondaryTextColor:"#6b7280",borderColor:"#e5e7eb",userMessageColor:"#2563eb",botMessageColor:"#f3f4f6",botAvatarColor:"#dbeafe",inputBackgroundColor:"#f3f4f6",inputTextColor:"#1f2937",buttonColor:"#2563eb",buttonHoverColor:"#1d4ed8",buttonTextColor:"#ffffff",shadowColor:"rgba(0, 0, 0, 0.25)",scrollButtonColor:"rgba(255, 255, 255, 0.8)"},features:{fileUpload:!1,typing:!0,sound:!1,minimizable:!0,scrollToBottom:!0,scrollToBottomThreshold:100},maxMessages:50,autoOpen:!1,customIcons:{bot:void 0,send:void 0,minimize:void 0,scrollDown:void 0,chatButton:void 0},showPoweredBy:!0,chatButtonBackgroundColor:void 0,showChatButtonBackground:!0,metadata:void 0},Ae={required:["apiKey"],validPositions:["bottom-right","bottom-left","top-right","top-left"],numberRanges:{width:{min:320,max:800},height:{m