@eka-care/medassist-widget-embed 0.2.58-0 → 0.2.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -101,7 +101,22 @@ type NudgeCacheHit = {
101
101
  path: string;
102
102
  data: NudgePathData;
103
103
  };
104
- declare function findCachedNudge(agentId: string, currentUrl: string): NudgeCacheHit | null;
104
+ /**
105
+ * Build path candidates from the most specific path back to "/" by stripping
106
+ * one segment at a time. e.g. /abc/efg/ff → ["/abc/efg/ff", "/abc/efg", "/abc", "/"]
107
+ */
108
+ declare function getNudgePathCandidates(pathname: string): string[];
109
+ /**
110
+ * Look up a cached nudge for the given path candidates (checked in order, most
111
+ * specific first). Also matches the wildcard variant of each candidate
112
+ * (e.g. "/abc/*"). Returns the first match, or null.
113
+ */
114
+ declare function findCachedNudgeForCandidates(agentId: string, url: URL, candidates: string[]): NudgeCacheHit | null;
115
+ /**
116
+ * Like findCachedNudgeForCandidates, but drops (and clears) an expired hit so
117
+ * callers always get a still-valid cached nudge or null.
118
+ */
119
+ declare function findFreshCachedNudge(agentId: string, url: URL, candidates: string[]): NudgeCacheHit | null;
105
120
  declare function clearNudgeForPath(agentId: string, domain: string, path: string): void;
106
121
  declare function storeNudgeResponse(agentId: string, response: NudgeApiResponse): void;
