@eka-care/medassist-widget-embed 0.2.18 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -37,12 +37,16 @@ declare function mapAgentConfigThemeToWidgetTheme(apiTheme: AgentConfig["theme"]
37
37
  declare function preloadImage(url: string): void;
38
38
  /** Fetch agent-config from API and return theme from response data */
39
39
  declare function fetchAgentConfig(baseUrl: string, agentId: string): Promise<AgentConfig | undefined>;
40
+ type ReactRoot = {
41
+ unmount: () => void;
42
+ };
40
43
  interface EkaMedAssistWindow extends Window {
41
44
  EkaMedAssist?: {
42
45
  init: (config: MedAssistInitConfig) => void;
43
46
  onClose?: () => void;
44
47
  };
45
48
  __ekaMedAssistConfig__?: MedAssistInitConfig;
49
+ renderMedAssist?: (container: HTMLElement, agentId: string, config: MedAssistInitConfig) => ReactRoot;
46
50
  }
47
51
  declare const globalMedAssistConfig: MedAssistInitConfig;
48
52
  declare const getWidgetElement: () => HTMLElement | null;
@@ -58,6 +62,7 @@ declare class MedAssistWidgetLoader extends HTMLElement {
58
62
  private defaultIconUrl;
59
63
  private widgetLoaded;
60
64
  private displayMode;
65
+ private reactRoot;
61
66
  constructor();
62
67
  static get observedAttributes(): string[];
63
68
  connectedCallback(): void;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev")?"https://unpkg.com/@eka-care/medassist-widget@dev/dist/":"https://unpkg.com/@eka-care/medassist-widget@latest/dist/"})();function mapAgentConfigThemeToWidgetTheme(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.title_img&&{titleImg:e.title_img}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const i=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,n=await fetch(i,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!n.ok)return;const o=await n.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var i,n,o;Object.assign(globalMedAssistConfig,t);const d=getWidgetElement();if(d){if(t.agentId&&d.setAttribute("agent-id",t.agentId),t.title&&d.setAttribute("title",t.title),t.iconUrl&&d.setAttribute("icon-url",t.iconUrl),t.baseUrl&&d.setAttribute("base-url",t.baseUrl),t.context)try{d.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(n=d).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 widgetScriptPromise=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{constructor(){super(),this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadWidgetCss().then(()=>this.loadWidgetScript()).then(()=>this.loadAndRender()).catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.preloadWidgetAssets())}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const i=this.getAttribute("display-mode")==="full"?"full":"widget";i!==this.displayMode&&(this.displayMode=i,i==="full"?this.initializeFullMode():this.renderButton())}}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetScript(),this.preloadBackgroundImage()}preloadBackgroundImage(){var t;const i=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,n=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=i==null?void 0:i.theme)===null||t===void 0?void 0:t.backgroundImage,d=n==null?void 0:n.backgroundImage;o&&preloadImage(o),d&&d!==o&&preloadImage(d);const r=(i==null?void 0:i.baseUrl)||this.getAttribute("base-url")||"",a=(i==null?void 0:i.agentId)||this.getAttribute("agent-id")||"";r&&a&&fetchAgentConfig(r,a).then(u=>{var l;const g=(l=u==null?void 0:u.theme)===null||l===void 0?void 0:l.background_img;g&&preloadImage(g)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=i=>{var n;((n=i.data)===null||n===void 0?void 0:n.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadWidgetCss().then(()=>this.loadWidgetScript()).then(()=>this.loadAndRender()).catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}renderButton(){var t;const i=this.getAttribute("icon-url")||this.defaultIconUrl,n=this.shadowRoot;if(!n){console.error("Shadow root was not created");return}if(!n.querySelector("button"))n.innerHTML=`
1
+ "use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const t=document.getElementsByTagName("script");return t.length?t[t.length-1]:null},getEnvironment=e=>{if(e==="production"||e==="development"||e==="staging")return e},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var e;return!((e=scriptEl==null?void 0:scriptEl.src)===null||e===void 0)&&e.includes("@dev")?"https://unpkg.com/@eka-care/medassist-widget@dev/dist/":"https://unpkg.com/@eka-care/medassist-widget@latest/dist/"})();function mapAgentConfigThemeToWidgetTheme(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.title_img&&{titleImg:e.title_img}}}function preloadImage(e){if(!(!e||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=e,document.head.appendChild(t)}catch{const t=new Image;t.src=e}}async function fetchAgentConfig(e,t){const i=`${e.replace(/\/$/,"")}/med-assist/agent-config/${t}`,n=await fetch(i,{headers:{"ngrok-skip-browser-warning":"69420"}});if(!n.ok)return;const o=await n.json();if(o!=null&&o.success&&(o!=null&&o.data))return o.data}const globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const e=window;e.__ekaMedAssistConfig__=globalMedAssistConfig,e.EkaMedAssist={init(t){var i,n,o;Object.assign(globalMedAssistConfig,t);const s=getWidgetElement();if(s){if(t.agentId&&s.setAttribute("agent-id",t.agentId),t.title&&s.setAttribute("title",t.title),t.iconUrl&&s.setAttribute("icon-url",t.iconUrl),t.baseUrl&&s.setAttribute("base-url",t.baseUrl),t.context)try{s.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}!((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 widgetScriptPromise=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{constructor(){super(),this.reactRoot=null,this.attachShadow({mode:"open"}),this.defaultIconUrl="https://cdn.eka.care/bot-icon.svg",this.widgetLoaded=!1,this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadWidgetCss().then(()=>this.loadWidgetScript()).then(()=>this.loadAndRender()).catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderButton(),this.preloadWidgetAssets())}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode==="widget"&&this.renderButton(),t==="display-mode"){const i=this.getAttribute("display-mode")==="full"?"full":"widget";i!==this.displayMode&&(this.displayMode=i,i==="full"?this.initializeFullMode():this.renderButton())}}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetScript(),this.preloadBackgroundImage()}preloadBackgroundImage(){var t;const i=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,n=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=i==null?void 0:i.theme)===null||t===void 0?void 0:t.backgroundImage,s=n==null?void 0:n.backgroundImage;o&&preloadImage(o),s&&s!==o&&preloadImage(s);const r=(i==null?void 0:i.baseUrl)||this.getAttribute("base-url")||"",h=(i==null?void 0:i.agentId)||this.getAttribute("agent-id")||"";r&&h&&fetchAgentConfig(r,h).then(a=>{var u;const c=(u=a==null?void 0:a.theme)===null||u===void 0?void 0:u.background_img;c&&preloadImage(c)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=i=>{var n;((n=i.data)===null||n===void 0?void 0:n.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){this.displayMode=this.getAttribute("display-mode")==="full"?"full":"widget",this.displayMode==="full"?this.initializeFullMode():this.renderButton(),this.loadWidgetCss().then(()=>this.loadWidgetScript()).then(()=>this.loadAndRender()).catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}renderButton(){var t;const i=this.getAttribute("icon-url")||this.defaultIconUrl,n=this.shadowRoot;if(!n){console.error("Shadow root was not created");return}if(!n.querySelector("button"))n.innerHTML=`
2
2
  <style>
3
3
  #medassist-open-btn {
4
4
  width: 60px;
@@ -55,4 +55,4 @@
55
55
  }
56
56
  </style>
57
57
  <div id="medassist-widget-root"></div>
58
- `)}async loadAndRender(){var t,i,n,o;const d=this.shadowRoot;if(!d){console.error("Shadow root is not available");return}const r=d.getElementById("medassist-open-btn"),a=d.getElementById("medassist-widget-root"),u=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||this.defaultIconUrl;const g=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";let f=this.getAttribute("title")||"Medi Clinic";const y=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",A=this.getAttribute("display-mode")==="full"?"full":"widget",k=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,E=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,c=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},_={...k||{},...c.context||{}},x=c.auth||void 0,h=c.agentId||u,m=c.baseUrl||y,w=typeof window!="undefined"?(i=window.EkaMedAssist)===null||i===void 0?void 0:i.onClose:void 0;if(!h){console.error("Agent ID is required");return}if(!a){console.error("Widget root element is missing");return}r&&r.classList.add("hidden"),a.classList.remove("hidden");let p,b;if(m)try{const s=await fetchAgentConfig(m,h);f=(s==null?void 0:s.name)||f,l=((n=s==null?void 0:s.theme)===null||n===void 0?void 0:n.icon_img)||l,p=mapAgentConfigThemeToWidgetTheme((s==null?void 0:s.theme)||void 0),b=s==null?void 0:s.allowed}catch{}const v={title:c.title||f,iconUrl:c.iconUrl||l,allowed:b,environment:g,onClose:()=>{w&&typeof w=="function"&&w(),r&&r.classList.remove("hidden"),a.classList.add("hidden")},baseUrl:m,context:_,displayMode:A,auth:x,theme:{...p||{},...E||{},...c.theme||{}}};if(this.widgetLoaded){(o=window.renderMedAssist)===null||o===void 0||o.call(window,a,h,v);return}try{if(await Promise.all([this.loadWidgetCss(),this.loadWidgetScript()]),typeof window.renderMedAssist!="function")throw new Error("renderMedAssist is not available on window");window.renderMedAssist(a,h,v),this.widgetLoaded=!0}catch(s){console.error("Failed to load MedAssist widget",s),r&&r.classList.remove("hidden"),a.classList.add("hidden")}}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const i=await getWidgetCssTextPromise(),n=document.createElement("style");n.setAttribute("data-medassist-style","true"),n.textContent=i,t.appendChild(n)}loadWidgetScript(){return widgetScriptPromise||(widgetScriptPromise=new Promise((t,i)=>{const n=document.querySelector(`script[src="${WIDGET_JS_URL}"]`);if(n){if(n.dataset.loaded==="true"){t();return}n.addEventListener("load",()=>t()),n.addEventListener("error",d=>i(d.error||new Error("Unknown script loading error")));return}const o=document.createElement("script");o.src=WIDGET_JS_URL,o.async=!0,o.dataset.widget="medassist",o.onload=()=>{o.dataset.loaded="true",t()},o.onerror=d=>{if(d instanceof ErrorEvent&&d.error){i(d.error);return}i(new Error(`Failed to load ${WIDGET_JS_URL}`))},document.head.appendChild(o)})),widgetScriptPromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
58
+ `)}async loadAndRender(){var t,i,n;const o=this.shadowRoot;if(!o){console.error("Shadow root is not available");return}this.style.display="";const s=o.getElementById("medassist-open-btn"),r=o.getElementById("medassist-widget-root"),h=this.getAttribute("agent-id");let a=this.getAttribute("icon-url")||this.defaultIconUrl;const u=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";let c=this.getAttribute("title")||"Medi Clinic";const A=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode")==="full"?"full":"widget",k=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,E=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,l=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},_={...k||{},...l.context||{}},x=l.auth||void 0,g=l.agentId||h,f=l.baseUrl||A,m=typeof window!="undefined"?(i=window.EkaMedAssist)===null||i===void 0?void 0:i.onClose:void 0;if(!g){console.error("Agent ID is required");return}if(!r){console.error("Widget root element is missing");return}s&&s.classList.add("hidden"),r.classList.remove("hidden");let b,v;if(f)try{const d=await fetchAgentConfig(f,g);c=(d==null?void 0:d.name)||c,a=((n=d==null?void 0:d.theme)===null||n===void 0?void 0:n.icon_img)||a,b=mapAgentConfigThemeToWidgetTheme((d==null?void 0:d.theme)||void 0),v=d==null?void 0:d.allowed}catch{}const y={title:l.title||c,iconUrl:l.iconUrl||a,allowed:v,environment:u,onClose:()=>{var d;(d=this.reactRoot)===null||d===void 0||d.unmount(),this.reactRoot=null,m&&typeof m=="function"&&m(),w==="full"?this.style.display="none":(s&&s.classList.remove("hidden"),r.classList.add("hidden"))},baseUrl:f,context:_,displayMode:w,auth:x,theme:{...b||{},...E||{},...l.theme||{}}},p=window;if(this.widgetLoaded){this.reactRoot=p.renderMedAssist(r,g,y);return}try{if(await Promise.all([this.loadWidgetCss(),this.loadWidgetScript()]),typeof p.renderMedAssist!="function")throw new Error("renderMedAssist is not available on window");this.reactRoot=p.renderMedAssist(r,g,y),this.widgetLoaded=!0}catch(d){console.error("Failed to load MedAssist widget",d),s&&s.classList.remove("hidden"),r.classList.add("hidden")}}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const i=await getWidgetCssTextPromise(),n=document.createElement("style");n.setAttribute("data-medassist-style","true"),n.textContent=i,t.appendChild(n)}loadWidgetScript(){return widgetScriptPromise||(widgetScriptPromise=new Promise((t,i)=>{const n=document.querySelector(`script[src="${WIDGET_JS_URL}"]`);if(n){if(n.dataset.loaded==="true"){t();return}n.addEventListener("load",()=>t()),n.addEventListener("error",s=>i(s.error||new Error("Unknown script loading error")));return}const o=document.createElement("script");o.src=WIDGET_JS_URL,o.async=!0,o.dataset.widget="medassist",o.onload=()=>{o.dataset.loaded="true",t()},o.onerror=s=>{if(s instanceof ErrorEvent&&s.error){i(s.error);return}i(new Error(`Failed to load ${WIDGET_JS_URL}`))},document.head.appendChild(o)})),widgetScriptPromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eka-care/medassist-widget-embed",
3
- "version": "0.2.18",
3
+ "version": "0.2.19",
4
4
  "description": "Embeddable MedAssist widget loader built with Web Components.",
5
5
  "author": "Geethanjali S",
6
6
  "license": "MIT",