@eka-care/medassist-widget-embed 0.2.108-dev.0 → 0.2.109
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/README.md +36 -0
- package/dist/eka-agents.html +4 -4
- package/dist/iframe.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -157,6 +157,42 @@ If your viewport-sized root sits inside a wrapper element, the cap does not reac
|
|
|
157
157
|
}
|
|
158
158
|
```
|
|
159
159
|
|
|
160
|
+
### Host analytics events
|
|
161
|
+
|
|
162
|
+
The widget never talks to GTM / gtag / `dataLayer` itself. The host page opts in by defining a global `window.trackWidgetEvent(name, detail)`; the widget calls it and the host forwards whatever it wants to its own analytics stack. Without that function the widget emits nothing. `detail` is `{ sessionId, ...extra }` and carries only non-sensitive identifiers — never message text, user data or phone numbers. `sessionId` is omitted only while a brand-new session is still being created.
|
|
163
|
+
|
|
164
|
+
Define the function before the loader script runs: events fired before it exists are dropped, not queued.
|
|
165
|
+
|
|
166
|
+
#### Startup (per occurrence)
|
|
167
|
+
|
|
168
|
+
| `name` | Extra `detail` | When |
|
|
169
|
+
| --- | --- | --- |
|
|
170
|
+
| `auth_failed` | `{ reason, status? }` | A credential was rejected: token exchange or refresh failed, or the server answered 401/403. `reason` is the SDK recovery reason (`AUTH_EXPIRED`, `SESSION_FORBIDDEN`) or the server's error code. |
|
|
171
|
+
| `session_failed` | `{ reason, status? }` | The session could not be created, resumed or kept: a session API error, or an in-band `session_not_found` / token-mismatch / not-owned error. `reason` is the server's error code, the recovery reason (`SESSION_NOT_FOUND`, `RETRY_LATER`) or the SDK classification. |
|
|
172
|
+
| `connection_failed` | `{ reason, status?, closeCode? }` | The transport could not be reached or dropped: `NETWORK_ERROR` (fetch failed), `timeout` (request timed out), `CONNECTION_ERROR`, or a socket/stream disconnect reason (`network_error`, `server_closed`, `authentication_error`, `timeout`, `max_reconnect_attempts`) with the socket close code. |
|
|
173
|
+
| `connection_established` | `{ elapsedMs }` | The transport is connected. `elapsedMs` is measured from the start of the attempt (the widget's start call, or the disconnect that preceded a reconnect). Fires on every reconnect too. |
|
|
174
|
+
| `ready` | — | Session established and transport connected — the user can send a message. Once per session id. |
|
|
175
|
+
|
|
176
|
+
SDK errors are reported only while the chat is not connected; an error after that (feedback, history, recording) is not a startup failure.
|
|
177
|
+
|
|
178
|
+
#### Engagement (once per session id)
|
|
179
|
+
|
|
180
|
+
| `name` | Extra `detail` | When |
|
|
181
|
+
| --- | --- | --- |
|
|
182
|
+
| `typing_started` | — | First non-empty keystroke in the composer. Voice transcription does not count. |
|
|
183
|
+
| `first_message_sent` | — | The user's first message is sent (Enter or the send button). Not fired when a resumed session already contains a user message. |
|
|
184
|
+
| `first_bot_reply` | `{ messageId }` | The first assistant reply starts rendering. The static greeting does not count, and a resumed session with an earlier reply does not re-fire. |
|
|
185
|
+
|
|
186
|
+
Starting a new chat creates a new session id, so the once-per-session events fire again for it.
|
|
187
|
+
|
|
188
|
+
Event names are snake_case; the host adds its own prefix when forwarding (e.g. `eka_auth_failed`).
|
|
189
|
+
|
|
190
|
+
```js
|
|
191
|
+
window.trackWidgetEvent = (name, detail) => {
|
|
192
|
+
window.dataLayer?.push({ event: `eka_${name}`, ...detail });
|
|
193
|
+
};
|
|
194
|
+
```
|
|
195
|
+
|
|
160
196
|
#### What push cannot move, and the hooks to handle it
|
|
161
197
|
|
|
162
198
|
`position: fixed` elements (sticky headers, banners, `inset: 0` overlays) are positioned against the viewport, so no outside stylesheet can move them. While the panel is open the loader publishes what it did so your own CSS or JS can follow:
|
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.
|
|
21
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.131/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.
|
|
30
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.131/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.
|
|
37
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.131/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.
|
|
152
|
+
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.131/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){if(!e)return;const t=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},...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},...e.consent_content&&{consentContent:e.consent_content},...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.
|
|
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){if(!e)return;const t=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},...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},...e.consent_content&&{consentContent:e.consent_content},...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.131/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 m=null,f=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']")||(f||(f=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 f)}function h(){return m||(m=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)})),m}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.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=Array.from(document.getElementsByTagName("script")),i=t.find(o=>o.hasAttribute("data-widget-assets"));if(i)return i;const n=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return n.length?n[n.length-1]: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.130-dev.0/dist/"})();var FeedbackTypeEnum;(function(e){e.DEFAULT="default",e.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));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},...e.hide_watermark&&{hideWatermark:e.hide_watermark},...e.explicit_disclaimer&&{explicitDisclaimer:e.explicit_disclaimer},...e.consent_content&&{consentContent:e.consent_content},...e.upfront_consent&&{upfrontConsent:e.upfront_consent},...e.feature!==void 0&&{feature:e.feature}}}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}}function channelFromDisplayMode(e){return e==="full"?"web":e==="side_panel"?"side_panel":"widget"}function normalizeDisplayMode(e){return e==="full"?"full":e==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(e){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[e]}catch{return}}function writeAgentConfigCache(e,t){try{const i=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),n=i?JSON.parse(i):{};n[e]={...n[e]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(n))}catch{}}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),i=[];for(let n=t.length;n>=0;n--)i.push(n===0?"/":"/"+t.slice(0,n).join("/"));return i}function findCachedNudgeForCandidates(e,t,i){const o=getNudgeStore()[e];if(!o)return null;const s=t.host,r=o[s];if(!r)return null;for(const d of i){if(r[d]!==void 0)return{domain:s,path:d,data:r[d]};const a=d==="/"?"/*":d+"/*";if(r[a]!==void 0)return{domain:s,path:a,data:r[a]}}return null}function findFreshCachedNudge(e,t,i){const n=findCachedNudgeForCandidates(e,t,i);if(!n)return null;const o=Math.floor(Date.now()/1e3);return n.data.expiry<=o?(clearNudgeForPath(e,n.domain,n.path),null):n}function clearNudgeForPath(e,t,i){const n=getNudgeStore(),o=n[e];!o||!o[t]||(delete o[t][i],setNudgeStore(n))}function storeNudgeResponse(e,t,i){var n,o,s,r;const d=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,a=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((s=t.nudges)===null||s===void 0)&&s.length)||!t.expiry||!d||!a)return;const c=getNudgeStore();c[e]||(c[e]={}),c[e][d]||(c[e][d]={});const h={nudges:t.nudges,expiry:t.expiry,delay:(r=t.delay)!==null&&r!==void 0?r:5};c[e][d][a]=h,i&&i!==a&&(c[e][d][i]=h),setNudgeStore(c)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const i=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${i}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const i=t.split("=")[1];return i==="open"||i==="closed"?i:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(e){var t,i;try{const n=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${e}`),o=n?(i=(t=JSON.parse(n))===null||t===void 0?void 0:t.state)===null||i===void 0?void 0:i.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(e,t,i,n="widget"){const o=`${i}/med-assist/user-nudge`,s=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(r=>{var d,a,c;const h=(d=r.getAttribute("name"))!==null&&d!==void 0?d:void 0,f=(a=r.getAttribute("property"))!==null&&a!==void 0?a:void 0,p=(c=r.getAttribute("content"))!==null&&c!==void 0?c:void 0;(h||f)&&s.push({name:h,property:f,content:p})});try{const r=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,"x-channel":n,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:s,url:typeof window!="undefined"?window.location.href:""})});return r.ok?await r.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 e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var i,n,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"||t.displayMode==="side_panel")&&s.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&s.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&s.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&s.setAttribute("side",t.side),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),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(n=s).openFromBridge)===null||o===void 0||o.call(n)}}}}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{setLauncherState(t){var i;const n=(i=this.shadowRoot)===null||i===void 0?void 0:i.getElementById("medassist-open-btn");n&&(n.classList.toggle("loading",t==="loading"),n.classList.toggle("hidden",t==="open"),t==="loading"?n.setAttribute("aria-busy","true"):n.removeAttribute("aria-busy"))}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const i=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(i==null?void 0:i.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=i.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=i.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const s=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(r=>{var d;return(d=r.fetchAgentConfig)===null||d===void 0?void 0:d.call(r,{agentId:o,serverUrl:n,environment:s,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.authPrefetchPromise=null,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",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"]}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.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,i,n,o,s;(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(i=document.body)===null||i===void 0||i.classList.remove("eka-medassist-pushed"),(n=document.documentElement)===null||n===void 0||n.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(s=this.hostPushStyleEl)===null||s===void 0||s.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,i,n){var o;if(typeof document=="undefined")return;const s=t?{width:i,side:n}:null,r=this.hostPushState;if(r===s||r&&s&&r.width===s.width&&r.side===s.side)return;this.hostPushState=s,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=n==="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:e}=document;if(e instanceof HTMLScriptElement)return e;const t=Array.from(document.getElementsByTagName("script")),i=t.find(o=>o.hasAttribute("data-widget-assets"));if(i)return i;const n=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return n.length?n[n.length-1]: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.131/dist/"})();var FeedbackTypeEnum;(function(e){e.DEFAULT="default",e.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));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},...e.hide_watermark&&{hideWatermark:e.hide_watermark},...e.explicit_disclaimer&&{explicitDisclaimer:e.explicit_disclaimer},...e.consent_content&&{consentContent:e.consent_content},...e.upfront_consent&&{upfrontConsent:e.upfront_consent},...e.feature!==void 0&&{feature:e.feature}}}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}}function channelFromDisplayMode(e){return e==="full"?"web":e==="side_panel"?"side_panel":"widget"}function normalizeDisplayMode(e){return e==="full"?"full":e==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(e){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[e]}catch{return}}function writeAgentConfigCache(e,t){try{const i=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),n=i?JSON.parse(i):{};n[e]={...n[e]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(n))}catch{}}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),i=[];for(let n=t.length;n>=0;n--)i.push(n===0?"/":"/"+t.slice(0,n).join("/"));return i}function findCachedNudgeForCandidates(e,t,i){const o=getNudgeStore()[e];if(!o)return null;const s=t.host,r=o[s];if(!r)return null;for(const d of i){if(r[d]!==void 0)return{domain:s,path:d,data:r[d]};const a=d==="/"?"/*":d+"/*";if(r[a]!==void 0)return{domain:s,path:a,data:r[a]}}return null}function findFreshCachedNudge(e,t,i){const n=findCachedNudgeForCandidates(e,t,i);if(!n)return null;const o=Math.floor(Date.now()/1e3);return n.data.expiry<=o?(clearNudgeForPath(e,n.domain,n.path),null):n}function clearNudgeForPath(e,t,i){const n=getNudgeStore(),o=n[e];!o||!o[t]||(delete o[t][i],setNudgeStore(n))}function storeNudgeResponse(e,t,i){var n,o,s,r;const d=(n=t==null?void 0:t.url_pattern)===null||n===void 0?void 0:n.domain,a=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((s=t.nudges)===null||s===void 0)&&s.length)||!t.expiry||!d||!a)return;const c=getNudgeStore();c[e]||(c[e]={}),c[e][d]||(c[e][d]={});const h={nudges:t.nudges,expiry:t.expiry,delay:(r=t.delay)!==null&&r!==void 0?r:5};c[e][d][a]=h,i&&i!==a&&(c[e][d][i]=h),setNudgeStore(c)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(e,t){const i=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${e}=${t}; expires=${i}; path=/; SameSite=Lax`}function getNudgeCookie(e){const t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${NUDGE_COOKIE_PREFIX}-${e}=`));if(!t)return null;const i=t.split("=")[1];return i==="open"||i==="closed"?i:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(e){var t,i;try{const n=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${e}`),o=n?(i=(t=JSON.parse(n))===null||t===void 0?void 0:t.state)===null||i===void 0?void 0:i.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(e,t,i,n="widget"){const o=`${i}/med-assist/user-nudge`,s=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(r=>{var d,a,c;const h=(d=r.getAttribute("name"))!==null&&d!==void 0?d:void 0,f=(a=r.getAttribute("property"))!==null&&a!==void 0?a:void 0,p=(c=r.getAttribute("content"))!==null&&c!==void 0?c:void 0;(h||f)&&s.push({name:h,property:f,content:p})});try{const r=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":e,"x-channel":n,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:s,url:typeof window!="undefined"?window.location.href:""})});return r.ok?await r.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 e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var i,n,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"||t.displayMode==="side_panel")&&s.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&s.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&s.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&s.setAttribute("side",t.side),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),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(n=s).openFromBridge)===null||o===void 0||o.call(n)}}}}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{setLauncherState(t){var i;const n=(i=this.shadowRoot)===null||i===void 0?void 0:i.getElementById("medassist-open-btn");n&&(n.classList.toggle("loading",t==="loading"),n.classList.toggle("hidden",t==="open"),t==="loading"?n.setAttribute("aria-busy","true"):n.removeAttribute("aria-busy"))}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const i=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(i==null?void 0:i.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},n=i.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=i.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const s=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(r=>{var d;return(d=r.fetchAgentConfig)===null||d===void 0?void 0:d.call(r,{agentId:o,serverUrl:n,environment:s,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.authPrefetchPromise=null,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",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"]}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.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,i,n,o,s;(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(i=document.body)===null||i===void 0||i.classList.remove("eka-medassist-pushed"),(n=document.documentElement)===null||n===void 0||n.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(s=this.hostPushStyleEl)===null||s===void 0||s.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,i,n){var o;if(typeof document=="undefined")return;const s=t?{width:i,side:n}:null,r=this.hostPushState;if(r===s||r&&s&&r.width===s.width&&r.side===s.side)return;this.hostPushState=s,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=n==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
2
2
|
body.eka-medassist-pushed {
|
|
3
3
|
${d}: ${i}px;
|
|
4
4
|
transition: margin 300ms ease;
|