107
122
  declare const NUDGE_COOKIE_PREFIX = "eka-nudge";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.86-0/dist/"})();function mapAgentConfigThemeToWidgetTheme(e){if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...t&&{textColor:t},...e.mode&&{mode:e.mode},...e.header_tinted!==void 0&&{headerTinted:e.header_tinted},...e.title_img&&{titleImg:e.title_img},...e.tagline&&{tagline:e.tagline}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const n=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,i=await fetch(n,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!i.ok)return;const o=await i.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const NUDGE_STORAGE_KEY="eka-medassist-nudges";function getNudgeStore(){try{const e=localStorage.getItem(NUDGE_STORAGE_KEY);return e?JSON.parse(e):{}}catch{return{}}}function setNudgeStore(e){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(e))}catch{}}function normalizePath(e){let t=e.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function findCachedNudge(e,t){const i=getNudgeStore()[e];if(!i)return null;let o;try{o=new URL(t)}catch{return null}const s=o.host,a=i[s];if(!a)return null;const d=o.pathname.split("/").filter(Boolean),u=[];for(let c=d.length;c>=0;c--)u.push(c===0?"/":"/"+d.slice(0,c).join("/"));for(const c of u){if(a[c]!==void 0)return{domain:s,path:c,data:a[c]};const l=c==="/"?"/*":c+"/*";if(a[l]!==void 0)return{domain:s,path:l,data:a[l]}}return null}function clearNudgeForPath(e,t,n){const i=getNudgeStore(),o=i[e];!o||!o[t]||(delete o[t][n],setNudgeStore(i))}function storeNudgeResponse(e,t){var n,i,o,s;const a=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!a||!d)return;const u=getNudgeStore();u[e]||(u[e]={}),u[e][a]||(u[e][a]={}),u[e][a][d]={nudges:t.nudges,expiry:t.expiry,delay:(s=t.delay)!==null&&s!==void 0?s:5},setNudgeStore(u)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const n=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${n}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const n=t.split("=")[1];return n==="open"||n==="closed"?n:null}async function fetchNudgeData(e,t){const n=`${t}/med-assist/user-nudge`,i=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(o=>{var s,a,d;const u=(s=o.getAttribute("name"))!==null&&s!==void 0?s:void 0,c=(a=o.getAttribute("property"))!==null&&a!==void 0?a:void 0,l=(d=o.getAttribute("content"))!==null&&d!==void 0?d:void 0;(u||c)&&i.push({name:u,property:c,content:l})});try{const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,referer:typeof window!="undefined"?window.location.href:""},body:JSON.stringify({meta_tags:i,url:typeof window!="undefined"?window.location.href:""})});return o.ok?await o.json():void 0}catch{return}}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var n,i,o;Object.assign(globalMedAssistConfig,t);const s=getWidgetElement();if(s){if(t.agentId&&s.setAttribute("agent-id",t.agentId),t.authToken&&s.setAttribute("auth-token",t.authToken),t.title&&s.setAttribute("title",t.title),t.iconUrl&&s.setAttribute("icon-url",t.iconUrl),t.baseUrl&&s.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&s.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget")&&s.setAttribute("display-mode",t.displayMode),t.context)try{s.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&s.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.redirectUrl&&s.setAttribute("redirect-url",t.redirectUrl),!((n=t.theme)===null||n===void 0)&&n.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=s).openFromBridge)===null||o===void 0||o.call(i)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const e=scriptEl.dataset.widgetAssets;if(e==="local")return`${scriptBaseUrl}src/`;if(e&&e.length>0)try{return new URL(e,scriptBaseUrl).href}catch{return e.endsWith("/")?e:`${e}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(e=>{if(!e.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return e.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{getAgentConfig(){if(!this.agentConfigPromise){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=t.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",i=t.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);this.agentConfigPromise=fetchAgentConfig(n,i).catch(()=>{})}return this.agentConfigPromise}constructor(){super(),this.reactRoot=null,this.agentConfigPromise=null,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.initNudge()}))}scheduleIdle(t){if(typeof window=="undefined"){t();return}const n=window.requestIdleCallback;typeof n=="function"?n(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const n=this.getAttribute("display-mode")==="full"?"full":"widget";n!==this.displayMode&&(this.displayMode=n,n==="full"?this.initializeFullMode():this.renderButton())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}preloadBackgroundImage(){var t;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=n==null?void 0:n.theme)===null||t===void 0?void 0:t.backgroundImage,s=i==null?void 0:i.backgroundImage;o&&preloadImage(o),s&&s!==o&&preloadImage(s),this.getAgentConfig().then(a=>{var d;const u=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;u&&preloadImage(u)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=n=>{var i;((i=n.data)===null||i===void 0?void 0:i.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,n,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const u=(n=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&n!==void 0?n:"#ffffff",c=typeof window!="undefined"?window.location.href:"";let l=findCachedNudge(a,c);if(l){const f=Math.floor(Date.now()/1e3);l.data.expiry<=f&&(clearNudgeForPath(a,l.domain,l.path),l=null)}if(!l){const f=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,m=(f==null?void 0:f.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=await fetchNudgeData(a,m).catch(()=>{});if(!(!((i=w==null?void 0:w.nudges)===null||i===void 0)&&i.length)||(storeNudgeResponse(a,w),l=findCachedNudge(a,c),!l))return}const h=l.data.nudges[Math.floor(Math.random()*l.data.nudges.length)],p=(o=l.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(h,u)},p*1e3)}showNudgePopup(t,n){var i,o;const s=this.shadowRoot;if(!s||!(!((i=s.getElementById("medassist-widget-root"))===null||i===void 0)&&i.classList.contains("hidden")))return;const d=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||"";if(d&&getNudgeCookie(d)!==null||s.getElementById("medassist-nudge-popup"))return;const c=s.getElementById("medassist-open-btn"),l=c==null?void 0:c.getBoundingClientRect(),h=272,p=12,f=8,m=16,w=16;let y=window.innerWidth-h-p,v=76,x=h-m-f*2;if(l&&l.width>0){const g=l.left+l.width/2,A=g-h/2,_=window.innerWidth-h-p;y=Math.max(p,Math.min(A,_)),v=window.innerHeight-l.top+w,x=Math.max(m,Math.min(g-y-f,h-m-f*2))}const b=document.createElement("div");b.id="medassist-nudge-popup",b.innerHTML=`
1
+ "use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.86-0/dist/"})();function mapAgentConfigThemeToWidgetTheme(e){if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...t&&{textColor:t},...e.mode&&{mode:e.mode},...e.header_tinted!==void 0&&{headerTinted:e.header_tinted},...e.title_img&&{titleImg:e.title_img},...e.tagline&&{tagline:e.tagline}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const n=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,i=await fetch(n,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!i.ok)return;const o=await i.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const NUDGE_STORAGE_KEY="eka-medassist-nudges";function getNudgeStore(){try{const e=localStorage.getItem(NUDGE_STORAGE_KEY);return e?JSON.parse(e):{}}catch{return{}}}function setNudgeStore(e){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(e))}catch{}}function normalizePath(e){let t=e.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(e){const t=e.split("/").filter(Boolean),n=[];for(let i=t.length;i>=0;i--)n.push(i===0?"/":"/"+t.slice(0,i).join("/"));return n}function findCachedNudgeForCandidates(e,t,n){const o=getNudgeStore()[e];if(!o)return null;const s=t.host,a=o[s];if(!a)return null;for(const d of n){if(a[d]!==void 0)return{domain:s,path:d,data:a[d]};const l=d==="/"?"/*":d+"/*";if(a[l]!==void 0)return{domain:s,path:l,data:a[l]}}return null}function findFreshCachedNudge(e,t,n){const i=findCachedNudgeForCandidates(e,t,n);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(e,i.domain,i.path),null):i}function clearNudgeForPath(e,t,n){const i=getNudgeStore(),o=i[e];!o||!o[t]||(delete o[t][n],setNudgeStore(i))}function storeNudgeResponse(e,t){var n,i,o,s;const a=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!a||!d)return;const l=getNudgeStore();l[e]||(l[e]={}),l[e][a]||(l[e][a]={}),l[e][a][d]={nudges:t.nudges,expiry:t.expiry,delay:(s=t.delay)!==null&&s!==void 0?s:5},setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const n=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${n}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const n=t.split("=")[1];return n==="open"||n==="closed"?n:null}async function fetchNudgeData(e,t){const n=`${t}/med-assist/user-nudge`,i=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(o=>{var s,a,d;const l=(s=o.getAttribute("name"))!==null&&s!==void 0?s:void 0,h=(a=o.getAttribute("property"))!==null&&a!==void 0?a:void 0,c=(d=o.getAttribute("content"))!==null&&d!==void 0?d:void 0;(l||h)&&i.push({name:l,property:h,content:c})});try{const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,referer:typeof window!="undefined"?window.location.href:""},body:JSON.stringify({meta_tags:i,url:typeof window!="undefined"?window.location.href:""})});return o.ok?await o.json():void 0}catch{return}}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var n,i,o;Object.assign(globalMedAssistConfig,t);const s=getWidgetElement();if(s){if(t.agentId&&s.setAttribute("agent-id",t.agentId),t.authToken&&s.setAttribute("auth-token",t.authToken),t.title&&s.setAttribute("title",t.title),t.iconUrl&&s.setAttribute("icon-url",t.iconUrl),t.baseUrl&&s.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&s.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget")&&s.setAttribute("display-mode",t.displayMode),t.context)try{s.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&s.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.redirectUrl&&s.setAttribute("redirect-url",t.redirectUrl),!((n=t.theme)===null||n===void 0)&&n.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=s).openFromBridge)===null||o===void 0||o.call(i)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const e=scriptEl.dataset.widgetAssets;if(e==="local")return`${scriptBaseUrl}src/`;if(e&&e.length>0)try{return new URL(e,scriptBaseUrl).href}catch{return e.endsWith("/")?e:`${e}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(e=>{if(!e.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return e.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{getAgentConfig(){if(!this.agentConfigPromise){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=t.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",i=t.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);this.agentConfigPromise=fetchAgentConfig(n,i).catch(()=>{})}return this.agentConfigPromise}constructor(){super(),this.reactRoot=null,this.agentConfigPromise=null,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.initNudge()}))}scheduleIdle(t){if(typeof window=="undefined"){t();return}const n=window.requestIdleCallback;typeof n=="function"?n(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const n=this.getAttribute("display-mode")==="full"?"full":"widget";n!==this.displayMode&&(this.displayMode=n,n==="full"?this.initializeFullMode():this.renderButton())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}preloadBackgroundImage(){var t;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=n==null?void 0:n.theme)===null||t===void 0?void 0:t.backgroundImage,s=i==null?void 0:i.backgroundImage;o&&preloadImage(o),s&&s!==o&&preloadImage(s),this.getAgentConfig().then(a=>{var d;const l=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;l&&preloadImage(l)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=n=>{var i;((i=n.data)===null||i===void 0?void 0:i.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,n,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const l=(n=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&n!==void 0?n:"#ffffff",h=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(h)}catch{return}const f=getNudgePathCandidates(c.pathname),p=f.slice(0,2),w=f.slice(2);let g=findFreshCachedNudge(a,c,p);if(!g){const b=(s==null?void 0:s.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",m=await fetchNudgeData(a,b).catch(()=>{});!((i=m==null?void 0:m.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(a,m),g=findFreshCachedNudge(a,c,f))}if(g||(g=findFreshCachedNudge(a,c,w)),!g)return;const x=g.data.nudges[Math.floor(Math.random()*g.data.nudges.length)],y=(o=g.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(x,l)},y*1e3)}showNudgePopup(t,n){var i,o;const s=this.shadowRoot;if(!s||!(!((i=s.getElementById("medassist-widget-root"))===null||i===void 0)&&i.classList.contains("hidden")))return;const d=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||"";if(d&&getNudgeCookie(d)!==null||s.getElementById("medassist-nudge-popup"))return;const h=s.getElementById("medassist-open-btn"),c=h==null?void 0:h.getBoundingClientRect(),f=272,p=12,w=8,g=16,x=16;let y=window.innerWidth-f-p,b=76,m=f-g-w*2;if(c&&c.width>0){const u=c.left+c.width/2,A=u-f/2,_=window.innerWidth-f-p;y=Math.max(p,Math.min(A,_)),b=window.innerHeight-c.top+x,m=Math.max(g,Math.min(u-y-w,f-g-w*2))}const v=document.createElement("div");v.id="medassist-nudge-popup",v.innerHTML=`
2
2
  <style>
3
3
  @keyframes nudge-slide-up {
4
4
  from { opacity: 0; transform: translateY(12px) scale(0.97); }
@@ -6,9 +6,9 @@
6
6
  }
7
7
  #medassist-nudge-popup {
8
8
  position: fixed;
9
- bottom: ${v}px;
9
+ bottom: ${b}px;
10
10
  left: ${y}px;
11
- width: ${h}px;
11
+ width: ${f}px;
12
12
  background: ${n};
13
13
  border-radius: 16px;
14
14
  box-shadow: 0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08);
@@ -26,7 +26,7 @@
26
26
  content: '';
27
27
  position: absolute;
28
28
  bottom: -8px;
29
- left: ${x}px;
29
+ left: ${m}px;
30
30
  width: 16px;
31
31
  height: 10px;
32
32
  background: ${n};
@@ -79,7 +79,7 @@
79
79
  <p class="nudge-text">${t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}</p>
80
80
  <button class="nudge-close" aria-label="Dismiss">&#x2715;</button>
81
81
  </div>
82
- `,(o=b.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",g=>{g.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),b.addEventListener("click",()=>{d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.loadAndRender()}),s.appendChild(b)}dismissNudgePopup(){var t;const n=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");n==null||n.remove()}applyCustomLauncherStyles(){var t;const n=this.shadowRoot;if(!n||this.displayMode!=="widget")return;const i=n.querySelector('style[data-medassist-custom-launcher="true"]'),o=(t=this.getAttribute("custom-launcher-styles"))!==null&&t!==void 0?t:"";if(!o){i==null||i.remove();return}if(i){i.textContent=o;return}const s=document.createElement("style");s.setAttribute("data-medassist-custom-launcher","true"),s.textContent=o,n.appendChild(s)}renderButton(){var t;const n=this.getAttribute("icon-url")||this.defaultIconUrl,i=this.shadowRoot;if(!i){console.error("Shadow root was not created");return}if(!i.querySelector("button"))i.innerHTML=`
82
+ `,(o=v.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",u=>{u.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),v.addEventListener("click",()=>{d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.loadAndRender()}),s.appendChild(v)}dismissNudgePopup(){var t;const n=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");n==null||n.remove()}applyCustomLauncherStyles(){var t;const n=this.shadowRoot;if(!n||this.displayMode!=="widget")return;const i=n.querySelector('style[data-medassist-custom-launcher="true"]'),o=(t=this.getAttribute("custom-launcher-styles"))!==null&&t!==void 0?t:"";if(!o){i==null||i.remove();return}if(i){i.textContent=o;return}const s=document.createElement("style");s.setAttribute("data-medassist-custom-launcher","true"),s.textContent=o,n.appendChild(s)}renderButton(){var t;const n=this.getAttribute("icon-url")||this.defaultIconUrl,i=this.shadowRoot;if(!i){console.error("Shadow root was not created");return}if(!i.querySelector("button"))i.innerHTML=`
83
83
  <style>
84
84
  #medassist-open-btn {
85
85
  width: 60px;
@@ -138,4 +138,4 @@
138
138
  }
139
139
  </style>
140
140
  <div id="medassist-widget-root"></div>
141
- `)}async loadAndRender(){var t,n,i,o,s;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}this.style.display="";const d=a.getElementById("medassist-open-btn"),u=a.getElementById("medassist-widget-root"),c=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||this.defaultIconUrl;const h=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production",p=this.getAttribute("connectivity"),f=p==="sse"||p==="socket"?p:void 0;let m=this.getAttribute("title")||"Medi Clinic";const w=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",v=this.getAttribute("display-mode")==="full"?"full":"widget",x=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,b=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,g=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},A={...x||{},...g.context||{}},_=g.auth||void 0,B=g.authToken||this.getAttribute("auth-token")||void 0,k=g.agentId||c,P=g.baseUrl||w,C=typeof window!="undefined"?(n=window.EkaMedAssist)===null||n===void 0?void 0:n.onClose:void 0,T=this.getAttribute("redirect-url")||void 0,M=g.redirectUrl||T,$=!!M||g.showCloseButton===!0;if(!k){console.error("Agent ID is required");return}if(!u){console.error("Widget root element is missing");return}d&&d.classList.add("hidden"),u.classList.remove("hidden");let E,S,I,U=!1,L,R=!1;try{const r=await this.getAgentConfig();m=(r==null?void 0:r.name)||m,l=((i=r==null?void 0:r.theme)===null||i===void 0?void 0:i.icon_img)||l,E=mapAgentConfigThemeToWidgetTheme((r==null?void 0:r.theme)||void 0),S=r==null?void 0:r.allowed,I=r==null?void 0:r.connectivity,U=(r==null?void 0:r.resize)||(g==null?void 0:g.resize)||!1,L=r==null?void 0:r.initial_message,R=(s=(o=r==null?void 0:r.theme)===null||o===void 0?void 0:o.hide_watermark)!==null&&s!==void 0?s:!1}catch{}const W=I||f||"socket",N={title:g.title||m,iconUrl:l||g.iconUrl,showCloseButton:$,allowed:S,environment:h,connectionType:W,onClose:()=>{var r;if((r=this.reactRoot)===null||r===void 0||r.unmount(),this.reactRoot=null,C&&typeof C=="function"&&C(),M){window.location.href=M;return}v==="full"?this.style.display="none":(d&&d.classList.remove("hidden"),u.classList.add("hidden"))},baseUrl:P,context:A,displayMode:v,resize:U||this.getAttribute("resize")==="true",auth:_,authToken:B,initialMessage:L,hideWatermark:R,theme:{...E||{},...b||{},...g.theme||{}}},z=window;if(this.widgetLoaded){this.reactRoot=z.renderMedAssist(u,k,N);return}try{const[,r]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=r.renderMedAssist(u,k,N),this.widgetLoaded=!0}catch(r){console.error("Failed to load MedAssist widget",r),d&&d.classList.remove("hidden"),u.classList.add("hidden")}}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const n=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=n,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
141
+ `)}async loadAndRender(){var t,n,i,o,s;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}this.style.display="";const d=a.getElementById("medassist-open-btn"),l=a.getElementById("medassist-widget-root"),h=this.getAttribute("agent-id");let c=this.getAttribute("icon-url")||this.defaultIconUrl;const f=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production",p=this.getAttribute("connectivity"),w=p==="sse"||p==="socket"?p:void 0;let g=this.getAttribute("title")||"Medi Clinic";const x=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",b=this.getAttribute("display-mode")==="full"?"full":"widget",m=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,v=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,u=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},A={...m||{},...u.context||{}},_=u.auth||void 0,B=u.authToken||this.getAttribute("auth-token")||void 0,C=u.agentId||h,P=u.baseUrl||x,k=typeof window!="undefined"?(n=window.EkaMedAssist)===null||n===void 0?void 0:n.onClose:void 0,T=this.getAttribute("redirect-url")||void 0,M=u.redirectUrl||T,$=!!M||u.showCloseButton===!0;if(!C){console.error("Agent ID is required");return}if(!l){console.error("Widget root element is missing");return}d&&d.classList.add("hidden"),l.classList.remove("hidden");let E,S,I,U=!1,L,R=!1;try{const r=await this.getAgentConfig();g=(r==null?void 0:r.name)||g,c=((i=r==null?void 0:r.theme)===null||i===void 0?void 0:i.icon_img)||c,E=mapAgentConfigThemeToWidgetTheme((r==null?void 0:r.theme)||void 0),S=r==null?void 0:r.allowed,I=r==null?void 0:r.connectivity,U=(r==null?void 0:r.resize)||(u==null?void 0:u.resize)||!1,L=r==null?void 0:r.initial_message,R=(s=(o=r==null?void 0:r.theme)===null||o===void 0?void 0:o.hide_watermark)!==null&&s!==void 0?s:!1}catch{}const W=I||w||"socket",N={title:u.title||g,iconUrl:c||u.iconUrl,showCloseButton:$,allowed:S,environment:f,connectionType:W,onClose:()=>{var r;if((r=this.reactRoot)===null||r===void 0||r.unmount(),this.reactRoot=null,k&&typeof k=="function"&&k(),M){window.location.href=M;return}b==="full"?this.style.display="none":(d&&d.classList.remove("hidden"),l.classList.add("hidden"))},baseUrl:P,context:A,displayMode:b,resize:U||this.getAttribute("resize")==="true",auth:_,authToken:B,initialMessage:L,hideWatermark:R,theme:{...E||{},...v||{},...u.theme||{}}},z=window;if(this.widgetLoaded){this.reactRoot=z.renderMedAssist(l,C,N);return}try{const[,r]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=r.renderMedAssist(l,C,N),this.widgetLoaded=!0}catch(r){console.error("Failed to load MedAssist widget",r),d&&d.classList.remove("hidden"),l.classList.add("hidden")}}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const n=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=n,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eka-care/medassist-widget-embed",
3
- "version": "0.2.58-0",
3
+ "version": "0.2.58",
4
4
  "description": "Embeddable MedAssist widget loader built with Web Components.",
5
5
  "author": "Geethanjali S",
6
6
  "license": "MIT",