@returningai/widget-sdk 1.2.4 → 1.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/rai-widget.iife.js +1 -1
- package/dist/rai-widget.js +83 -99
- package/dist/types/BaseWidget.d.ts +10 -16
- package/dist/types/types.d.ts +19 -0
- package/package.json +1 -1
package/dist/rai-widget.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var RaiWidget=function(e){"use strict";var t=Object.defineProperty,r=(e,r,i)=>((e,r,i)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i)(e,"symbol"!=typeof r?r+"":r,i);function i(e){return`${e.storagePrefix}-${e.widgetId}-auth`}function a(e){return`${e.storagePrefix}-${e.widgetId}-error-settings`}function n(e){try{localStorage.removeItem(i(e))}catch{}}function o(e){return!e||Date.now()>=e-6e4}function s(e,t,r,a){t.accessToken=r.accessToken,t.refreshToken=r.refreshToken,t.tokenFamily=r.tokenFamily??null;const n=Date.now();t.accessTokenExpiry=n+1e3*r.accessTokenTTL,t.refreshTokenExpiry=n+1e3*r.refreshTokenTTL,function(e,t){try{const r={refreshToken:t.refreshToken,tokenFamily:t.tokenFamily,refreshTokenExpiry:t.refreshTokenExpiry};localStorage.setItem(i(e),JSON.stringify(r))}catch{}}(e,t),e.autoRefresh&&a&&a()}async function l(e,t,r){const i=crypto.randomUUID(),a=Date.now(),n=e.maxRetries??3,o=e.retryDelay??500;for(let l=0;l<=n;l++){l>0&&await new Promise(e=>setTimeout(e,o*(1<<l-1)));let c=!1;try{const n=await fetch(`${e.apiUrl}/${e.widgetId}/auth/serverless`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nonce:i,timestamp:a,widgetType:e.widgetType,userIdentifiers:e.userIdentifiers}),credentials:"include"});if(!n.ok){c=n.status>=400&&n.status<500;const e=await n.json().catch(()=>({error:"Authentication failed"}));throw new Error(e.error||`HTTP ${n.status}`)}const o=await n.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid authentication response");return s(e,t,o,r),t.isAuthenticated=!0,!0}catch{if(c||l===n)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function c(e,t,r){const i=e.maxRetries??3,a=e.retryDelay??500;for(let n=0;n<=i;n++){n>0&&await new Promise(e=>setTimeout(e,a*(1<<n-1)));let o=!1;try{const i=await fetch(e.authUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(!i.ok)throw o=i.status>=400&&i.status<500,new Error(`HTTP ${i.status}`);const a=await i.json();if(!a.token)throw new Error("Invalid proxy auth response");const n=a.expiresIn??300;return t.accessToken=a.token,t.refreshToken=null,t.tokenFamily=null,t.accessTokenExpiry=Date.now()+1e3*n,t.refreshTokenExpiry=null,t.isAuthenticated=!0,e.autoRefresh&&r&&r(),!0}catch{if(o||n===i)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function d(e,t,r,i){return t.isRefreshing?t.refreshPromise:!!t.refreshToken&&(t.isRefreshing=!0,t.refreshPromise=(async()=>{try{const a=await fetch(`${e.apiUrl}/${e.widgetId}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.refreshToken}`},body:JSON.stringify({widgetType:e.widgetType})});if(!a.ok){if(401===a.status||403===a.status)return u(t),n(e),l(e,t,r);const i=await a.json().catch(()=>({error:"Token refresh failed"}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid refresh response");return s(e,t,o,r),i&&i(),!0}catch{return u(t),n(e),l(e,t,r)}finally{t.isRefreshing=!1,t.refreshPromise=null}})(),t.refreshPromise)}async function h(e,t){const r=function(e){try{const t=localStorage.getItem(a(e));if(!t)return null;const r=JSON.parse(t);return r.cachedAt&&Date.now()-r.cachedAt<36e5?r:(localStorage.removeItem(a(e)),null)}catch{return null}}(e);if(r)return r.configured&&(t.errorSettings={errorMessage:r.errorMessage,modalColor:r.modalColor,backgroundImage:r.backgroundImage}),t.errorSettings;try{const r=await fetch(`${e.apiUrl}/${e.widgetId}/auth/error-settings?widgetType=${e.widgetType}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!r.ok)return null;const i=await r.json();return function(e,t){try{localStorage.setItem(a(e),JSON.stringify({...t,cachedAt:Date.now()}))}catch{}}(e,i),i.configured&&(t.errorSettings={errorMessage:i.errorMessage,modalColor:i.modalColor,backgroundImage:i.backgroundImage}),t.errorSettings}catch{return null}}function u(e){e.accessToken=null,e.refreshToken=null,e.tokenFamily=null,e.accessTokenExpiry=null,e.refreshTokenExpiry=null,e.isAuthenticated=!1,e.isRefreshing=!1,e.refreshPromise=null,e.refreshTimer&&(clearTimeout(e.refreshTimer),e.refreshTimer=null),e.syncTimer&&(clearInterval(e.syncTimer),e.syncTimer=null)}function m(e,t,r){var i;if(t.accessToken)try{null==(i=r.contentWindow)||i.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{widgetId:e.widgetId,token:t.accessToken,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}}function p(e,t,r,i,a,n,s,h){const u=function(e,t){let r=null;return{call(i){r&&clearTimeout(r),r=setTimeout(()=>{e(i),r=null},t)},cancel(){r&&(clearTimeout(r),r=null)}}}(e=>{i.style.height=`${e}px`,null==h||h("rai-height-change",{height:e})},e.heightDebounce??100),m=async r=>{var m;if(r.origin!==e.widgetDomain)return;if(!r.data||"string"!=typeof r.data.type)return;const{type:p,containerId:g,widgetId:f,payload:w}=r.data;switch(p){case"RETURNINGAI_WIDGET_REQUEST_TOKEN":try{const r=await async function(e,t,r){if(t.accessToken&&!o(t.accessTokenExpiry))return t.accessToken;if(e.authUrl){if(await c(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}if(await d(e,t,r)&&t.accessToken)return t.accessToken;if(await l(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}(e,t,a);null==(m=i.contentWindow)||m.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{token:r,widgetId:e.widgetId,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}break;case"WIDGET_HEIGHT_UPDATE":{const e=Number(null==w?void 0:w.height);Number.isFinite(e)&&e>0&&u.call(e);break}case"WIDGET_READY":if(void 0!==f&&f!==e.widgetId)break;if(void 0!==g&&g!==e.container)break;i.classList.add("loaded"),s&&s(),null==h||h("rai-ready");break;case"WIDGET_ERROR":s&&s();break;case"WIDGET_LOGOUT":n&&await n()}};return window.addEventListener("message",m),()=>{window.removeEventListener("message",m),u.cancel()}}const g=new Set(["community-id","channel-id","widget-id","widget-type","theme","container","width","height","api-url","widget-url","auto-refresh","debug","storage-prefix","max-retries","retry-delay","height-debounce","locale","custom-data","retry-label","auth-url","bundle-url","embed-token","v2-api-url"]),f={store:"RaiStoreWidget",channel:"RaiChannelWidget",social:"RaiSocialWidget",milestone:"RaiMilestoneWidget","currency-view":"RaiCurrencyWidget","referral-conditions":"RaiReferralWidget",custom:"RaiCustomWidget"},w={"RAI-STORE-WIDGET":"store","RAI-CHANNEL-WIDGET":"channel","RAI-MILESTONE-WIDGET":"milestone","RAI-SOCIAL-WIDGET":"social","RAI-CURRENCY-WIDGET":"currency-view","RAI-REFERRAL-WIDGET":"referral-conditions","RAI-CUSTOM-WIDGET":"custom","RAI-WIDGET":"store"};class y extends HTMLElement{constructor(){super(),r(this,"shadow"),r(this,"config"),r(this,"state",{accessToken:null,refreshToken:null,tokenFamily:null,accessTokenExpiry:null,refreshTokenExpiry:null,refreshTimer:null,syncTimer:null,iframe:null,isAuthenticated:!1,isRefreshing:!1,refreshPromise:null,errorSettings:null}),r(this,"loaderEl",null),r(this,"errorEl",null),r(this,"msgEl",null),r(this,"cleanupListener"),r(this,"intersectionObserver"),r(this,"themeObserver"),r(this,"loaderObserver"),this.shadow=this.attachShadow({mode:"closed"})}connectedCallback(){this.config=function(e,t){const r=t=>e.getAttribute(t)??e.getAttribute(`data-${t}`)??"",i=(e,t)=>{const i=parseInt(r(e),10);return Number.isFinite(i)&&i>=0?i:t},a=!!r("community-id"),n=r("community-id")||r("widget-id")||t||"";if(n&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(n))throw new Error(`[rai-widget] Invalid community-id: "${n}"`);const o=r("channel-id")||void 0;if(o&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(o))throw new Error(`[rai-widget] Invalid channel-id: "${o}"`);const s=r("widget-type")||w[e.tagName]||"store";let l;l=a?"store"===s?n:"channel"===s?o?btoa(o):n:n?btoa(n):n:n;let c,d=r("widget-url")||"https://widget.returningai.com";d.endsWith("store-widget")&&(d=`${d}/${n}/open-widget`);try{c=new URL(d).origin}catch{c=d}if(d.includes("store-widget")){const e=new URL(d);e.searchParams.set("color",r("theme")||"light"),d=e.toString()}const h=r("container")||r("data-container")||`returning-ai-widget-${n}`,u={};Array.from(e.attributes).forEach(e=>{const t=e.name.toLowerCase();if(!t.startsWith("data-"))return;const r=t.slice(5);g.has(r)||(u[t]=e.value)});const m=(()=>{const e=r("custom-data");if(e)try{return JSON.parse(e)}catch{return}})();return{communityId:n,channelId:o,widgetId:l,widgetType:s,theme:r("theme")||"light",container:h,width:r("width")||"100%",height:r("height")||"600px",apiUrl:r("api-url")||"https://sgtr-eks-widgets.genesiv.org",widgetUrl:d,widgetDomain:c,autoRefresh:"false"!==r("auto-refresh"),debug:"true"===r("debug"),storagePrefix:r("storage-prefix")||"returning-ai-widget",userIdentifiers:u,maxRetries:i("max-retries",3),retryDelay:i("retry-delay",500),heightDebounce:i("height-debounce",100),locale:r("locale")||void 0,customData:m,authUrl:r("auth-url")||void 0,bundleUrl:r("bundle-url")||void 0,embedToken:r("embed-token")||void 0,v2ApiUrl:r("v2-api-url")||void 0}}(this,void 0);const e=document.createElement("style");e.textContent=':host{display:block;position:relative;width:100%;height:100%}.rai-loader{position:absolute;top:0;left:0;display:flex;align-items:center;justify-content:center;width:100%;height:100%;background:var(--rai-loader-bg, #ffffff);border-radius:8px;z-index:10;transition:opacity .3s ease-out}.rai-loader.fade-out{opacity:0;pointer-events:none}.rai-error{display:none;position:absolute;top:0;left:0;width:100%;height:100%;align-items:center;justify-content:center;flex-direction:column;gap:12px;background:var(--rai-error-bg, #1a1a1a);border-radius:8px;padding:24px;box-sizing:border-box;text-align:center;color:var(--rai-error-text, #9ca3af);font-family:system-ui,-apple-system,sans-serif;z-index:10}.rai-error.visible{display:flex}iframe{display:block;border:none;opacity:0;transition:opacity .3s ease-in}iframe.loaded{opacity:1}.rai-lottie-loader{width:100px;height:100px}.rai-lottie-loader svg{width:100%!important;height:100%!important}.rai-lottie-spinner{width:32px;height:32px;margin:34px auto;border:3px solid var(--rai-text4, #6b7280);border-top-color:var(--rai-accent, #000000);border-radius:50%;animation:rai-spin .7s linear infinite}@keyframes rai-spin{to{transform:rotate(360deg)}}.rai-sdk-loader{position:relative;width:75px;height:100px}.rai-sdk-loader__bar{position:absolute;bottom:0;width:10px;height:50%;background:var(--rai-accent, #000000);transform-origin:center bottom;box-shadow:1px 1px #0003}.rai-sdk-loader__bar:nth-child(1){left:0;transform:scaleY(.2);animation:rai-sdk-barUp1 4s infinite}.rai-sdk-loader__bar:nth-child(2){left:15px;transform:scaleY(.4);animation:rai-sdk-barUp2 4s infinite}.rai-sdk-loader__bar:nth-child(3){left:30px;transform:scaleY(.6);animation:rai-sdk-barUp3 4s infinite}.rai-sdk-loader__bar:nth-child(4){left:45px;transform:scaleY(.8);animation:rai-sdk-barUp4 4s infinite}.rai-sdk-loader__bar:nth-child(5){left:60px;transform:scale(1);animation:rai-sdk-barUp5 4s infinite}.rai-sdk-loader__ball{position:absolute;bottom:10px;left:0;width:10px;height:10px;background:var(--rai-accent, #000000);border-radius:50%;animation:rai-sdk-ball 4s infinite}@keyframes rai-sdk-ball{0%{transform:translate(0)}5%{transform:translate(8px,-14px)}10%{transform:translate(15px,-10px)}17%{transform:translate(23px,-24px)}20%{transform:translate(30px,-20px)}27%{transform:translate(38px,-34px)}30%{transform:translate(45px,-30px)}37%{transform:translate(53px,-44px)}40%{transform:translate(60px,-40px)}50%{transform:translate(60px)}57%{transform:translate(53px,-14px)}60%{transform:translate(45px,-10px)}67%{transform:translate(37px,-24px)}70%{transform:translate(30px,-20px)}77%{transform:translate(22px,-34px)}80%{transform:translate(15px,-30px)}87%{transform:translate(7px,-44px)}90%{transform:translateY(-40px)}to{transform:translate(0)}}@keyframes rai-sdk-barUp1{0%{transform:scaleY(.2)}40%{transform:scaleY(.2)}50%{transform:scale(1)}90%{transform:scale(1)}to{transform:scaleY(.2)}}@keyframes rai-sdk-barUp2{0%{transform:scaleY(.4)}40%{transform:scaleY(.4)}50%{transform:scaleY(.8)}90%{transform:scaleY(.8)}to{transform:scaleY(.4)}}@keyframes rai-sdk-barUp3{0%{transform:scaleY(.6)}to{transform:scaleY(.6)}}@keyframes rai-sdk-barUp4{0%{transform:scaleY(.8)}40%{transform:scaleY(.8)}50%{transform:scaleY(.4)}90%{transform:scaleY(.4)}to{transform:scaleY(.8)}}@keyframes rai-sdk-barUp5{0%{transform:scale(1)}40%{transform:scale(1)}50%{transform:scaleY(.2)}90%{transform:scaleY(.2)}to{transform:scale(1)}}#loading-square{width:75px;aspect-ratio:1;display:flex;color:var(--rai-accent, #000000);background:linear-gradient(currentColor 0 0) right / 51% 100%,linear-gradient(currentColor 0 0) bottom / 100% 51%;background-repeat:no-repeat;animation:l16-0 2s infinite linear .25s}#loading-square>div{width:50%;height:50%;background:currentColor;animation:l16-1 .5s infinite linear}@keyframes l16-0{0%,12.49%{transform:rotate(0)}12.5%,37.49%{transform:rotate(90deg)}37.5%,62.49%{transform:rotate(180deg)}62.5%,87.49%{transform:rotate(270deg)}87.5%,to{transform:rotate(360deg)}}@keyframes l16-1{0%{transform:perspective(80px) rotate3d(-1,-1,0,0)}80%,to{transform:perspective(80px) rotate3d(-1,-1,0,-180deg)}}#loading-circle{width:75px;aspect-ratio:1;display:grid;grid:50%/50%;color:var(--rai-accent, #000000);border-radius:50%;--_g: no-repeat linear-gradient(currentColor 0 0);background:var(--_g),var(--_g),var(--_g);background-size:50.1% 50.1%;animation:l9-0 1.5s infinite steps(1) alternate,l9-0-0 3s infinite steps(1) alternate}#loading-circle>div{background:var(--rai-text4, #6b7280);border-top-left-radius:100px;transform:perspective(150px) rotateY(0) rotateX(0);transform-origin:bottom right;animation:l9-1 1.5s infinite linear alternate}@keyframes l9-0{0%{background-position:0 100%,100% 100%,100% 0}33%{background-position:100% 100%,100% 100%,100% 0}66%{background-position:100% 0,100% 0,100% 0}}@keyframes l9-0-0{0%{transform:scaleX(1) rotate(0)}50%{transform:scaleX(-1) rotate(-90deg)}}@keyframes l9-1{16.5%{transform:perspective(150px) rotateX(-90deg) rotateY(0) rotateX(0);filter:grayscale(.8)}33%{transform:perspective(150px) rotateX(-180deg) rotateY(0) rotateX(0)}66%{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(0)}to{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(-180deg);filter:grayscale(.8)}}.rai-custom-error{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10}.tiptap strong.tw-font-bold,.tiptap b.tw-font-bold{font-weight:700}.tiptap em.tw-font-italic,.tiptap i.tw-font-italic{font-style:italic}.tiptap a.tiptap-rich-text-link{color:#3b82f6;text-decoration:underline;position:relative;display:inline-block;width:fit-content}.tiptap a.tiptap-rich-text-link:hover{color:#3b82f6cc;text-decoration:none}.tiptap a.tiptap-rich-text-link:not([title=""]):before{content:attr(title);position:absolute;top:-2rem;left:50%;transform:translate(-50%);white-space:nowrap;border-radius:.25rem;background-color:#000;padding:.25rem .5rem;color:#fff;opacity:0;transition:opacity .2s;pointer-events:none}.tiptap a.tiptap-rich-text-link:not([title=""]):hover:before{opacity:1}.tiptap p[style*="text-align: left"]{text-align:left}.tiptap p[style*="text-align: center"]{text-align:center}.tiptap p[style*="text-align: right"]{text-align:right}.tiptap p[style*="text-align: justify"]{text-align:justify}.tiptap u{text-decoration:underline}.tiptap.ProseMirror{background-color:transparent;height:fit-content!important;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;padding:0;width:100%;overflow-y:auto}.tiptap{line-height:1.6;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.tiptap p{margin:.5em 0}.tiptap p:first-child{margin-top:0}.tiptap p:last-child{margin-bottom:0}.tiptap img{max-width:100%;height:auto;display:block}.tiptap p[style*="text-align: left"] img{margin-left:0;margin-right:auto}.tiptap p[style*="text-align: center"] img{margin-left:auto;margin-right:auto}.tiptap p[style*="text-align: right"] img{margin-left:auto;margin-right:0}.rai-retry-btn{padding:8px 20px;border:none;border-radius:6px;background:var(--rai-accent, #000000);color:var(--rai-error-bg, #ffffff);font-size:14px;font-family:system-ui,-apple-system,sans-serif;cursor:pointer}.rai-retry-btn:hover{opacity:.85}',this.shadow.appendChild(e);const t=this.config.theme,r="dark"===t?"#ffffff":"#000000",i="dark"===t?"#9ca3af":"#6b7280",a="dark"===t?"#1a1a1a":"#ffffff";this.style.width=this.config.width,this.style.height=this.config.height,this.style.setProperty("--rai-accent",r),this.style.setProperty("--rai-text4",i),this.style.setProperty("--rai-loader-bg",a),this.style.setProperty("--rai-error-bg",a),this.renderShell(),this.hasAttribute("eager")?this.init():(this.intersectionObserver=new IntersectionObserver(e=>{e[0].isIntersecting&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0,this.init())}),this.intersectionObserver.observe(this))}disconnectedCallback(){var e,t,r;null==(e=this.intersectionObserver)||e.disconnect(),null==(t=this.themeObserver)||t.disconnect(),null==(r=this.loaderObserver)||r.disconnect(),this.cleanupListener&&this.cleanupListener(),u(this.state)}emit(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t??{}}))}renderShell(){this.loaderEl=document.createElement("div"),this.loaderEl.className="rai-loader",this.shadow.appendChild(this.loaderEl),this.resolveLoader(),this.errorEl=document.createElement("div"),this.errorEl.className="rai-error",this.msgEl=document.createElement("span"),this.msgEl.className="rai-error-msg",this.msgEl.textContent="Authentication failed. Please try again later.",this.errorEl.appendChild(this.msgEl);const e=this.getAttribute("retry-label")||this.getAttribute("data-retry-label")||"Retry",t=document.createElement("button");t.className="rai-retry-btn",t.textContent=e,t.addEventListener("click",()=>this.reload()),this.errorEl.appendChild(t),this.shadow.appendChild(this.errorEl)}resolveLoader(){const e=this.querySelector(".widget-loader");e?this.applyLoader(e):(this.loaderObserver=new MutationObserver(()=>{const e=this.querySelector(".widget-loader");e&&(this.loaderObserver.disconnect(),this.loaderObserver=void 0,this.applyLoader(e))}),this.loaderObserver.observe(this,{childList:!0,subtree:!0}),setTimeout(()=>{this.loaderObserver&&(this.loaderObserver.disconnect(),this.loaderObserver=void 0,this.loaderEl&&0===this.loaderEl.childElementCount&&this.loaderEl.appendChild(this.createDefaultLoader()))},50))}applyLoader(e){this.loaderEl&&this.renderCustomLoader(e)}createDefaultLoader(){const e=document.createElement("div");e.className="rai-sdk-loader";for(let r=0;r<5;r++){const t=document.createElement("div");t.className="rai-sdk-loader__bar",e.appendChild(t)}const t=document.createElement("div");return t.className="rai-sdk-loader__ball",e.appendChild(t),e}createPresetLoader(e){if("square"===e){const e=document.createElement("div");e.id="loading-square";const t=document.createElement("div");return e.appendChild(t),e}if("circle"===e){const e=document.createElement("div");e.id="loading-circle";const t=document.createElement("div");return e.appendChild(t),e}return this.createDefaultLoader()}renderCustomLoader(e){const t=e.getAttribute("data-loader-type");if("lottie"===t){const t=e.querySelector(".lottie-data");if(t)try{const e=JSON.parse(t.textContent||""),r=document.createElement("div");r.className="rai-lottie-loader";const i=document.createElement("div");i.className="rai-lottie-spinner",r.appendChild(i),this.loaderEl.appendChild(r);const a=window;if(void 0!==a.lottie)a.lottie.loadAnimation({container:r,renderer:"svg",loop:!0,autoplay:!0,animationData:e});else{const t=document.createElement("script");t.src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js",t.onload=()=>{window.lottie.loadAnimation({container:r,renderer:"svg",loop:!0,autoplay:!0,animationData:e})},document.head.appendChild(t)}}catch{this.loaderEl.appendChild(this.createDefaultLoader())}else this.loaderEl.appendChild(this.createDefaultLoader())}else if("custom"===t){const t=document.createElement("div");t.innerHTML=e.innerHTML,this.loaderEl.appendChild(t)}else if("preset"===t){const t=e.getAttribute("data-preset");this.loaderEl.appendChild(this.createPresetLoader(t))}else this.loaderEl.appendChild(this.createDefaultLoader());e.remove()}hideLoader(){this.loaderEl&&(this.loaderEl.classList.add("fade-out"),setTimeout(()=>{var e;return null==(e=this.loaderEl)?void 0:e.remove()},300),this.loaderEl=null)}showError(){this.hideLoader();const e=this.state.errorSettings;(null==e?void 0:e.errorMessage)?this.renderCustomError(e):this.errorEl&&this.errorEl.classList.add("visible"),this.emit("rai-error",{message:(null==e?void 0:e.errorMessage)??"Authentication failed"})}renderCustomError(e){var t,r;null==(t=this.errorEl)||t.remove(),this.errorEl=null;const i=(null==(r=e.backgroundImage)?void 0:r.trim())?`background-image: url('${e.backgroundImage}'); background-size: cover; background-position: center; background-repeat: no-repeat;`:"",a=document.createElement("div");a.className="rai-custom-error",a.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: auto;\n width: 100%;\n height: 100%;\n ${i}\n `;const n=document.createElement("div");n.className="rai-rich-text",n.style.cssText=`\n min-width: 50%;\n min-height: 50%;\n margin: 0 auto;\n padding: 20px;\n width: auto;\n height: auto;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 6px;\n background-color: ${e.modalColor||"transparent"};\n `;const o=document.createElement("div");o.className="tiptap ProseMirror",o.innerHTML=e.errorMessage||"",n.appendChild(o),a.appendChild(n),this.shadow.appendChild(a)}async init(){if(!this.config.communityId)return void this.showError();if(await h(this.config,this.state),this.config.embedToken){if(!(await async function(e){try{const t=e.v2ApiUrl||e.apiUrl;return(await fetch(`${t}/v2/api/widget-access-keys/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:e.embedToken})})).ok}catch{return!1}}(this.config)))return void this.showError()}const e=()=>{this.config.bundleUrl?this.mountWidget():this.createIframe()};if(this.config.authUrl){return void(await c(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError())}if(function(e,t){try{const r=localStorage.getItem(i(e));if(!r)return!1;const a=JSON.parse(r);return a.refreshToken&&!o(a.refreshTokenExpiry)?(t.refreshToken=a.refreshToken,t.tokenFamily=a.tokenFamily,t.refreshTokenExpiry=a.refreshTokenExpiry,!0):(n(e),!1)}catch{return!1}}(this.config,this.state)){return await d(this.config,this.state,()=>this.scheduleRefresh())?(this.state.isAuthenticated=!0,this.emit("rai-authenticated"),void e()):void this.showError()}await l(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError()}createIframe(){const e=document.createElement("iframe");e.src=this.buildWidgetUrl(this.config),e.allow="clipboard-write",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),e.frameBorder="0",e.scrolling="no",e.style.width=this.config.width,e.style.height=this.config.height,e.style.border="none",e.style.display="block",e.onload=()=>{m(this.config,this.state,e),this.schedulePeriodicSync(e)},e.onerror=()=>{this.showError()},this.state.iframe=e,this.shadow.appendChild(e),this.cleanupListener=p(this.config,this.state,this.shadow,e,()=>this.scheduleRefresh(),()=>this.logoutAndClear(),()=>this.hideLoader(),(e,t)=>this.emit(e,t))}async mountWidget(){try{const t=window,r=["api_url","base_url","auth_api","socket_path_v2","socket_path","channel_api"];for(const e of r)t[e]||(t[e]=this.config.apiUrl);window.__IS_WIDGET__=!0,window.guest_token=this.state.accessToken,await(e=this.config.bundleUrl,new Promise((t,r)=>{const i=document.createElement("script");i.src=e,i.onload=()=>t(),i.onerror=()=>r(new Error(`Failed to load ${e}`)),document.head.appendChild(i)}));const i=f[this.config.widgetType],a=window[i];if(!(null==a?void 0:a.mount))throw new Error(`window.${i}.mount not found after loading bundle`);const n=document.createElement("div");if(n.style.cssText="position: relative; width: 100%; height: 100%;",this.appendChild(n),!this.shadow.querySelector("slot")){const e=document.createElement("slot");this.shadow.appendChild(e)}this.loaderEl&&(this.loaderEl.remove(),this.loaderEl=null),a.mount(n,{widgetType:this.config.widgetType,communityId:this.config.communityId,channelId:this.config.channelId,widgetId:this.config.communityId,apiUrl:this.config.apiUrl,token:this.state.accessToken,basePath:"/",isPreview:!1,isOpenWidget:!0,defaultColorSchema:"dark"===this.config.theme?"dark":"light"}),this.emit("rai-mounted")}catch(t){console.error("[rai-widget] Bundle mount failed:",t),this.showError()}var e}scheduleRefresh(){if(this.state.refreshTimer&&clearTimeout(this.state.refreshTimer),!this.state.accessTokenExpiry)return;const e=this.state.accessTokenExpiry-Date.now()-6e4,t=()=>{this.state.iframe&&m(this.config,this.state,this.state.iframe),this.config.bundleUrl&&this.state.accessToken&&(window.guest_token=this.state.accessToken)},r=async()=>{if(this.config.authUrl){await c(this.config,this.state,()=>this.scheduleRefresh())&&t()}else await d(this.config,this.state,()=>this.scheduleRefresh(),t)};e>0?this.state.refreshTimer=setTimeout(r,e):r()}schedulePeriodicSync(e){this.state.syncTimer&&clearInterval(this.state.syncTimer),this.state.syncTimer=setInterval(()=>{this.state.accessToken&&m(this.config,this.state,e)},12e4)}async logoutAndClear(){await async function(e,t){if(t.accessToken)try{await fetch(`${e.apiUrl}/${e.widgetId}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({refreshToken:t.refreshToken})})}catch{}u(t),n(e)}(this.config,this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),this.emit("rai-logout")}async reload(){u(this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),await this.init()}async logoutPublic(){await this.logoutAndClear()}isAuthenticated(){return this.state.isAuthenticated&&null!==this.state.accessToken}getTokenInfo(){return{hasAccessToken:!!this.state.accessToken,hasRefreshToken:!!this.state.refreshToken,accessTokenExpiry:this.state.accessTokenExpiry?new Date(this.state.accessTokenExpiry):null,refreshTokenExpiry:this.state.refreshTokenExpiry?new Date(this.state.refreshTokenExpiry):null,isAccessTokenValid:!!this.state.accessToken&&!o(this.state.accessTokenExpiry),isRefreshTokenValid:!!this.state.refreshToken&&!o(this.state.refreshTokenExpiry)}}}class b extends y{buildWidgetUrl(e){const t=new URL(e.widgetUrl);return t.searchParams.set("color",e.theme),t.searchParams.set("containerId",e.container),t.searchParams.set("connectType","simple"),t.searchParams.set("mode","private"),e.locale&&t.searchParams.set("locale",e.locale),t.toString()}}class k extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("channel-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class v extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("milestone-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class T extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("social-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class x extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("currency-overview-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class E extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("referral-conditions-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class I extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("custom-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}console.log("[rai-widget] v1.2.4");const U=[["rai-store-widget",b],["rai-channel-widget",k],["rai-milestone-widget",v],["rai-social-widget",T],["rai-currency-widget",x],["rai-referral-widget",E],["rai-custom-widget",I],["rai-widget",class extends b{}]];for(const[$,D]of U)customElements.get($)||customElements.define($,D);const C={store:b,channel:k,milestone:v,social:T,"currency-view":x,"referral-conditions":E,custom:I},A=U.map(([e])=>e).join(", ");function S(){var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return;const i=r.getAttribute("data-community-id")||r.getAttribute("data-widget-id");if(!i)return;const a=r.getAttribute("data-container")||`returning-ai-widget-${i}`,n=document.getElementById(a);if(!n)return;"static"===getComputedStyle(n).position&&(n.style.position="relative");const o=r.getAttribute("data-widget-type")??"store",s=new(C[o]??b);Array.from(r.attributes).forEach(e=>{s.setAttribute(e.name,e.value)}),n.appendChild(s)}function R(){const e=(()=>{var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return null;const i=r.getAttribute("data-container")||`returning-ai-widget-${r.getAttribute("data-community-id")||r.getAttribute("data-widget-id")}`;return document.getElementById(i)})(),t=null==e?void 0:e.querySelector(A);window.ReturningAIWidget={version:"1.2.4",reload:()=>(null==t?void 0:t.reload())??Promise.resolve(),logout:()=>(null==t?void 0:t.logoutPublic())??Promise.resolve(),isAuthenticated:()=>(null==t?void 0:t.isAuthenticated())??!1,getTokenInfo:()=>(null==t?void 0:t.getTokenInfo())??{}}}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",S):S(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",R):R(),e.ChannelWidget=k,e.CurrencyWidget=x,e.CustomWidget=I,e.MilestoneWidget=v,e.ReferralWidget=E,e.SocialWidget=T,e.StoreWidget=b,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|
|
1
|
+
var RaiWidget=function(e){"use strict";var t=Object.defineProperty,r=(e,r,i)=>((e,r,i)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[r]=i)(e,"symbol"!=typeof r?r+"":r,i);function i(e){return`${e.storagePrefix}-${e.widgetId}-auth`}function a(e){return`${e.storagePrefix}-${e.widgetId}-error-settings`}function n(e){try{localStorage.removeItem(i(e))}catch{}}function o(e){return!e||Date.now()>=e-6e4}function s(e,t,r,a){t.accessToken=r.accessToken,t.refreshToken=r.refreshToken,t.tokenFamily=r.tokenFamily??null;const n=Date.now();t.accessTokenExpiry=n+1e3*r.accessTokenTTL,t.refreshTokenExpiry=n+1e3*r.refreshTokenTTL,function(e,t){try{const r={refreshToken:t.refreshToken,tokenFamily:t.tokenFamily,refreshTokenExpiry:t.refreshTokenExpiry};localStorage.setItem(i(e),JSON.stringify(r))}catch{}}(e,t),e.autoRefresh&&a&&a()}async function l(e,t,r){const i=crypto.randomUUID(),a=Date.now(),n=e.maxRetries??3,o=e.retryDelay??500;for(let l=0;l<=n;l++){l>0&&await new Promise(e=>setTimeout(e,o*(1<<l-1)));let c=!1;try{const n=await fetch(`${e.apiUrl}/${e.widgetId}/auth/serverless`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nonce:i,timestamp:a,widgetType:e.widgetType,userIdentifiers:e.userIdentifiers}),credentials:"include"});if(!n.ok){c=n.status>=400&&n.status<500;const e=await n.json().catch(()=>({error:"Authentication failed"}));throw new Error(e.error||`HTTP ${n.status}`)}const o=await n.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid authentication response");return s(e,t,o,r),t.isAuthenticated=!0,!0}catch{if(c||l===n)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function c(e,t,r){const i=e.maxRetries??3,a=e.retryDelay??500;for(let n=0;n<=i;n++){n>0&&await new Promise(e=>setTimeout(e,a*(1<<n-1)));let o=!1;try{const i=await fetch(e.authUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(!i.ok)throw o=i.status>=400&&i.status<500,new Error(`HTTP ${i.status}`);const a=await i.json();if(!a.token)throw new Error("Invalid proxy auth response");const n=a.expiresIn??300;return t.accessToken=a.token,t.refreshToken=null,t.tokenFamily=null,t.accessTokenExpiry=Date.now()+1e3*n,t.refreshTokenExpiry=null,t.isAuthenticated=!0,e.autoRefresh&&r&&r(),!0}catch{if(o||n===i)return t.isAuthenticated=!1,!1}}return t.isAuthenticated=!1,!1}async function d(e,t,r,i){return t.isRefreshing?t.refreshPromise:!!t.refreshToken&&(t.isRefreshing=!0,t.refreshPromise=(async()=>{try{const a=await fetch(`${e.apiUrl}/${e.widgetId}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.refreshToken}`},body:JSON.stringify({widgetType:e.widgetType})});if(!a.ok){if(401===a.status||403===a.status)return u(t),n(e),l(e,t,r);const i=await a.json().catch(()=>({error:"Token refresh failed"}));throw new Error(i.error||`HTTP ${a.status}`)}const o=await a.json();if(!o.accessToken||!o.refreshToken)throw new Error("Invalid refresh response");return s(e,t,o,r),i&&i(),!0}catch{return u(t),n(e),l(e,t,r)}finally{t.isRefreshing=!1,t.refreshPromise=null}})(),t.refreshPromise)}async function h(e,t){const r=function(e){try{const t=localStorage.getItem(a(e));if(!t)return null;const r=JSON.parse(t);return r.cachedAt&&Date.now()-r.cachedAt<36e5?r:(localStorage.removeItem(a(e)),null)}catch{return null}}(e);if(r)return r.configured&&(t.errorSettings={errorMessage:r.errorMessage,modalColor:r.modalColor,backgroundImage:r.backgroundImage}),r.loadingAnimation&&(t.loadingAnimation=r.loadingAnimation),t.errorSettings;try{const r=await fetch(`${e.apiUrl}/${e.widgetId}/auth/error-settings?widgetType=${e.widgetType}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!r.ok)return null;const i=await r.json();return function(e,t){try{localStorage.setItem(a(e),JSON.stringify({...t,cachedAt:Date.now()}))}catch{}}(e,i),i.configured&&(t.errorSettings={errorMessage:i.errorMessage,modalColor:i.modalColor,backgroundImage:i.backgroundImage}),i.loadingAnimation&&(t.loadingAnimation=i.loadingAnimation),t.errorSettings}catch{return null}}function u(e){e.accessToken=null,e.refreshToken=null,e.tokenFamily=null,e.accessTokenExpiry=null,e.refreshTokenExpiry=null,e.isAuthenticated=!1,e.isRefreshing=!1,e.refreshPromise=null,e.loadingAnimation=null,e.refreshTimer&&(clearTimeout(e.refreshTimer),e.refreshTimer=null),e.syncTimer&&(clearInterval(e.syncTimer),e.syncTimer=null)}function m(e,t,r){var i;if(t.accessToken)try{null==(i=r.contentWindow)||i.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{widgetId:e.widgetId,token:t.accessToken,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}}function g(e,t,r,i,a,n,s,h){const u=function(e,t){let r=null;return{call(i){r&&clearTimeout(r),r=setTimeout(()=>{e(i),r=null},t)},cancel(){r&&(clearTimeout(r),r=null)}}}(e=>{i.style.height=`${e}px`,null==h||h("rai-height-change",{height:e})},e.heightDebounce??100),m=async r=>{var m;if(r.origin!==e.widgetDomain)return;if(!r.data||"string"!=typeof r.data.type)return;const{type:g,containerId:p,widgetId:f,payload:w}=r.data;switch(g){case"RETURNINGAI_WIDGET_REQUEST_TOKEN":try{const r=await async function(e,t,r){if(t.accessToken&&!o(t.accessTokenExpiry))return t.accessToken;if(e.authUrl){if(await c(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}if(await d(e,t,r)&&t.accessToken)return t.accessToken;if(await l(e,t,r)&&t.accessToken)return t.accessToken;throw new Error("Unable to obtain valid token")}(e,t,a);null==(m=i.contentWindow)||m.postMessage({type:"RETURNINGAI_WIDGET_TOKEN",value:{token:r,widgetId:e.widgetId,...void 0!==e.customData&&{customData:e.customData}}},e.widgetDomain)}catch{}break;case"WIDGET_HEIGHT_UPDATE":{const e=Number(null==w?void 0:w.height);Number.isFinite(e)&&e>0&&u.call(e);break}case"WIDGET_READY":if(void 0!==f&&f!==e.widgetId)break;if(void 0!==p&&p!==e.container)break;i.classList.add("loaded"),s&&s(),null==h||h("rai-ready");break;case"WIDGET_ERROR":s&&s();break;case"WIDGET_LOGOUT":n&&await n()}};return window.addEventListener("message",m),()=>{window.removeEventListener("message",m),u.cancel()}}const p=new Set(["community-id","channel-id","widget-id","widget-type","theme","container","width","height","api-url","widget-url","auto-refresh","debug","storage-prefix","max-retries","retry-delay","height-debounce","locale","custom-data","retry-label","auth-url","bundle-url","embed-token","v2-api-url"]),f={store:"RaiStoreWidget",channel:"RaiChannelWidget",social:"RaiSocialWidget",milestone:"RaiMilestoneWidget","currency-view":"RaiCurrencyWidget","referral-conditions":"RaiReferralWidget",custom:"RaiCustomWidget"},w={"RAI-STORE-WIDGET":"store","RAI-CHANNEL-WIDGET":"channel","RAI-MILESTONE-WIDGET":"milestone","RAI-SOCIAL-WIDGET":"social","RAI-CURRENCY-WIDGET":"currency-view","RAI-REFERRAL-WIDGET":"referral-conditions","RAI-CUSTOM-WIDGET":"custom","RAI-WIDGET":"store"};class y extends HTMLElement{constructor(){super(),r(this,"shadow"),r(this,"config"),r(this,"state",{accessToken:null,refreshToken:null,tokenFamily:null,accessTokenExpiry:null,refreshTokenExpiry:null,refreshTimer:null,syncTimer:null,iframe:null,isAuthenticated:!1,isRefreshing:!1,refreshPromise:null,errorSettings:null,loadingAnimation:null}),r(this,"loaderEl",null),r(this,"errorEl",null),r(this,"msgEl",null),r(this,"cleanupListener"),r(this,"intersectionObserver"),r(this,"themeObserver"),r(this,"errorSettingsPromise"),this.shadow=this.attachShadow({mode:"closed"})}connectedCallback(){this.config=function(e,t){const r=t=>e.getAttribute(t)??e.getAttribute(`data-${t}`)??"",i=(e,t)=>{const i=parseInt(r(e),10);return Number.isFinite(i)&&i>=0?i:t},a=!!r("community-id"),n=r("community-id")||r("widget-id")||t||"";if(n&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(n))throw new Error(`[rai-widget] Invalid community-id: "${n}"`);const o=r("channel-id")||void 0;if(o&&!/^[a-zA-Z0-9_\-=]{8,}$/.test(o))throw new Error(`[rai-widget] Invalid channel-id: "${o}"`);const s=r("widget-type")||w[e.tagName]||"store";let l;l=a?"store"===s?n:"channel"===s?o?btoa(o):n:n?btoa(n):n:n;let c,d=r("widget-url")||"https://widget.returningai.com";d.endsWith("store-widget")&&(d=`${d}/${n}/open-widget`);try{c=new URL(d).origin}catch{c=d}if(d.includes("store-widget")){const e=new URL(d);e.searchParams.set("color",r("theme")||"light"),d=e.toString()}const h=r("container")||r("data-container")||`returning-ai-widget-${n}`,u={};Array.from(e.attributes).forEach(e=>{const t=e.name.toLowerCase();if(!t.startsWith("data-"))return;const r=t.slice(5);p.has(r)||(u[t]=e.value)});const m=(()=>{const e=r("custom-data");if(e)try{return JSON.parse(e)}catch{return}})();return{communityId:n,channelId:o,widgetId:l,widgetType:s,theme:r("theme")||"light",container:h,width:r("width")||"100%",height:r("height")||"600px",apiUrl:r("api-url")||"https://sgtr-eks-widgets.genesiv.org",widgetUrl:d,widgetDomain:c,autoRefresh:"false"!==r("auto-refresh"),debug:"true"===r("debug"),storagePrefix:r("storage-prefix")||"returning-ai-widget",userIdentifiers:u,maxRetries:i("max-retries",3),retryDelay:i("retry-delay",500),heightDebounce:i("height-debounce",100),locale:r("locale")||void 0,customData:m,authUrl:r("auth-url")||void 0,bundleUrl:r("bundle-url")||void 0,embedToken:r("embed-token")||void 0,v2ApiUrl:r("v2-api-url")||void 0}}(this,void 0);const e=document.createElement("style");e.textContent=':host{display:block;position:relative;width:100%;height:100%}.rai-loader{position:absolute;top:0;left:0;display:flex;align-items:center;justify-content:center;width:100%;height:100%;background:var(--rai-loader-bg, #ffffff);border-radius:8px;z-index:10;transition:opacity .3s ease-out}.rai-loader.fade-out{opacity:0;pointer-events:none}.rai-error{display:none;position:absolute;top:0;left:0;width:100%;height:100%;align-items:center;justify-content:center;flex-direction:column;gap:12px;background:var(--rai-error-bg, #1a1a1a);border-radius:8px;padding:24px;box-sizing:border-box;text-align:center;color:var(--rai-error-text, #9ca3af);font-family:system-ui,-apple-system,sans-serif;z-index:10}.rai-error.visible{display:flex}iframe{display:block;border:none;opacity:0;transition:opacity .3s ease-in}iframe.loaded{opacity:1}.rai-lottie-loader{width:100px;height:100px}.rai-lottie-loader svg{width:100%!important;height:100%!important}.rai-lottie-spinner{width:32px;height:32px;margin:34px auto;border:3px solid var(--rai-text4, #6b7280);border-top-color:var(--rai-accent, #000000);border-radius:50%;animation:rai-spin .7s linear infinite}@keyframes rai-spin{to{transform:rotate(360deg)}}.rai-sdk-loader{position:relative;width:75px;height:100px}.rai-sdk-loader__bar{position:absolute;bottom:0;width:10px;height:50%;background:var(--rai-accent, #000000);transform-origin:center bottom;box-shadow:1px 1px #0003}.rai-sdk-loader__bar:nth-child(1){left:0;transform:scaleY(.2);animation:rai-sdk-barUp1 4s infinite}.rai-sdk-loader__bar:nth-child(2){left:15px;transform:scaleY(.4);animation:rai-sdk-barUp2 4s infinite}.rai-sdk-loader__bar:nth-child(3){left:30px;transform:scaleY(.6);animation:rai-sdk-barUp3 4s infinite}.rai-sdk-loader__bar:nth-child(4){left:45px;transform:scaleY(.8);animation:rai-sdk-barUp4 4s infinite}.rai-sdk-loader__bar:nth-child(5){left:60px;transform:scale(1);animation:rai-sdk-barUp5 4s infinite}.rai-sdk-loader__ball{position:absolute;bottom:10px;left:0;width:10px;height:10px;background:var(--rai-accent, #000000);border-radius:50%;animation:rai-sdk-ball 4s infinite}@keyframes rai-sdk-ball{0%{transform:translate(0)}5%{transform:translate(8px,-14px)}10%{transform:translate(15px,-10px)}17%{transform:translate(23px,-24px)}20%{transform:translate(30px,-20px)}27%{transform:translate(38px,-34px)}30%{transform:translate(45px,-30px)}37%{transform:translate(53px,-44px)}40%{transform:translate(60px,-40px)}50%{transform:translate(60px)}57%{transform:translate(53px,-14px)}60%{transform:translate(45px,-10px)}67%{transform:translate(37px,-24px)}70%{transform:translate(30px,-20px)}77%{transform:translate(22px,-34px)}80%{transform:translate(15px,-30px)}87%{transform:translate(7px,-44px)}90%{transform:translateY(-40px)}to{transform:translate(0)}}@keyframes rai-sdk-barUp1{0%{transform:scaleY(.2)}40%{transform:scaleY(.2)}50%{transform:scale(1)}90%{transform:scale(1)}to{transform:scaleY(.2)}}@keyframes rai-sdk-barUp2{0%{transform:scaleY(.4)}40%{transform:scaleY(.4)}50%{transform:scaleY(.8)}90%{transform:scaleY(.8)}to{transform:scaleY(.4)}}@keyframes rai-sdk-barUp3{0%{transform:scaleY(.6)}to{transform:scaleY(.6)}}@keyframes rai-sdk-barUp4{0%{transform:scaleY(.8)}40%{transform:scaleY(.8)}50%{transform:scaleY(.4)}90%{transform:scaleY(.4)}to{transform:scaleY(.8)}}@keyframes rai-sdk-barUp5{0%{transform:scale(1)}40%{transform:scale(1)}50%{transform:scaleY(.2)}90%{transform:scaleY(.2)}to{transform:scale(1)}}#loading-square{width:75px;aspect-ratio:1;display:flex;color:var(--rai-accent, #000000);background:linear-gradient(currentColor 0 0) right / 51% 100%,linear-gradient(currentColor 0 0) bottom / 100% 51%;background-repeat:no-repeat;animation:l16-0 2s infinite linear .25s}#loading-square>div{width:50%;height:50%;background:currentColor;animation:l16-1 .5s infinite linear}@keyframes l16-0{0%,12.49%{transform:rotate(0)}12.5%,37.49%{transform:rotate(90deg)}37.5%,62.49%{transform:rotate(180deg)}62.5%,87.49%{transform:rotate(270deg)}87.5%,to{transform:rotate(360deg)}}@keyframes l16-1{0%{transform:perspective(80px) rotate3d(-1,-1,0,0)}80%,to{transform:perspective(80px) rotate3d(-1,-1,0,-180deg)}}#loading-circle{width:75px;aspect-ratio:1;display:grid;grid:50%/50%;color:var(--rai-accent, #000000);border-radius:50%;--_g: no-repeat linear-gradient(currentColor 0 0);background:var(--_g),var(--_g),var(--_g);background-size:50.1% 50.1%;animation:l9-0 1.5s infinite steps(1) alternate,l9-0-0 3s infinite steps(1) alternate}#loading-circle>div{background:var(--rai-text4, #6b7280);border-top-left-radius:100px;transform:perspective(150px) rotateY(0) rotateX(0);transform-origin:bottom right;animation:l9-1 1.5s infinite linear alternate}@keyframes l9-0{0%{background-position:0 100%,100% 100%,100% 0}33%{background-position:100% 100%,100% 100%,100% 0}66%{background-position:100% 0,100% 0,100% 0}}@keyframes l9-0-0{0%{transform:scaleX(1) rotate(0)}50%{transform:scaleX(-1) rotate(-90deg)}}@keyframes l9-1{16.5%{transform:perspective(150px) rotateX(-90deg) rotateY(0) rotateX(0);filter:grayscale(.8)}33%{transform:perspective(150px) rotateX(-180deg) rotateY(0) rotateX(0)}66%{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(0)}to{transform:perspective(150px) rotateX(-180deg) rotateY(-180deg) rotateX(-180deg);filter:grayscale(.8)}}.rai-custom-error{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10}.tiptap strong.tw-font-bold,.tiptap b.tw-font-bold{font-weight:700}.tiptap em.tw-font-italic,.tiptap i.tw-font-italic{font-style:italic}.tiptap a.tiptap-rich-text-link{color:#3b82f6;text-decoration:underline;position:relative;display:inline-block;width:fit-content}.tiptap a.tiptap-rich-text-link:hover{color:#3b82f6cc;text-decoration:none}.tiptap a.tiptap-rich-text-link:not([title=""]):before{content:attr(title);position:absolute;top:-2rem;left:50%;transform:translate(-50%);white-space:nowrap;border-radius:.25rem;background-color:#000;padding:.25rem .5rem;color:#fff;opacity:0;transition:opacity .2s;pointer-events:none}.tiptap a.tiptap-rich-text-link:not([title=""]):hover:before{opacity:1}.tiptap p[style*="text-align: left"]{text-align:left}.tiptap p[style*="text-align: center"]{text-align:center}.tiptap p[style*="text-align: right"]{text-align:right}.tiptap p[style*="text-align: justify"]{text-align:justify}.tiptap u{text-decoration:underline}.tiptap.ProseMirror{background-color:transparent;height:fit-content!important;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;padding:0;width:100%;overflow-y:auto}.tiptap{line-height:1.6;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}.tiptap p{margin:.5em 0}.tiptap p:first-child{margin-top:0}.tiptap p:last-child{margin-bottom:0}.tiptap img{max-width:100%;height:auto;display:block}.tiptap p[style*="text-align: left"] img{margin-left:0;margin-right:auto}.tiptap p[style*="text-align: center"] img{margin-left:auto;margin-right:auto}.tiptap p[style*="text-align: right"] img{margin-left:auto;margin-right:0}.rai-retry-btn{padding:8px 20px;border:none;border-radius:6px;background:var(--rai-accent, #000000);color:var(--rai-error-bg, #ffffff);font-size:14px;font-family:system-ui,-apple-system,sans-serif;cursor:pointer}.rai-retry-btn:hover{opacity:.85}',this.shadow.appendChild(e);const t=this.config.theme,r="dark"===t?"#ffffff":"#000000",i="dark"===t?"#9ca3af":"#6b7280",a="dark"===t?"#1a1a1a":"#ffffff";this.style.width=this.config.width,this.style.height=this.config.height,this.style.setProperty("--rai-accent",r),this.style.setProperty("--rai-text4",i),this.style.setProperty("--rai-loader-bg",a),this.style.setProperty("--rai-error-bg",a),this.renderShell(),this.hasAttribute("eager")?this.init():(this.intersectionObserver=new IntersectionObserver(e=>{e[0].isIntersecting&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0,this.init())}),this.intersectionObserver.observe(this))}disconnectedCallback(){var e,t;null==(e=this.intersectionObserver)||e.disconnect(),null==(t=this.themeObserver)||t.disconnect(),this.cleanupListener&&this.cleanupListener(),u(this.state)}emit(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t??{}}))}renderShell(){this.loaderEl=document.createElement("div"),this.loaderEl.className="rai-loader",this.shadow.appendChild(this.loaderEl),this.fetchAndRenderLoader(),this.errorEl=document.createElement("div"),this.errorEl.className="rai-error",this.msgEl=document.createElement("span"),this.msgEl.className="rai-error-msg",this.msgEl.textContent="Authentication failed. Please try again later.",this.errorEl.appendChild(this.msgEl);const e=this.getAttribute("retry-label")||this.getAttribute("data-retry-label")||"Retry",t=document.createElement("button");t.className="rai-retry-btn",t.textContent=e,t.addEventListener("click",()=>this.reload()),this.errorEl.appendChild(t),this.shadow.appendChild(this.errorEl)}async fetchAndRenderLoader(){var e;const t=document.createElement("div");t.className="rai-lottie-spinner",null==(e=this.loaderEl)||e.appendChild(t);try{this.errorSettingsPromise=h(this.config,this.state),await this.errorSettingsPromise}catch{}if(!this.loaderEl)return;this.loaderEl.innerHTML="";const r=this.state.loadingAnimation,i="dark"===this.config.theme?"dark":"light";if("custom"===(null==r?void 0:r.type)&&r.custom){const e=r.custom[i]||r.custom.light||r.custom.dark;if(e){if("lottie"===e.type&&e.lottieData)return void this.renderLottieLoader(e.lottieData);if("custom"===e.type&&e.html){const t=document.createElement("div");return t.innerHTML=e.html,void this.loaderEl.appendChild(t)}}}"preset"===(null==r?void 0:r.type)&&r.preset?this.loaderEl.appendChild(this.createPresetLoader(r.preset)):this.loaderEl.appendChild(this.createDefaultLoader())}renderLottieLoader(e){const t=document.createElement("div");t.className="rai-lottie-loader",this.loaderEl.appendChild(t);const r=window;if(void 0!==r.lottie)r.lottie.loadAnimation({container:t,renderer:"svg",loop:!0,autoplay:!0,animationData:e});else{const r=document.createElement("div");r.className="rai-lottie-spinner",t.appendChild(r);const i=document.createElement("script");i.src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js",i.onload=()=>{window.lottie.loadAnimation({container:t,renderer:"svg",loop:!0,autoplay:!0,animationData:e})},document.head.appendChild(i)}}createDefaultLoader(){const e=document.createElement("div");e.className="rai-sdk-loader";for(let r=0;r<5;r++){const t=document.createElement("div");t.className="rai-sdk-loader__bar",e.appendChild(t)}const t=document.createElement("div");return t.className="rai-sdk-loader__ball",e.appendChild(t),e}createPresetLoader(e){if("square"===e){const e=document.createElement("div");e.id="loading-square";const t=document.createElement("div");return e.appendChild(t),e}if("circle"===e){const e=document.createElement("div");e.id="loading-circle";const t=document.createElement("div");return e.appendChild(t),e}return this.createDefaultLoader()}hideLoader(){this.loaderEl&&(this.loaderEl.classList.add("fade-out"),setTimeout(()=>{var e;return null==(e=this.loaderEl)?void 0:e.remove()},300),this.loaderEl=null)}showError(){this.hideLoader();const e=this.state.errorSettings;(null==e?void 0:e.errorMessage)?this.renderCustomError(e):this.errorEl&&this.errorEl.classList.add("visible"),this.emit("rai-error",{message:(null==e?void 0:e.errorMessage)??"Authentication failed"})}renderCustomError(e){var t,r;null==(t=this.errorEl)||t.remove(),this.errorEl=null;const i=(null==(r=e.backgroundImage)?void 0:r.trim())?`background-image: url('${e.backgroundImage}'); background-size: cover; background-position: center; background-repeat: no-repeat;`:"",a=document.createElement("div");a.className="rai-custom-error",a.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: center;\n overflow: auto;\n width: 100%;\n height: 100%;\n ${i}\n `;const n=document.createElement("div");n.className="rai-rich-text",n.style.cssText=`\n min-width: 50%;\n min-height: 50%;\n margin: 0 auto;\n padding: 20px;\n width: auto;\n height: auto;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 6px;\n background-color: ${e.modalColor||"transparent"};\n `;const o=document.createElement("div");o.className="tiptap ProseMirror",o.innerHTML=e.errorMessage||"",n.appendChild(o),a.appendChild(n),this.shadow.appendChild(a)}async init(){if(!this.config.communityId)return void this.showError();if(await(this.errorSettingsPromise??h(this.config,this.state)),this.config.embedToken){if(!(await async function(e){try{const t=e.v2ApiUrl||e.apiUrl;return(await fetch(`${t}/v2/api/widget-access-keys/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:e.embedToken})})).ok}catch{return!1}}(this.config)))return void this.showError()}const e=()=>{this.config.bundleUrl?this.mountWidget():this.createIframe()};if(this.config.authUrl){return void(await c(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError())}if(function(e,t){try{const r=localStorage.getItem(i(e));if(!r)return!1;const a=JSON.parse(r);return a.refreshToken&&!o(a.refreshTokenExpiry)?(t.refreshToken=a.refreshToken,t.tokenFamily=a.tokenFamily,t.refreshTokenExpiry=a.refreshTokenExpiry,!0):(n(e),!1)}catch{return!1}}(this.config,this.state)){return await d(this.config,this.state,()=>this.scheduleRefresh())?(this.state.isAuthenticated=!0,this.emit("rai-authenticated"),void e()):void this.showError()}await l(this.config,this.state,()=>this.scheduleRefresh())?(this.emit("rai-authenticated"),e()):this.showError()}createIframe(){const e=document.createElement("iframe");e.src=this.buildWidgetUrl(this.config),e.allow="clipboard-write",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),e.frameBorder="0",e.scrolling="no",e.style.width=this.config.width,e.style.height=this.config.height,e.style.border="none",e.style.display="block",e.onload=()=>{m(this.config,this.state,e),this.schedulePeriodicSync(e)},e.onerror=()=>{this.showError()},this.state.iframe=e,this.shadow.appendChild(e),this.cleanupListener=g(this.config,this.state,this.shadow,e,()=>this.scheduleRefresh(),()=>this.logoutAndClear(),()=>this.hideLoader(),(e,t)=>this.emit(e,t))}async mountWidget(){try{const t=window,r=["api_url","base_url","auth_api","socket_path_v2","socket_path","channel_api"];for(const e of r)t[e]||(t[e]=this.config.apiUrl);window.__IS_WIDGET__=!0,window.guest_token=this.state.accessToken,await(e=this.config.bundleUrl,new Promise((t,r)=>{const i=document.createElement("script");i.src=e,i.onload=()=>t(),i.onerror=()=>r(new Error(`Failed to load ${e}`)),document.head.appendChild(i)}));const i=f[this.config.widgetType],a=window[i];if(!(null==a?void 0:a.mount))throw new Error(`window.${i}.mount not found after loading bundle`);const n=document.createElement("div");if(n.style.cssText="position: relative; width: 100%; height: 100%;",this.appendChild(n),!this.shadow.querySelector("slot")){const e=document.createElement("slot");this.shadow.appendChild(e)}this.loaderEl&&(this.loaderEl.remove(),this.loaderEl=null),a.mount(n,{widgetType:this.config.widgetType,communityId:this.config.communityId,channelId:this.config.channelId,widgetId:this.config.communityId,apiUrl:this.config.apiUrl,token:this.state.accessToken,basePath:"/",isPreview:!1,isOpenWidget:!0,defaultColorSchema:"dark"===this.config.theme?"dark":"light"}),this.emit("rai-mounted")}catch(t){console.error("[rai-widget] Bundle mount failed:",t),this.showError()}var e}scheduleRefresh(){if(this.state.refreshTimer&&clearTimeout(this.state.refreshTimer),!this.state.accessTokenExpiry)return;const e=this.state.accessTokenExpiry-Date.now()-6e4,t=()=>{this.state.iframe&&m(this.config,this.state,this.state.iframe),this.config.bundleUrl&&this.state.accessToken&&(window.guest_token=this.state.accessToken)},r=async()=>{if(this.config.authUrl){await c(this.config,this.state,()=>this.scheduleRefresh())&&t()}else await d(this.config,this.state,()=>this.scheduleRefresh(),t)};e>0?this.state.refreshTimer=setTimeout(r,e):r()}schedulePeriodicSync(e){this.state.syncTimer&&clearInterval(this.state.syncTimer),this.state.syncTimer=setInterval(()=>{this.state.accessToken&&m(this.config,this.state,e)},12e4)}async logoutAndClear(){await async function(e,t){if(t.accessToken)try{await fetch(`${e.apiUrl}/${e.widgetId}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({refreshToken:t.refreshToken})})}catch{}u(t),n(e)}(this.config,this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),this.emit("rai-logout")}async reload(){u(this.state),this.shadow.querySelectorAll("iframe").forEach(e=>e.remove()),await this.init()}async logoutPublic(){await this.logoutAndClear()}isAuthenticated(){return this.state.isAuthenticated&&null!==this.state.accessToken}getTokenInfo(){return{hasAccessToken:!!this.state.accessToken,hasRefreshToken:!!this.state.refreshToken,accessTokenExpiry:this.state.accessTokenExpiry?new Date(this.state.accessTokenExpiry):null,refreshTokenExpiry:this.state.refreshTokenExpiry?new Date(this.state.refreshTokenExpiry):null,isAccessTokenValid:!!this.state.accessToken&&!o(this.state.accessTokenExpiry),isRefreshTokenValid:!!this.state.refreshToken&&!o(this.state.refreshTokenExpiry)}}}class b extends y{buildWidgetUrl(e){const t=new URL(e.widgetUrl);return t.searchParams.set("color",e.theme),t.searchParams.set("containerId",e.container),t.searchParams.set("connectType","simple"),t.searchParams.set("mode","private"),e.locale&&t.searchParams.set("locale",e.locale),t.toString()}}class k extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("channel-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class T extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("milestone-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class v extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("social-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class x extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("currency-overview-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class E extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("referral-conditions-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}class I extends y{buildWidgetUrl(e){const t=e.widgetUrl.endsWith("custom-widget")?`${e.widgetUrl}/${e.widgetId}`:e.widgetUrl;if(!e.locale)return t;try{const r=new URL(t);return r.searchParams.set("locale",e.locale),r.toString()}catch{return`${t}?locale=${encodeURIComponent(e.locale)}`}}}console.log("[rai-widget] v1.2.5");const U=[["rai-store-widget",b],["rai-channel-widget",k],["rai-milestone-widget",T],["rai-social-widget",v],["rai-currency-widget",x],["rai-referral-widget",E],["rai-custom-widget",I],["rai-widget",class extends b{}]];for(const[$,P]of U)customElements.get($)||customElements.define($,P);const A={store:b,channel:k,milestone:T,social:v,"currency-view":x,"referral-conditions":E,custom:I},R=U.map(([e])=>e).join(", ");function S(){var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return;const i=r.getAttribute("data-community-id")||r.getAttribute("data-widget-id");if(!i)return;const a=r.getAttribute("data-container")||`returning-ai-widget-${i}`,n=document.getElementById(a);if(!n)return;"static"===getComputedStyle(n).position&&(n.style.position="relative");const o=r.getAttribute("data-widget-type")??"store",s=new(A[o]??b);Array.from(r.attributes).forEach(e=>{s.setAttribute(e.name,e.value)}),n.appendChild(s)}function C(){const e=(()=>{var e,t;const r=((null==(e=document.currentScript)?void 0:e.hasAttribute("data-widget-id"))||(null==(t=document.currentScript)?void 0:t.hasAttribute("data-community-id"))?document.currentScript:null)||document.querySelector("script[data-widget-id], script[data-community-id]");if(!r)return null;const i=r.getAttribute("data-container")||`returning-ai-widget-${r.getAttribute("data-community-id")||r.getAttribute("data-widget-id")}`;return document.getElementById(i)})(),t=null==e?void 0:e.querySelector(R);window.ReturningAIWidget={version:"1.2.5",reload:()=>(null==t?void 0:t.reload())??Promise.resolve(),logout:()=>(null==t?void 0:t.logoutPublic())??Promise.resolve(),isAuthenticated:()=>(null==t?void 0:t.isAuthenticated())??!1,getTokenInfo:()=>(null==t?void 0:t.getTokenInfo())??{}}}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",S):S(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",C):C(),e.ChannelWidget=k,e.CurrencyWidget=x,e.CustomWidget=I,e.MilestoneWidget=T,e.ReferralWidget=E,e.SocialWidget=v,e.StoreWidget=b,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|
package/dist/rai-widget.js
CHANGED
|
@@ -269,6 +269,9 @@ async function fetchErrorSettings(config, state) {
|
|
|
269
269
|
backgroundImage: cached.backgroundImage
|
|
270
270
|
};
|
|
271
271
|
}
|
|
272
|
+
if (cached.loadingAnimation) {
|
|
273
|
+
state.loadingAnimation = cached.loadingAnimation;
|
|
274
|
+
}
|
|
272
275
|
return state.errorSettings;
|
|
273
276
|
}
|
|
274
277
|
try {
|
|
@@ -286,6 +289,9 @@ async function fetchErrorSettings(config, state) {
|
|
|
286
289
|
backgroundImage: data.backgroundImage
|
|
287
290
|
};
|
|
288
291
|
}
|
|
292
|
+
if (data.loadingAnimation) {
|
|
293
|
+
state.loadingAnimation = data.loadingAnimation;
|
|
294
|
+
}
|
|
289
295
|
return state.errorSettings;
|
|
290
296
|
} catch {
|
|
291
297
|
return null;
|
|
@@ -300,6 +306,7 @@ function clearState(state) {
|
|
|
300
306
|
state.isAuthenticated = false;
|
|
301
307
|
state.isRefreshing = false;
|
|
302
308
|
state.refreshPromise = null;
|
|
309
|
+
state.loadingAnimation = null;
|
|
303
310
|
if (state.refreshTimer) {
|
|
304
311
|
clearTimeout(state.refreshTimer);
|
|
305
312
|
state.refreshTimer = null;
|
|
@@ -576,7 +583,8 @@ function createInitialState() {
|
|
|
576
583
|
isAuthenticated: false,
|
|
577
584
|
isRefreshing: false,
|
|
578
585
|
refreshPromise: null,
|
|
579
|
-
errorSettings: null
|
|
586
|
+
errorSettings: null,
|
|
587
|
+
loadingAnimation: null
|
|
580
588
|
};
|
|
581
589
|
}
|
|
582
590
|
class BaseWidget extends HTMLElement {
|
|
@@ -592,7 +600,7 @@ class BaseWidget extends HTMLElement {
|
|
|
592
600
|
__publicField(this, "intersectionObserver");
|
|
593
601
|
// #3
|
|
594
602
|
__publicField(this, "themeObserver");
|
|
595
|
-
__publicField(this, "
|
|
603
|
+
__publicField(this, "errorSettingsPromise");
|
|
596
604
|
this.shadow = this.attachShadow({ mode: "closed" });
|
|
597
605
|
}
|
|
598
606
|
connectedCallback() {
|
|
@@ -625,10 +633,9 @@ class BaseWidget extends HTMLElement {
|
|
|
625
633
|
}
|
|
626
634
|
}
|
|
627
635
|
disconnectedCallback() {
|
|
628
|
-
var _a, _b
|
|
636
|
+
var _a, _b;
|
|
629
637
|
(_a = this.intersectionObserver) == null ? void 0 : _a.disconnect();
|
|
630
638
|
(_b = this.themeObserver) == null ? void 0 : _b.disconnect();
|
|
631
|
-
(_c = this.loaderObserver) == null ? void 0 : _c.disconnect();
|
|
632
639
|
if (this.cleanupListener) this.cleanupListener();
|
|
633
640
|
clearState(this.state);
|
|
634
641
|
}
|
|
@@ -647,7 +654,7 @@ class BaseWidget extends HTMLElement {
|
|
|
647
654
|
this.loaderEl = document.createElement("div");
|
|
648
655
|
this.loaderEl.className = "rai-loader";
|
|
649
656
|
this.shadow.appendChild(this.loaderEl);
|
|
650
|
-
this.
|
|
657
|
+
this.fetchAndRenderLoader();
|
|
651
658
|
this.errorEl = document.createElement("div");
|
|
652
659
|
this.errorEl.className = "rai-error";
|
|
653
660
|
this.msgEl = document.createElement("span");
|
|
@@ -663,48 +670,80 @@ class BaseWidget extends HTMLElement {
|
|
|
663
670
|
this.shadow.appendChild(this.errorEl);
|
|
664
671
|
}
|
|
665
672
|
/**
|
|
666
|
-
*
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
* 1. Try immediately (works when element is upgraded after full parse)
|
|
671
|
-
* 2. If not found, use MutationObserver to wait for children
|
|
672
|
-
* 3. On timeout (50ms), fall back to the default loader
|
|
673
|
+
* Fetches the community's loading animation config from the error-settings
|
|
674
|
+
* API (which now also returns loadingAnimation) and renders the appropriate
|
|
675
|
+
* loader. Falls back to the default bar loader if the API fails or if no
|
|
676
|
+
* custom animation is configured.
|
|
673
677
|
*
|
|
674
|
-
*
|
|
675
|
-
* the
|
|
678
|
+
* This runs in parallel with auth — the API call is fire-and-forget and
|
|
679
|
+
* the loader is rendered as soon as the response arrives. The result is
|
|
680
|
+
* also cached by fetchErrorSettings so init() doesn't re-fetch.
|
|
676
681
|
*/
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
+
async fetchAndRenderLoader() {
|
|
683
|
+
var _a;
|
|
684
|
+
const spinner = document.createElement("div");
|
|
685
|
+
spinner.className = "rai-lottie-spinner";
|
|
686
|
+
(_a = this.loaderEl) == null ? void 0 : _a.appendChild(spinner);
|
|
687
|
+
try {
|
|
688
|
+
this.errorSettingsPromise = fetchErrorSettings(this.config, this.state);
|
|
689
|
+
await this.errorSettingsPromise;
|
|
690
|
+
} catch {
|
|
682
691
|
}
|
|
683
|
-
this.
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
this.loaderEl.appendChild(
|
|
692
|
+
if (!this.loaderEl) return;
|
|
693
|
+
this.loaderEl.innerHTML = "";
|
|
694
|
+
const anim = this.state.loadingAnimation;
|
|
695
|
+
const theme = this.config.theme === "dark" ? "dark" : "light";
|
|
696
|
+
if ((anim == null ? void 0 : anim.type) === "custom" && anim.custom) {
|
|
697
|
+
const themeConfig = anim.custom[theme] || anim.custom.light || anim.custom.dark;
|
|
698
|
+
if (themeConfig) {
|
|
699
|
+
if (themeConfig.type === "lottie" && themeConfig.lottieData) {
|
|
700
|
+
this.renderLottieLoader(themeConfig.lottieData);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
if (themeConfig.type === "custom" && themeConfig.html) {
|
|
704
|
+
const wrapper = document.createElement("div");
|
|
705
|
+
wrapper.innerHTML = themeConfig.html;
|
|
706
|
+
this.loaderEl.appendChild(wrapper);
|
|
707
|
+
return;
|
|
698
708
|
}
|
|
699
709
|
}
|
|
700
|
-
}
|
|
710
|
+
}
|
|
711
|
+
if ((anim == null ? void 0 : anim.type) === "preset" && anim.preset) {
|
|
712
|
+
this.loaderEl.appendChild(this.createPresetLoader(anim.preset));
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
this.loaderEl.appendChild(this.createDefaultLoader());
|
|
701
716
|
}
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
717
|
+
renderLottieLoader(animationData) {
|
|
718
|
+
const lottieContainer = document.createElement("div");
|
|
719
|
+
lottieContainer.className = "rai-lottie-loader";
|
|
720
|
+
this.loaderEl.appendChild(lottieContainer);
|
|
721
|
+
const w = window;
|
|
722
|
+
if (typeof w.lottie !== "undefined") {
|
|
723
|
+
w.lottie.loadAnimation({
|
|
724
|
+
container: lottieContainer,
|
|
725
|
+
renderer: "svg",
|
|
726
|
+
loop: true,
|
|
727
|
+
autoplay: true,
|
|
728
|
+
animationData
|
|
729
|
+
});
|
|
730
|
+
} else {
|
|
731
|
+
const spinner = document.createElement("div");
|
|
732
|
+
spinner.className = "rai-lottie-spinner";
|
|
733
|
+
lottieContainer.appendChild(spinner);
|
|
734
|
+
const script = document.createElement("script");
|
|
735
|
+
script.src = "https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js";
|
|
736
|
+
script.onload = () => {
|
|
737
|
+
window.lottie.loadAnimation({
|
|
738
|
+
container: lottieContainer,
|
|
739
|
+
renderer: "svg",
|
|
740
|
+
loop: true,
|
|
741
|
+
autoplay: true,
|
|
742
|
+
animationData
|
|
743
|
+
});
|
|
744
|
+
};
|
|
745
|
+
document.head.appendChild(script);
|
|
746
|
+
}
|
|
708
747
|
}
|
|
709
748
|
createDefaultLoader() {
|
|
710
749
|
const loader = document.createElement("div");
|
|
@@ -736,61 +775,6 @@ class BaseWidget extends HTMLElement {
|
|
|
736
775
|
}
|
|
737
776
|
return this.createDefaultLoader();
|
|
738
777
|
}
|
|
739
|
-
renderCustomLoader(loaderEl) {
|
|
740
|
-
const loaderType = loaderEl.getAttribute("data-loader-type");
|
|
741
|
-
if (loaderType === "lottie") {
|
|
742
|
-
const lottieDataEl = loaderEl.querySelector(".lottie-data");
|
|
743
|
-
if (lottieDataEl) {
|
|
744
|
-
try {
|
|
745
|
-
const lottieData = JSON.parse(lottieDataEl.textContent || "");
|
|
746
|
-
const lottieContainer = document.createElement("div");
|
|
747
|
-
lottieContainer.className = "rai-lottie-loader";
|
|
748
|
-
const spinner = document.createElement("div");
|
|
749
|
-
spinner.className = "rai-lottie-spinner";
|
|
750
|
-
lottieContainer.appendChild(spinner);
|
|
751
|
-
this.loaderEl.appendChild(lottieContainer);
|
|
752
|
-
const w = window;
|
|
753
|
-
if (typeof w.lottie !== "undefined") {
|
|
754
|
-
w.lottie.loadAnimation({
|
|
755
|
-
container: lottieContainer,
|
|
756
|
-
renderer: "svg",
|
|
757
|
-
loop: true,
|
|
758
|
-
autoplay: true,
|
|
759
|
-
animationData: lottieData
|
|
760
|
-
});
|
|
761
|
-
} else {
|
|
762
|
-
const script = document.createElement("script");
|
|
763
|
-
script.src = "https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js";
|
|
764
|
-
script.onload = () => {
|
|
765
|
-
;
|
|
766
|
-
window.lottie.loadAnimation({
|
|
767
|
-
container: lottieContainer,
|
|
768
|
-
renderer: "svg",
|
|
769
|
-
loop: true,
|
|
770
|
-
autoplay: true,
|
|
771
|
-
animationData: lottieData
|
|
772
|
-
});
|
|
773
|
-
};
|
|
774
|
-
document.head.appendChild(script);
|
|
775
|
-
}
|
|
776
|
-
} catch {
|
|
777
|
-
this.loaderEl.appendChild(this.createDefaultLoader());
|
|
778
|
-
}
|
|
779
|
-
} else {
|
|
780
|
-
this.loaderEl.appendChild(this.createDefaultLoader());
|
|
781
|
-
}
|
|
782
|
-
} else if (loaderType === "custom") {
|
|
783
|
-
const wrapper = document.createElement("div");
|
|
784
|
-
wrapper.innerHTML = loaderEl.innerHTML;
|
|
785
|
-
this.loaderEl.appendChild(wrapper);
|
|
786
|
-
} else if (loaderType === "preset") {
|
|
787
|
-
const preset = loaderEl.getAttribute("data-preset");
|
|
788
|
-
this.loaderEl.appendChild(this.createPresetLoader(preset));
|
|
789
|
-
} else {
|
|
790
|
-
this.loaderEl.appendChild(this.createDefaultLoader());
|
|
791
|
-
}
|
|
792
|
-
loaderEl.remove();
|
|
793
|
-
}
|
|
794
778
|
hideLoader() {
|
|
795
779
|
if (!this.loaderEl) return;
|
|
796
780
|
this.loaderEl.classList.add("fade-out");
|
|
@@ -855,7 +839,7 @@ class BaseWidget extends HTMLElement {
|
|
|
855
839
|
this.showError();
|
|
856
840
|
return;
|
|
857
841
|
}
|
|
858
|
-
await fetchErrorSettings(this.config, this.state);
|
|
842
|
+
await (this.errorSettingsPromise ?? fetchErrorSettings(this.config, this.state));
|
|
859
843
|
if (this.config.embedToken) {
|
|
860
844
|
const valid = await validateEmbedToken(this.config);
|
|
861
845
|
if (!valid) {
|
|
@@ -1148,7 +1132,7 @@ class CustomWidget extends BaseWidget {
|
|
|
1148
1132
|
}
|
|
1149
1133
|
}
|
|
1150
1134
|
}
|
|
1151
|
-
console.log(`[rai-widget] v${"1.2.
|
|
1135
|
+
console.log(`[rai-widget] v${"1.2.5"}`);
|
|
1152
1136
|
class StoreWidgetCompat extends StoreWidget {
|
|
1153
1137
|
}
|
|
1154
1138
|
const WIDGET_REGISTRY = [
|
|
@@ -1212,7 +1196,7 @@ function exposePublicApi() {
|
|
|
1212
1196
|
})();
|
|
1213
1197
|
const widget = container == null ? void 0 : container.querySelector(ALL_WIDGET_SELECTOR);
|
|
1214
1198
|
window.ReturningAIWidget = {
|
|
1215
|
-
version: "1.2.
|
|
1199
|
+
version: "1.2.5",
|
|
1216
1200
|
reload: () => (widget == null ? void 0 : widget.reload()) ?? Promise.resolve(),
|
|
1217
1201
|
logout: () => (widget == null ? void 0 : widget.logoutPublic()) ?? Promise.resolve(),
|
|
1218
1202
|
isAuthenticated: () => (widget == null ? void 0 : widget.isAuthenticated()) ?? false,
|
|
@@ -10,7 +10,7 @@ export declare abstract class BaseWidget extends HTMLElement {
|
|
|
10
10
|
private cleanupListener?;
|
|
11
11
|
private intersectionObserver?;
|
|
12
12
|
private themeObserver?;
|
|
13
|
-
private
|
|
13
|
+
private errorSettingsPromise?;
|
|
14
14
|
constructor();
|
|
15
15
|
protected abstract buildWidgetUrl(config: WidgetConfig): string;
|
|
16
16
|
connectedCallback(): void;
|
|
@@ -18,25 +18,19 @@ export declare abstract class BaseWidget extends HTMLElement {
|
|
|
18
18
|
private emit;
|
|
19
19
|
private renderShell;
|
|
20
20
|
/**
|
|
21
|
-
*
|
|
21
|
+
* Fetches the community's loading animation config from the error-settings
|
|
22
|
+
* API (which now also returns loadingAnimation) and renders the appropriate
|
|
23
|
+
* loader. Falls back to the default bar loader if the API fails or if no
|
|
24
|
+
* custom animation is configured.
|
|
22
25
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* 2. If not found, use MutationObserver to wait for children
|
|
27
|
-
* 3. On timeout (50ms), fall back to the default loader
|
|
28
|
-
*
|
|
29
|
-
* The loader wrapper stays empty until we decide, so there's no flash of
|
|
30
|
-
* the default loader when a custom one is provided.
|
|
31
|
-
*/
|
|
32
|
-
private resolveLoader;
|
|
33
|
-
/**
|
|
34
|
-
* Applies the custom loader from the light DOM .widget-loader element.
|
|
26
|
+
* This runs in parallel with auth — the API call is fire-and-forget and
|
|
27
|
+
* the loader is rendered as soon as the response arrives. The result is
|
|
28
|
+
* also cached by fetchErrorSettings so init() doesn't re-fetch.
|
|
35
29
|
*/
|
|
36
|
-
private
|
|
30
|
+
private fetchAndRenderLoader;
|
|
31
|
+
private renderLottieLoader;
|
|
37
32
|
private createDefaultLoader;
|
|
38
33
|
private createPresetLoader;
|
|
39
|
-
private renderCustomLoader;
|
|
40
34
|
private hideLoader;
|
|
41
35
|
private showError;
|
|
42
36
|
private renderCustomError;
|
package/dist/types/types.d.ts
CHANGED
|
@@ -48,6 +48,25 @@ export interface WidgetState {
|
|
|
48
48
|
modalColor?: string;
|
|
49
49
|
backgroundImage?: string;
|
|
50
50
|
} | null;
|
|
51
|
+
loadingAnimation: {
|
|
52
|
+
type?: string;
|
|
53
|
+
preset?: string;
|
|
54
|
+
active_theme?: string;
|
|
55
|
+
custom?: {
|
|
56
|
+
dark?: {
|
|
57
|
+
type?: string;
|
|
58
|
+
html?: string;
|
|
59
|
+
lottie?: string;
|
|
60
|
+
lottieData?: unknown;
|
|
61
|
+
};
|
|
62
|
+
light?: {
|
|
63
|
+
type?: string;
|
|
64
|
+
html?: string;
|
|
65
|
+
lottie?: string;
|
|
66
|
+
lottieData?: unknown;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
} | null;
|
|
51
70
|
}
|
|
52
71
|
export interface TokenData {
|
|
53
72
|
accessToken: string;
|