@eka-care/medassist-widget-embed 0.2.119-dev.0 → 0.2.119
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/eka-agents.html +4 -4
- package/dist/iframe.js +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/dist/eka-agents.html
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
CORS mode — the browser would download it twice. -->
|
|
19
19
|
<link
|
|
20
20
|
rel="modulepreload"
|
|
21
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141
|
|
21
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/medassist-widget.js"
|
|
22
22
|
fetchpriority="high"
|
|
23
23
|
crossorigin
|
|
24
24
|
/>
|
|
@@ -27,14 +27,14 @@
|
|
|
27
27
|
<link
|
|
28
28
|
rel="preload"
|
|
29
29
|
as="style"
|
|
30
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141
|
|
30
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/medassist-widget.css"
|
|
31
31
|
onload="this.rel='stylesheet'"
|
|
32
32
|
crossorigin
|
|
33
33
|
/>
|
|
34
34
|
<noscript>
|
|
35
35
|
<link
|
|
36
36
|
rel="stylesheet"
|
|
37
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141
|
|
37
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/medassist-widget.css"
|
|
38
38
|
/>
|
|
39
39
|
</noscript>
|
|
40
40
|
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
window.renderMedAssist would never be set. -->
|
|
150
150
|
<script
|
|
151
151
|
type="module"
|
|
152
|
-
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141
|
|
152
|
+
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/medassist-widget.js"
|
|
153
153
|
onload="init()"
|
|
154
154
|
fetchpriority="high"
|
|
155
155
|
crossorigin
|
package/dist/iframe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},C=e=>{if(e==="production"||e==="development"||e==="staging")return e};function z(e){var t;if(!e)return;const r=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background&&{background:e.background},...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...r&&{textColor:r},...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},...e.consent_content&&{consentContent:e.consent_content},...((t=e.tips)===null||t===void 0?void 0:t.length)&&{tips:e.tips},...e.feature!==void 0&&{feature:e.feature}}}function S(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 F(e,t,r){var n;try{return await h(),await((n=window.fetchAgentConfig)===null||n===void 0?void 0:n.call(window,{agentId:t,serverUrl:e,environment:r,channel:"web"}))}catch{return}}const U="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141
|
|
1
|
+
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},C=e=>{if(e==="production"||e==="development"||e==="staging")return e};function z(e){var t;if(!e)return;const r=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background&&{background:e.background},...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...r&&{textColor:r},...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},...e.consent_content&&{consentContent:e.consent_content},...((t=e.tips)===null||t===void 0?void 0:t.length)&&{tips:e.tips},...e.feature!==void 0&&{feature:e.feature}}}function S(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 F(e,t,r){var n;try{return await h(),await((n=window.fetchAgentConfig)===null||n===void 0?void 0:n.call(window,{agentId:t,serverUrl:e,environment:r,channel:"web"}))}catch{return}}const U="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/",s=$(),b=(()=>{if(!s)return"";try{return new URL(".",s.src||window.location.href).href}catch{return""}})(),u=(()=>{if(!s)return U;const e=s.dataset.widgetAssets;if(e==="local")return`${b}src/`;if(e&&e.length>0)try{return new URL(e,b).href}catch{return e.endsWith("/")?e:`${e}/`}return U})(),a=`${u}medassist-widget.js`,g=`${u}medassist-widget.css`;let f=null,m=null;const i=new URLSearchParams(typeof window!="undefined"?window.location.search:""),A=i.get("agentId"),w=i.get("baseUrl")||"https://matrix.eka.care/reloaded";if(typeof document!="undefined"&&document.head){try{const e=new URL(u).origin,t=new URL(w).origin,r=document.createElement("link");if(r.rel="preconnect",r.href=e,r.crossOrigin="anonymous",document.head.appendChild(r),e!==t){const c=document.createElement("link");c.rel="preconnect",c.href=t,c.crossOrigin="anonymous",document.head.appendChild(c)}const n=document.createElement("link");n.rel="modulepreload",n.href=a,document.head.appendChild(n);const d=document.createElement("link");d.rel="preload",d.as="style",d.href=g,document.head.appendChild(d)}catch{}M(),h()}const L=A&&w?F(w,A,C(i.get("environment"))):Promise.resolve(void 0);if(typeof document!="undefined"&&document.head){const e=i.get("theme");if(e)try{const t=JSON.parse(e);t.backgroundImage&&S(t.backgroundImage)}catch{}L.then(t=>{var r;const n=(r=t==null?void 0:t.theme)===null||r===void 0?void 0:r.background_img;n&&S(n)})}const I=async()=>{var e,t,r,n,d,c,p;const P=i.get("agentId");if(!P){console.error("Agent ID is required in URL parameters");return}let v=i.get("title")||"Medi Clinic",y=i.get("iconUrl")||void 0;const x=i.get("context"),G=i.get("baseUrl")||"https://matrix.eka.care/reloaded",O=i.get("auth-token")||void 0;let k=i.get("resize")==="true"?!0:void 0;const J=(e=C(i.get("environment")))!==null&&e!==void 0?e:"production",_=i.get("connectivity"),N=_==="http_stream"||_==="socket"?_:void 0,E=i.get("theme")?(()=>{try{return JSON.parse(i.get("theme")||"{}")}catch{return}})():void 0,q=document.getElementById("root")||document.body;try{const[,,o]=await Promise.all([M(),h(),L]);if(!(window!=null&&window.renderMedAssist)||typeof(window==null?void 0:window.renderMedAssist)!="function")throw new Error("renderMedAssist is not available on window");let l,W,R,B,D=!1;o&&(v=(t=o==null?void 0:o.name)!==null&&t!==void 0?t:v,y=(n=(r=o==null?void 0:o.theme)===null||r===void 0?void 0:r.icon_img)!==null&&n!==void 0?n:y,l=z((d=o==null?void 0:o.theme)!==null&&d!==void 0?d:void 0),W=o==null?void 0:o.allowed,R=o==null?void 0:o.connectivity,B=o==null?void 0:o.initial_message,D=(p=(c=o==null?void 0:o.theme)===null||c===void 0?void 0:c.hide_watermark)!==null&&p!==void 0?p:!1,k=k||(o==null?void 0:o.resize)||void 0);const H={title:v,iconUrl:y,environment:J,connectionType:R||N||"socket",onClose:()=>{window.parent!==window&&window.parent.postMessage({type:"WIDGET_CLOSE"},"*")},context:x?JSON.parse(x):void 0,baseUrl:G,displayMode:"full",allowed:W,showCloseButton:!1,resize:k,initialMessage:B,hideWatermark:D,...O&&{authToken:O},theme:{...l!=null?l:{},...E!=null?E:{}}};window.renderMedAssist(q,P,H)}catch(o){throw console.error("Failed to initialize MedAssist widget",o),o}};async function M(){document.querySelector("link[data-medassist-style='true']")||(m||(m=new Promise((t,r)=>{const n=document.createElement("link");n.rel="stylesheet",n.href=g,n.setAttribute("data-medassist-style","true"),n.onload=()=>{t("")},n.onerror=()=>{r(new Error(`Failed to load ${g}`))},document.head.appendChild(n)})),await m)}function h(){return f||(f=new Promise((e,t)=>{const r=document.querySelector(`script[src="${a}"]`);if(r){if(r.dataset.loaded==="true"){e();return}r.addEventListener("load",()=>e()),r.addEventListener("error",d=>t(d.error||new Error("Unknown script loading error")));return}const n=document.createElement("script");n.src=a,n.type="module",n.async=!0,n.dataset.widget="medassist",n.onload=()=>{n.dataset.loaded="true",e()},n.onerror=d=>{if(d instanceof ErrorEvent&&d.error){t(d.error);return}t(new Error(`Failed to load ${a}`))},document.head.appendChild(n)})),f}if(typeof document!="undefined")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",I);else try{I()}catch(e){console.error("Failed to initialize MedAssist widget",e)}})();
|
package/dist/index.d.ts
CHANGED
|
@@ -203,6 +203,13 @@ declare const WIDGET_STORE_KEY_PREFIX = "med-assist-store-";
|
|
|
203
203
|
/** Sess (access) token persisted by the widget store, if the widget already ran in this tab. */
|
|
204
204
|
declare function readPersistedSessToken(agentId: string): string | undefined;
|
|
205
205
|
declare function fetchNudgeData(agentId: string, sessToken: string, baseUrl?: string, channel?: SynapseChannel): Promise<NudgeApiResponse | undefined>;
|
|
206
|
+
/**
|
|
207
|
+
* Chatbox placeholders read as an open invitation, so each ends in "…".
|
|
208
|
+
* Nudge / suggestion / host strings arrive without one: a trailing "." or
|
|
209
|
+
* "..." becomes "…"; one that already ends in "…", "?" or "!" is left as is
|
|
210
|
+
* ("Need help booking?…" reads wrong).
|
|
211
|
+
*/
|
|
212
|
+
declare function withTrailingEllipsis(text: string): string;
|
|
206
213
|
type ReactRoot = {
|
|
207
214
|
unmount: () => void;
|
|
208
215
|
};
|
|
@@ -437,6 +444,7 @@ declare class MedAssistWidgetLoader extends HTMLElement {
|
|
|
437
444
|
private growWidgetFromChatbox;
|
|
438
445
|
/** Placeholders the chatbox cycles through while idle: host `chatbox-placeholders` / init({ chatboxPlaceholders }) first, else this page's nudges, else the agent's suggestion labels, else generic defaults. */
|
|
439
446
|
private getChatboxPlaceholders;
|
|
447
|
+
private collectChatboxPlaceholders;
|
|
440
448
|
/** Grow the chatbox textarea with its content (up to its max-height, then scroll). */
|
|
441
449
|
private autosizeChatbox;
|
|
442
450
|
/** Fade the top / bottom edge of the textarea only where there is more text beyond it. */
|
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:s}=document;if(s instanceof HTMLScriptElement)return s;const t=Array.from(document.getElementsByTagName("script")),e=t.find(o=>o.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=s=>{if(s==="production"||s==="development"||s==="staging")return s},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var s;return!((s=scriptEl==null?void 0:scriptEl.src)===null||s===void 0)&&s.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141-dev.0/dist/"})();var FeedbackTypeEnum;(function(s){s.DEFAULT="default",s.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(s){var t;if(!s)return;const e=s.mode==="dark"?"white":s.mode==="light"?"black":void 0;return{...s.background_img&&{backgroundImage:s.background_img},...s.accent&&{primary:s.accent},...e&&{textColor:e},...s.mode&&{mode:s.mode},...s.header_tinted!==void 0&&{headerTinted:s.header_tinted},...s.title_img&&{titleImg:s.title_img},...s.tagline&&{tagline:s.tagline},...s.hide_watermark&&{hideWatermark:s.hide_watermark},...s.explicit_disclaimer&&{explicitDisclaimer:s.explicit_disclaimer},...s.consent_content&&{consentContent:s.consent_content},...s.upfront_consent&&{upfrontConsent:s.upfront_consent},...((t=s.tips)===null||t===void 0?void 0:t.length)&&{tips:s.tips},...s.feature!==void 0&&{feature:s.feature},...typeof s.widget_width=="number"&&{widgetWidth:s.widget_width},...typeof s.widget_height=="number"&&{widgetHeight:s.widget_height}}}function preloadImage(s){if(!(!s||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=s,document.head.appendChild(t)}catch{const t=new Image;t.src=s}}function channelFromDisplayMode(s){return s==="full"?"web":s==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var s;return typeof window!="undefined"&&!!(!((s=window.matchMedia)===null||s===void 0)&&s.call(window,"(prefers-reduced-motion: reduce)").matches)}function nextFrame(){return new Promise(s=>requestAnimationFrame(()=>s()))}function colorOnAccent(s){const t=s.trim().replace("#",""),e=t.length===3?t.split("").map(n=>n+n).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(n=>parseInt(e.slice(n,n+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(s){return s==="full"?"full":s==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(s){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[s]}catch{return}}function writeAgentConfigCache(s,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[s]={...i[s]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const s=localStorage.getItem(NUDGE_STORAGE_KEY);return s?JSON.parse(s):{}}catch{return{}}}function setNudgeStore(s){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(s))}catch{}}function normalizePath(s){let t=s.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(s){const t=s.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(s,t,e){const o=getNudgeStore()[s];if(!o)return null;const n=t.host,a=o[n];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:n,path:d,data:a[d]};const r=d==="/"?"/*":d+"/*";if(a[r]!==void 0)return{domain:n,path:r,data:a[r]}}return null}function findFreshCachedNudge(s,t,e){const i=findCachedNudgeForCandidates(s,t,e);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(s,i.domain,i.path),null):i}function clearNudgeForPath(s,t,e){const i=getNudgeStore(),o=i[s];!o||!o[t]||(delete o[t][e],setNudgeStore(i))}function storeNudgeResponse(s,t,e){var i,o,n,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,r=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((n=t.nudges)===null||n===void 0)&&n.length)||!t.expiry||!d||!r)return;const l=getNudgeStore();l[s]||(l[s]={}),l[s][d]||(l[s][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};l[s][d][r]=c,e&&e!==r&&(l[s][d][e]=c),setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(s,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${s}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(s){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${s}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(s){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${s}`),o=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(s,t,e,i="widget"){const o=`${e}/med-assist/user-nudge`,n=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,r,l;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,h=(r=a.getAttribute("property"))!==null&&r!==void 0?r:void 0,m=(l=a.getAttribute("content"))!==null&&l!==void 0?l:void 0;(c||h)&&n.push({name:c,property:h,content:m})});try{const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":s,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:n,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const s=window;s.__ekaMedAssistConfig__=globalMedAssistConfig,s.EkaMedAssist={init(t){var e,i,o;Object.assign(globalMedAssistConfig,t);const n=getWidgetElement();if(n){if(t.agentId&&n.setAttribute("agent-id",t.agentId),t.authToken&&n.setAttribute("auth-token",t.authToken),t.title&&n.setAttribute("title",t.title),t.iconUrl&&n.setAttribute("icon-url",t.iconUrl),t.baseUrl&&n.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&n.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&n.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&n.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&n.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&n.setAttribute("side",t.side),t.context)try{n.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&n.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&n.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&n.setAttribute("redirect-url",t.redirectUrl),!((e=t.theme)===null||e===void 0)&&e.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=n).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 s=scriptEl.dataset.widgetAssets;if(s==="local")return`${scriptBaseUrl}src/`;if(s&&s.length>0)try{return new URL(s,scriptBaseUrl).href}catch{return s.endsWith("/")?s:`${s}/`}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(s=>{if(!s.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return s.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},o=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(o?(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),o=t.getElementById("medassist-open-btn");if(o){const a=e==="loading"&&!i;o.classList.toggle("loading",a),o.classList.toggle("hidden",e==="open"||i),a?o.setAttribute("aria-busy","true"):o.removeAttribute("aria-busy")}const n=t.getElementById("medassist-chatbox");if(n){this.applyChatboxTheme(n);const a=e==="loading"&&i;n.classList.toggle("hidden",e==="open"||!i),n.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";n.classList.toggle("continuing",d),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d,e==="open"&&(r.value="",this.autosizeChatbox());const l=n.querySelector(".medassist-chatbox-send");l&&(l.disabled=!r.value.trim())}}}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=e.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const n=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:o,serverUrl:i,environment:n,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,o,n;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(n=this.hostPushStyleEl)===null||n===void 0||n.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var o;if(typeof document=="undefined")return;const n=t?{width:e,side:i}:null,a=this.hostPushState;if(a===n||a&&n&&a.width===n.width&&a.side===n.side)return;this.hostPushState=n,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
1
|
+
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:s}=document;if(s instanceof HTMLScriptElement)return s;const t=Array.from(document.getElementsByTagName("script")),e=t.find(o=>o.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=s=>{if(s==="production"||s==="development"||s==="staging")return s},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var s;return!((s=scriptEl==null?void 0:scriptEl.src)===null||s===void 0)&&s.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/"})();var FeedbackTypeEnum;(function(s){s.DEFAULT="default",s.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(s){var t;if(!s)return;const e=s.mode==="dark"?"white":s.mode==="light"?"black":void 0;return{...s.background_img&&{backgroundImage:s.background_img},...s.accent&&{primary:s.accent},...e&&{textColor:e},...s.mode&&{mode:s.mode},...s.header_tinted!==void 0&&{headerTinted:s.header_tinted},...s.title_img&&{titleImg:s.title_img},...s.tagline&&{tagline:s.tagline},...s.hide_watermark&&{hideWatermark:s.hide_watermark},...s.explicit_disclaimer&&{explicitDisclaimer:s.explicit_disclaimer},...s.consent_content&&{consentContent:s.consent_content},...s.upfront_consent&&{upfrontConsent:s.upfront_consent},...((t=s.tips)===null||t===void 0?void 0:t.length)&&{tips:s.tips},...s.feature!==void 0&&{feature:s.feature},...typeof s.widget_width=="number"&&{widgetWidth:s.widget_width},...typeof s.widget_height=="number"&&{widgetHeight:s.widget_height}}}function preloadImage(s){if(!(!s||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=s,document.head.appendChild(t)}catch{const t=new Image;t.src=s}}function channelFromDisplayMode(s){return s==="full"?"web":s==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var s;return typeof window!="undefined"&&!!(!((s=window.matchMedia)===null||s===void 0)&&s.call(window,"(prefers-reduced-motion: reduce)").matches)}function nextFrame(){return new Promise(s=>requestAnimationFrame(()=>s()))}function colorOnAccent(s){const t=s.trim().replace("#",""),e=t.length===3?t.split("").map(n=>n+n).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(n=>parseInt(e.slice(n,n+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(s){return s==="full"?"full":s==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(s){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[s]}catch{return}}function writeAgentConfigCache(s,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[s]={...i[s]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const s=localStorage.getItem(NUDGE_STORAGE_KEY);return s?JSON.parse(s):{}}catch{return{}}}function setNudgeStore(s){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(s))}catch{}}function normalizePath(s){let t=s.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(s){const t=s.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(s,t,e){const o=getNudgeStore()[s];if(!o)return null;const n=t.host,a=o[n];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:n,path:d,data:a[d]};const r=d==="/"?"/*":d+"/*";if(a[r]!==void 0)return{domain:n,path:r,data:a[r]}}return null}function findFreshCachedNudge(s,t,e){const i=findCachedNudgeForCandidates(s,t,e);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(s,i.domain,i.path),null):i}function clearNudgeForPath(s,t,e){const i=getNudgeStore(),o=i[s];!o||!o[t]||(delete o[t][e],setNudgeStore(i))}function storeNudgeResponse(s,t,e){var i,o,n,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,r=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((n=t.nudges)===null||n===void 0)&&n.length)||!t.expiry||!d||!r)return;const l=getNudgeStore();l[s]||(l[s]={}),l[s][d]||(l[s][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};l[s][d][r]=c,e&&e!==r&&(l[s][d][e]=c),setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(s,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${s}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(s){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${s}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(s){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${s}`),o=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(s,t,e,i="widget"){const o=`${e}/med-assist/user-nudge`,n=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,r,l;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,h=(r=a.getAttribute("property"))!==null&&r!==void 0?r:void 0,m=(l=a.getAttribute("content"))!==null&&l!==void 0?l:void 0;(c||h)&&n.push({name:c,property:h,content:m})});try{const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":s,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:n,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(s){const t=s.trim();return/[…?!]$/.test(t)?t:`${t.replace(/\.+$/,"")}\u2026`}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const s=window;s.__ekaMedAssistConfig__=globalMedAssistConfig,s.EkaMedAssist={init(t){var e,i,o;Object.assign(globalMedAssistConfig,t);const n=getWidgetElement();if(n){if(t.agentId&&n.setAttribute("agent-id",t.agentId),t.authToken&&n.setAttribute("auth-token",t.authToken),t.title&&n.setAttribute("title",t.title),t.iconUrl&&n.setAttribute("icon-url",t.iconUrl),t.baseUrl&&n.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&n.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&n.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&n.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&n.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&n.setAttribute("side",t.side),t.context)try{n.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&n.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&n.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&n.setAttribute("redirect-url",t.redirectUrl),!((e=t.theme)===null||e===void 0)&&e.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=n).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 s=scriptEl.dataset.widgetAssets;if(s==="local")return`${scriptBaseUrl}src/`;if(s&&s.length>0)try{return new URL(s,scriptBaseUrl).href}catch{return s.endsWith("/")?s:`${s}/`}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(s=>{if(!s.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return s.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},o=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(o?(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),o=t.getElementById("medassist-open-btn");if(o){const a=e==="loading"&&!i;o.classList.toggle("loading",a),o.classList.toggle("hidden",e==="open"||i),a?o.setAttribute("aria-busy","true"):o.removeAttribute("aria-busy")}const n=t.getElementById("medassist-chatbox");if(n){this.applyChatboxTheme(n);const a=e==="loading"&&i;n.classList.toggle("hidden",e==="open"||!i),n.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";n.classList.toggle("continuing",d),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d,e==="open"&&(r.value="",this.autosizeChatbox());const l=n.querySelector(".medassist-chatbox-send");l&&(l.disabled=!r.value.trim())}}}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=e.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const n=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:o,serverUrl:i,environment:n,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,o,n;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(n=this.hostPushStyleEl)===null||n===void 0||n.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var o;if(typeof document=="undefined")return;const n=t?{width:e,side:i}:null,a=this.hostPushState;if(a===n||a&&n&&a.width===n.width&&a.side===n.side)return;this.hostPushState=n,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
2
2
|
body.eka-medassist-pushed {
|
|
3
3
|
${d}: ${e}px;
|
|
4
4
|
transition: margin 300ms ease;
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
@media (prefers-reduced-motion: reduce) {
|
|
10
10
|
body.eka-medassist-pushed { transition: none !important; }
|
|
11
11
|
}
|
|
12
|
-
`;const r=document.documentElement.style;t?(r.setProperty("--eka-medassist-panel-width",`${e}px`),r.setProperty("--eka-medassist-panel-side",i),document.body.classList.add("eka-medassist-pushed")):(document.body.classList.remove("eka-medassist-pushed"),r.removeProperty("--eka-medassist-panel-width"),r.removeProperty("--eka-medassist-panel-side"),this.hostPushStyleEl.remove(),this.hostPushStyleEl=null);const l={pushed:t,width:e,side:i};if(typeof window!="undefined"){try{window.dispatchEvent(new CustomEvent(SIDE_PANEL_PUSH_EVENT,{detail:l}))}catch{}const c=(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onSidePanelPushChange;if(typeof c=="function")try{c(t,e,i)}catch(h){console.error("EkaMedAssist.onSidePanelPushChange threw",h)}}}scheduleIdle(t){if(typeof window=="undefined"){t();return}const e=window.requestIdleCallback;typeof e=="function"?e(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode!=="full"&&this.renderLauncher(),t==="display-mode"){const e=normalizeDisplayMode(this.getAttribute("display-mode"));e!==this.displayMode&&(this.displayMode=e,e==="full"?this.initializeFullMode():this.renderLauncher())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles(),t==="launcher-type"&&this.updateLauncherView()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchPromise)return this.authPrefetchPromise;const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);const o=e.authToken||this.getAttribute("auth-token")||void 0,n=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",a=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";return this.authPrefetchPromise=this.loadWidgetModule().then(d=>{var r;return(r=d.prefetchAuth)===null||r===void 0?void 0:r.call(d,{agentId:i,authToken:o,serverUrl:n,environment:a,channel:this.getChannel()})}).catch(()=>{this.authPrefetchPromise=null}),this.authPrefetchPromise}async resolveSessToken(t){const e=readPersistedSessToken(t);if(e)return e;const i=await this.prefetchAuthTokens();return(i==null?void 0:i.sess_token)||readPersistedSessToken(t)}preloadBackgroundImage(){var t;const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=e==null?void 0:e.theme)===null||t===void 0?void 0:t.backgroundImage,n=i==null?void 0:i.backgroundImage;o&&preloadImage(o),n&&n!==o&&preloadImage(n),this.getAgentConfig().then(a=>{var d;const r=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;r&&preloadImage(r)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=e=>{var i;((i=e.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(){if(this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.displayMode==="full")this.initializeFullMode();else if(this.renderLauncher(),this.getLauncherType()==="chatbox")return;this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,e,i,o;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(n==null?void 0:n.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const r=(e=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&e!==void 0?e:"#ffffff",l=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(l)}catch{return}const h=getNudgePathCandidates(c.pathname),m=h.slice(0,1),x=h.slice(1);let p=findFreshCachedNudge(a,c,m);if(!p){const
|
|
12
|
+
`;const r=document.documentElement.style;t?(r.setProperty("--eka-medassist-panel-width",`${e}px`),r.setProperty("--eka-medassist-panel-side",i),document.body.classList.add("eka-medassist-pushed")):(document.body.classList.remove("eka-medassist-pushed"),r.removeProperty("--eka-medassist-panel-width"),r.removeProperty("--eka-medassist-panel-side"),this.hostPushStyleEl.remove(),this.hostPushStyleEl=null);const l={pushed:t,width:e,side:i};if(typeof window!="undefined"){try{window.dispatchEvent(new CustomEvent(SIDE_PANEL_PUSH_EVENT,{detail:l}))}catch{}const c=(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onSidePanelPushChange;if(typeof c=="function")try{c(t,e,i)}catch(h){console.error("EkaMedAssist.onSidePanelPushChange threw",h)}}}scheduleIdle(t){if(typeof window=="undefined"){t();return}const e=window.requestIdleCallback;typeof e=="function"?e(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode!=="full"&&this.renderLauncher(),t==="display-mode"){const e=normalizeDisplayMode(this.getAttribute("display-mode"));e!==this.displayMode&&(this.displayMode=e,e==="full"?this.initializeFullMode():this.renderLauncher())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles(),t==="launcher-type"&&this.updateLauncherView()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchPromise)return this.authPrefetchPromise;const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);const o=e.authToken||this.getAttribute("auth-token")||void 0,n=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",a=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";return this.authPrefetchPromise=this.loadWidgetModule().then(d=>{var r;return(r=d.prefetchAuth)===null||r===void 0?void 0:r.call(d,{agentId:i,authToken:o,serverUrl:n,environment:a,channel:this.getChannel()})}).catch(()=>{this.authPrefetchPromise=null}),this.authPrefetchPromise}async resolveSessToken(t){const e=readPersistedSessToken(t);if(e)return e;const i=await this.prefetchAuthTokens();return(i==null?void 0:i.sess_token)||readPersistedSessToken(t)}preloadBackgroundImage(){var t;const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=e==null?void 0:e.theme)===null||t===void 0?void 0:t.backgroundImage,n=i==null?void 0:i.backgroundImage;o&&preloadImage(o),n&&n!==o&&preloadImage(n),this.getAgentConfig().then(a=>{var d;const r=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;r&&preloadImage(r)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=e=>{var i;((i=e.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(){if(this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.displayMode==="full")this.initializeFullMode();else if(this.renderLauncher(),this.getLauncherType()==="chatbox")return;this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,e,i,o;const n=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(n==null?void 0:n.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const r=(e=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&e!==void 0?e:"#ffffff",l=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(l)}catch{return}const h=getNudgePathCandidates(c.pathname),m=h.slice(0,1),x=h.slice(1);let p=findFreshCachedNudge(a,c,m);if(!p){const y=(n==null?void 0:n.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",A=await this.resolveSessToken(a).catch(()=>{});if(A){const f=await fetchNudgeData(a,A,y,this.getChannel()).catch(()=>{});!((i=f==null?void 0:f.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(a,f,normalizePath(c.pathname)),p=findFreshCachedNudge(a,c,h))}}if(p||(p=findFreshCachedNudge(a,c,x)),!p)return;const C=p.data.nudges[Math.floor(Math.random()*p.data.nudges.length)],w=(o=p.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(C,r)},w*1e3)}showNudgePopup(t,e){var i,o;const n=this.shadowRoot;if(!n||!(!((i=n.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||n.getElementById("medassist-nudge-popup"))return;const l=this.isChatboxShown()?n.getElementById("medassist-chatbox"):n.getElementById("medassist-open-btn"),c=l==null?void 0:l.getBoundingClientRect(),h=272,m=12,x=8,p=16,C=16;let w=window.innerWidth-h-m,y=76,A=h-p-x*2;if(c&&c.width>0){const b=c.left+c.width/2,g=b-h/2,E=window.innerWidth-h-m;w=Math.max(m,Math.min(g,E)),y=window.innerHeight-c.top+C,A=Math.max(p,Math.min(b-w-x,h-p-x*2))}const f=document.createElement("div");f.id="medassist-nudge-popup",f.innerHTML=`
|
|
13
13
|
<style>
|
|
14
14
|
@keyframes nudge-slide-up {
|
|
15
15
|
from { opacity: 0; transform: translateY(12px) scale(0.97); }
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
}
|
|
18
18
|
#medassist-nudge-popup {
|
|
19
19
|
position: fixed;
|
|
20
|
-
bottom: ${
|
|
21
|
-
left: ${
|
|
20
|
+
bottom: ${y}px;
|
|
21
|
+
left: ${w}px;
|
|
22
22
|
width: ${h}px;
|
|
23
23
|
background: ${e};
|
|
24
24
|
border-radius: 16px;
|
|
@@ -180,7 +180,7 @@
|
|
|
180
180
|
--medassist-chatbox-on-accent: #fafafa;
|
|
181
181
|
--medassist-chatbox-bg: #ffffff;
|
|
182
182
|
--medassist-chatbox-text: #000000;
|
|
183
|
-
--medassist-chatbox-placeholder: #
|
|
183
|
+
--medassist-chatbox-placeholder: #8c8c8c;
|
|
184
184
|
/* Bottom centre. A host moving it to a corner must also reset
|
|
185
185
|
left and translate, e.g. left: auto; right: 20px; translate: none. */
|
|
186
186
|
position: fixed;
|
|
@@ -209,7 +209,7 @@
|
|
|
209
209
|
#medassist-chatbox[data-mode="dark"] {
|
|
210
210
|
--medassist-chatbox-bg: #000000;
|
|
211
211
|
--medassist-chatbox-text: #ffffff;
|
|
212
|
-
--medassist-chatbox-placeholder: #
|
|
212
|
+
--medassist-chatbox-placeholder: #808080;
|
|
213
213
|
}
|
|
214
214
|
#medassist-chatbox.pending {
|
|
215
215
|
display: none !important;
|
|
@@ -460,4 +460,4 @@
|
|
|
460
460
|
}
|
|
461
461
|
</style>
|
|
462
462
|
<div id="medassist-widget-root"></div>
|
|
463
|
-
`)}async loadAndRender(t){var e,i,o,n;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),r=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",h=this.getAttribute("connectivity"),m=h==="http_stream"||h==="socket"?h:void 0,x=this.getAttribute("force-start")==="true";let p=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",
|
|
463
|
+
`)}async loadAndRender(t){var e,i,o,n;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),r=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",h=this.getAttribute("connectivity"),m=h==="http_stream"||h==="socket"?h:void 0,x=this.getAttribute("force-start")==="true";let p=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode"),y=normalizeDisplayMode(w),A=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,f=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,b=this.getAttribute("feedback")?(()=>{try{return JSON.parse(this.getAttribute("feedback")||"{}")}catch{return}})():void 0,g=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=g.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=g.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=g.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),N=u=>{const v=Number(this.getAttribute(u));return Number.isFinite(v)&&v>0?v:void 0},T=N("override-widget-width"),B=N("override-widget-height"),G={...T!==void 0&&{overrideWidgetWidth:T},...B!==void 0&&{overrideWidgetHeight:B}},V={...A||{},...g.context||{}},K=g.authToken||this.getAttribute("auth-token")||void 0,_=g.agentId||r,X=g.baseUrl||C,P=typeof window!="undefined"?(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onClose:void 0,Z=this.getAttribute("redirect-url")||void 0,I=g.redirectUrl||Z,Q=!!I||g.showCloseButton===!0;if(!_){console.error("Agent ID is required");return}if(!d){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),d.classList.remove("hidden");let W,$,z,U=!1,F,O=!1,L;const D=u=>{var v,k,M;p=u.name||p,l=((v=u.theme)===null||v===void 0?void 0:v.icon_img)||l,W=mapAgentConfigThemeToWidgetTheme(u.theme||void 0),$=u.allowed,z=u.connectivity,U=u.resize||(g==null?void 0:g.resize)||!1,F=u.initial_message,O=(M=(k=u.theme)===null||k===void 0?void 0:k.hide_watermark)!==null&&M!==void 0?M:!1,L=u.feedback},H=readAgentConfigCache(_);if(H)D(H),this.getAgentConfig().then(u=>{u&&writeAgentConfigCache(_,u)}).catch(()=>{});else try{const u=await this.getAgentConfig();u&&(writeAgentConfigCache(_,u),D(u))}catch{}const tt=m||z||"socket",q={title:g.title||p,iconUrl:l||g.iconUrl,showCloseButton:Q,allowed:$,environment:c,connectionType:tt,onClose:()=>{var u;if((u=this.reactRoot)===null||u===void 0||u.unmount(),this.reactRoot=null,P&&typeof P=="function"&&P(),I){window.location.href=I;return}y==="full"?this.style.display="none":(this.setLauncherState("idle"),d.classList.add("hidden"))},baseUrl:X,context:V,displayMode:y,sidePanelMode:J,sidePanelWidth:Y,side:j,onSidePanelPushChange:(u,v,k)=>this.applyHostPush(u,v,k),resize:U||this.getAttribute("resize")==="true",authToken:K,force:x,initialMessage:F,hideWatermark:O,...(b||L)&&{feedback:b||L},...t&&{firstUserMessage:t},theme:{...this.isChatboxShown()&&{widgetWidth:520},...W||{},...f||{},...G,...g.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(n=a.getElementById("medassist-chatbox"))===null||n===void 0?void 0:n.getBoundingClientRect():void 0;if(this.widgetLoaded){this.reactRoot=et.renderMedAssist(d,_,q),this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open"),this.loading=!1;return}try{const[,u]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=u.renderMedAssist(d,_,q),this.widgetLoaded=!0,this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open")}catch(u){console.error("Failed to load MedAssist widget",u),this.setLauncherState("idle"),d.classList.add("hidden")}finally{this.loading=!1}}getOpenAnimation(){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},e=this.getAttribute("open-animation")||t.openAnimation;return e==="unfold"||e==="pop"||e==="curtain"||e==="fade"||e==="none"?e:"rise"}async growWidgetFromChatbox(t){var e;try{const i=this.getOpenAnimation();if(i==="none"||prefersReducedMotion())return;const o=this.shadowRoot;let n=null;for(let c=0;c<30&&!n;c++)await nextFrame(),n=(e=o==null?void 0:o.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!n||typeof n.animate!="function")return;const a=n.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,r="50% 100%";if(i==="rise")n.animate([{transform:"translateY(56px) scale(0.96)",opacity:0,transformOrigin:r},{transform:"translateY(0px) scale(1)",opacity:1,transformOrigin:r}],{duration:520,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});else if(i==="pop")n.animate([{transform:"scale(0.4)",opacity:0,transformOrigin:r},{transform:"scale(1.04)",opacity:1,transformOrigin:r,offset:.6},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:560,easing:"cubic-bezier(0.34, 1.2, 0.64, 1)"});else if(i==="curtain")n.animate([{transform:"translateY(20px)",clipPath:`inset(100% 0px 0px 0px round ${d}px)`},{transform:"translateY(0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:560,easing:"cubic-bezier(0.65, 0, 0.35, 1)"});else if(i==="fade"){n.animate([{transform:"scale(0.97)",opacity:0,transformOrigin:r},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:280,easing:"ease-out"});return}else{const c=t.left+t.width/2-(a.left+a.width/2),h=t.bottom-a.bottom,m=Math.max(0,a.height-t.height),x=Math.max(0,(a.width-t.width)/2),p=Math.min(t.height/2,28);n.animate([{transform:`translate(${c}px, ${h}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${p}px)`},{transform:"translate(0px, 0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:620,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}const l=Array.from(n.children).find(c=>c.tagName!=="STYLE");l==null||l.animate([{opacity:0,transform:"translateY(14px)"},{opacity:1,transform:"translateY(0px)"}],{duration:420,delay:140,easing:"cubic-bezier(0.22, 1, 0.36, 1)",fill:"backwards"})}catch{}}getChatboxPlaceholders(){return this.collectChatboxPlaceholders().map(withTrailingEllipsis)}collectChatboxPlaceholders(){var t,e,i;const o=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let n=o.chatboxPlaceholders;if(!Array.isArray(n))try{n=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{n=null}const a=Array.isArray(n)?n.filter(l=>typeof l=="string"&&!!l.trim()):[];if(a.length)return a;const d=o.agentId||this.getAttribute("agent-id")||"",r=l=>Array.isArray(l)?l.filter(c=>typeof c=="string"&&!!c.trim()):[];if(d){try{const c=new URL(window.location.href),h=findFreshCachedNudge(d,c,getNudgePathCandidates(c.pathname)),m=r(h==null?void 0:h.data.nudges);if(m.length)return m}catch{}const l=r((i=(e=(t=readAgentConfigCache(d))===null||t===void 0?void 0:t.initial_message)===null||e===void 0?void 0:e.suggestions)===null||i===void 0?void 0:i.map(c=>c.label||c.value));if(l.length)return l}return["Ask me anything\u2026","Not sure what to ask? Just say hi\u2026","You can type in any language\u2026"]}autosizeChatbox(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;e.style.height="auto";const i=parseFloat(getComputedStyle(e).maxHeight)||92;e.style.height=`${Math.min(e.scrollHeight,i)}px`,e.style.overflowY=e.scrollHeight>i?"auto":"hidden",this.updateChatboxFades()}updateChatboxFades(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");e&&(e.classList.toggle("fade-t",e.scrollTop>1),e.classList.toggle("fade-b",e.scrollHeight-e.clientHeight-e.scrollTop>1))}syncChatboxPulse(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;const o=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",o)}syncChatboxPlaceholder(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph");if(!t||!e)return;const i=t.getElementById("medassist-chatbox-input"),o=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const n=o?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==n&&(e.textContent=n)}startPlaceholderRotation(){this.placeholderTimer||(this.syncChatboxPlaceholder(),!prefersReducedMotion()&&(this.placeholderTimer=setInterval(()=>{const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!t||!e||!i)return;const o=this.getChatboxPlaceholders();o.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%o.length,e.classList.remove("out"),e.classList.add("in"),this.syncChatboxPlaceholder(),e.offsetWidth,e.classList.remove("in")},220))},3500)))}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 e=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=e,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|