@eka-care/medassist-widget-embed 0.2.119 → 0.2.120

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 CHANGED
@@ -234,6 +234,49 @@ window.addEventListener("eka-medassist:side-panel-push", (e) => {
234
234
  });
235
235
  ```
236
236
 
237
+ ## Client tools
238
+
239
+ Give the agent functions that run **in your page** (read or edit your app's state). The page declares them; the backend tells the LLM they exist; when the LLM calls one, the SDK runs your `run` and sends the result back. Declarations follow MCP's `Tool` shape; only `name / description / inputSchema / outputSchema / annotations` leave the page — `run` never does.
240
+
241
+ ```js
242
+ EkaMedAssist.init({
243
+ agentId: "<agent-id>",
244
+ tools: [
245
+ {
246
+ name: "read_note",
247
+ description: "Read the note the user has open.",
248
+ inputSchema: { type: "object", properties: { section_keys: { type: "array", items: { type: "string" } } } },
249
+ annotations: { title: "Reading the note", readOnlyHint: true },
250
+ run: async (input, ctx) => {
251
+ ctx.progress({ message: "Collecting sections…" });
252
+ return { sections: getSections(input.section_keys) }; // plain object → structured result
253
+ },
254
+ },
255
+ ],
256
+ });
257
+
258
+ // Replace the list at any time (before or after the widget opens):
259
+ EkaMedAssist.registerTools([...]);
260
+ ```
261
+
262
+ Rules:
263
+
264
+ - `run` must read live page state at call time — tools are registered once and reused.
265
+ - Return a plain object (becomes `structuredContent`) or a full MCP `CallToolResult`.
266
+ - Report a failure the model should handle by throwing an `Error` with `code` (string) and optional `data` (object); it becomes `{ isError: true, structuredContent: { code, message, ...data } }`.
267
+ - `annotations.title` is the label shown on the reply bubble while the tool runs; `ctx.progress({ message })` updates it live.
268
+ - `ctx.signal` aborts on timeout (`timeoutMs`, default 30 s), server cancel, or session end.
269
+ - Not supported in the iframe embed (functions cannot cross frames).
270
+ - Needs widget `0.2.x` (the React-SDK build). The legacy `0.1.x` widget ignores `tools`.
271
+
272
+ Protocol details: `docs/client-tools-plan.md` in the repo. Demo: `test-client-tools.html`.
273
+
274
+ ## Environments
275
+
276
+ The SDK ships with the production backend only. The `environment` attribute / `init({ environment })` is kept for
277
+ backward compatibility but any value other than `production` is ignored; point at another backend with `base-url` /
278
+ `init({ baseUrl })`.
279
+
237
280
  ## How it works
238
281
 
239
282
  1. **Initial load** – The script registers the custom element `<eka-medassist-widget>`.
@@ -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/dist/medassist-widget.js"
21
+ href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/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/dist/medassist-widget.css"
30
+ href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/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/dist/medassist-widget.css"
37
+ href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/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/dist/medassist-widget.js"
152
+ src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/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/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)}})();
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.2.0-dev.1/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
@@ -69,7 +69,38 @@ type AgentConfig = {
69
69
  /** Client-side flag set when the user clicks "Don't show again" on the feedback modal. */
70
70
  feedback_hidden?: boolean;
71
71
  };
72
+ /**
73
+ * Host-page function the LLM may call (MCP `Tool` declaration + `run`).
74
+ * Declared structurally — the loader is built without a bundler and cannot
75
+ * import the SDK. Kept in memory only, never serialised to an attribute.
76
+ */
77
+ type MedAssistClientTool = {
78
+ name: string;
79
+ description: string;
80
+ inputSchema: Record<string, unknown>;
81
+ outputSchema?: Record<string, unknown>;
82
+ annotations?: {
83
+ title?: string;
84
+ readOnlyHint?: boolean;
85
+ destructiveHint?: boolean;
86
+ idempotentHint?: boolean;
87
+ };
88
+ run: (input: Record<string, unknown>, ctx: {
89
+ requestId: string | number;
90
+ messageId?: string;
91
+ signal: AbortSignal;
92
+ progress: (update: {
93
+ message: string;
94
+ progress?: number;
95
+ total?: number;
96
+ }) => void;
97
+ }) => unknown;
98
+ parse?: (input: unknown) => Record<string, unknown>;
99
+ timeoutMs?: number;
100
+ };
72
101
  type MedAssistInitConfig = {
102
+ /** Client tools the LLM may call; replace later with `EkaMedAssist.registerTools()`. Not available in iframe mode. */
103
+ tools?: MedAssistClientTool[];
73
104
  /** Partner JWT/JWE — the only host-supplied credential; absent -> guest. */
74
105
  authToken?: string;
75
106
  agentId?: string;
@@ -229,6 +260,8 @@ type SidePanelPushDetail = {
229
260
  interface EkaMedAssistWindow extends Window {
230
261
  EkaMedAssist?: {
231
262
  init: (config: MedAssistInitConfig) => void;
263
+ /** Replace the client tools — before or after the widget renders. */
264
+ registerTools: (tools: MedAssistClientTool[]) => void;
232
265
  onClose?: () => void;
233
266
  /**
234
267
  * Side-panel push mode only. Called with `true` when the panel opens and
@@ -241,6 +274,8 @@ interface EkaMedAssistWindow extends Window {
241
274
  };
242
275
  __ekaMedAssistConfig__?: MedAssistInitConfig;
243
276
  renderMedAssist?: (container: HTMLElement, agentId: string, config: MedAssistInitConfig) => ReactRoot;
277
+ /** Exposed by the widget bundle once loaded; swaps tools in the running SDK. */
278
+ registerMedAssistTools?: (tools: MedAssistClientTool[]) => void;
244
279
  }
245
280
  declare const globalMedAssistConfig: MedAssistInitConfig;
246
281
  declare const getWidgetElement: () => HTMLElement | null;
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/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=`
1
+ "use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:n}=document;if(n instanceof HTMLScriptElement)return n;const t=Array.from(document.getElementsByTagName("script")),e=t.find(s=>s.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(s=>/(^|\/)index\.js(\?.*)?$/.test(s.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=n=>{if(n==="production"||n==="development"||n==="staging")return n},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var n;return!((n=scriptEl==null?void 0:scriptEl.src)===null||n===void 0)&&n.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.1/dist/"})();var FeedbackTypeEnum;(function(n){n.DEFAULT="default",n.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(n){var t;if(!n)return;const e=n.mode==="dark"?"white":n.mode==="light"?"black":void 0;return{...n.background_img&&{backgroundImage:n.background_img},...n.accent&&{primary:n.accent},...e&&{textColor:e},...n.mode&&{mode:n.mode},...n.header_tinted!==void 0&&{headerTinted:n.header_tinted},...n.title_img&&{titleImg:n.title_img},...n.tagline&&{tagline:n.tagline},...n.hide_watermark&&{hideWatermark:n.hide_watermark},...n.explicit_disclaimer&&{explicitDisclaimer:n.explicit_disclaimer},...n.consent_content&&{consentContent:n.consent_content},...n.upfront_consent&&{upfrontConsent:n.upfront_consent},...((t=n.tips)===null||t===void 0?void 0:t.length)&&{tips:n.tips},...n.feature!==void 0&&{feature:n.feature},...typeof n.widget_width=="number"&&{widgetWidth:n.widget_width},...typeof n.widget_height=="number"&&{widgetHeight:n.widget_height}}}function preloadImage(n){if(!(!n||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=n,document.head.appendChild(t)}catch{const t=new Image;t.src=n}}function channelFromDisplayMode(n){return n==="full"?"web":n==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var n;return typeof window!="undefined"&&!!(!((n=window.matchMedia)===null||n===void 0)&&n.call(window,"(prefers-reduced-motion: reduce)").matches)}function nextFrame(){return new Promise(n=>requestAnimationFrame(()=>n()))}function colorOnAccent(n){const t=n.trim().replace("#",""),e=t.length===3?t.split("").map(o=>o+o).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(o=>parseInt(e.slice(o,o+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(n){return n==="full"?"full":n==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(n){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[n]}catch{return}}function writeAgentConfigCache(n,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[n]={...i[n]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const n=localStorage.getItem(NUDGE_STORAGE_KEY);return n?JSON.parse(n):{}}catch{return{}}}function setNudgeStore(n){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(n))}catch{}}function normalizePath(n){let t=n.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(n){const t=n.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(n,t,e){const s=getNudgeStore()[n];if(!s)return null;const o=t.host,a=s[o];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:o,path:d,data:a[d]};const r=d==="/"?"/*":d+"/*";if(a[r]!==void 0)return{domain:o,path:r,data:a[r]}}return null}function findFreshCachedNudge(n,t,e){const i=findCachedNudgeForCandidates(n,t,e);if(!i)return null;const s=Math.floor(Date.now()/1e3);return i.data.expiry<=s?(clearNudgeForPath(n,i.domain,i.path),null):i}function clearNudgeForPath(n,t,e){const i=getNudgeStore(),s=i[n];!s||!s[t]||(delete s[t][e],setNudgeStore(i))}function storeNudgeResponse(n,t,e){var i,s,o,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,r=(s=t==null?void 0:t.url_pattern)===null||s===void 0?void 0:s.path;if(!(!((o=t.nudges)===null||o===void 0)&&o.length)||!t.expiry||!d||!r)return;const l=getNudgeStore();l[n]||(l[n]={}),l[n][d]||(l[n][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};l[n][d][r]=c,e&&e!==r&&(l[n][d][e]=c),setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(n,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${n}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(n){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${n}=`));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(n){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${n}`),s=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 s=="string"&&s?s:void 0}catch{return}}async function fetchNudgeData(n,t,e,i="widget"){const s=`${e}/med-assist/user-nudge`,o=[];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)&&o.push({name:c,property:h,content:m})});try{const a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":n,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:o,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(n){const t=n.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 n=window;n.__ekaMedAssistConfig__=globalMedAssistConfig,n.EkaMedAssist={registerTools(t){var e;globalMedAssistConfig.tools=t,(e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t)},init(t){var e,i,s,o;Object.assign(globalMedAssistConfig,t),t.tools&&((e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t.tools));const a=getWidgetElement();if(a){if(t.agentId&&a.setAttribute("agent-id",t.agentId),t.authToken&&a.setAttribute("auth-token",t.authToken),t.title&&a.setAttribute("title",t.title),t.iconUrl&&a.setAttribute("icon-url",t.iconUrl),t.baseUrl&&a.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&a.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&a.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&a.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&a.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&a.setAttribute("side",t.side),t.context)try{a.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&a.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&a.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&a.setAttribute("redirect-url",t.redirectUrl),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(s=a).openFromBridge)===null||o===void 0||o.call(s)}}}}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 n=scriptEl.dataset.widgetAssets;if(n==="local")return`${scriptBaseUrl}src/`;if(n&&n.length>0)try{return new URL(n,scriptBaseUrl).href}catch{return n.endsWith("/")?n:`${n}/`}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(n=>{if(!n.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return n.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)||{},s=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(s?(e=(t=readAgentConfigCache(s))===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(),s=t.getElementById("medassist-open-btn");if(s){const a=e==="loading"&&!i;s.classList.toggle("loading",a),s.classList.toggle("hidden",e==="open"||i),a?s.setAttribute("aria-busy","true"):s.removeAttribute("aria-busy")}const o=t.getElementById("medassist-chatbox");if(o){this.applyChatboxTheme(o);const a=e==="loading"&&i;o.classList.toggle("hidden",e==="open"||!i),o.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";o.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=o.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",s=e.agentId||this.getAttribute("agent-id")||"";if(!s)return Promise.resolve(void 0);const o=(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:s,serverUrl:i,environment:o,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,s,o;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"),(s=document.documentElement)===null||s===void 0||s.style.removeProperty("--eka-medassist-panel-side"),(o=this.hostPushStyleEl)===null||o===void 0||o.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var s;if(typeof document=="undefined")return;const o=t?{width:e,side:i}:null,a=this.hostPushState;if(a===o||a&&o&&a.width===o.width&&a.side===o.side)return;this.hostPushState=o,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 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=`
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=(s=window.EkaMedAssist)===null||s===void 0?void 0:s.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 s=e.authToken||this.getAttribute("auth-token")||void 0,o=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:s,serverUrl:o,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,s=(t=e==null?void 0:e.theme)===null||t===void 0?void 0:t.backgroundImage,o=i==null?void 0:i.backgroundImage;s&&preloadImage(s),o&&o!==s&&preloadImage(o),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,s;const o=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(o==null?void 0:o.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 g=findFreshCachedNudge(a,c,m);if(!g){const y=(o==null?void 0:o.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)),g=findFreshCachedNudge(a,c,h))}}if(g||(g=findFreshCachedNudge(a,c,x)),!g)return;const C=g.data.nudges[Math.floor(Math.random()*g.data.nudges.length)],w=(s=g.data.delay)!==null&&s!==void 0?s:5;setTimeout(()=>{this.showNudgePopup(C,r)},w*1e3)}showNudgePopup(t,e){var i,s;const o=this.shadowRoot;if(!o||!(!((i=o.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||o.getElementById("medassist-nudge-popup"))return;const l=this.isChatboxShown()?o.getElementById("medassist-chatbox"):o.getElementById("medassist-open-btn"),c=l==null?void 0:l.getBoundingClientRect(),h=272,m=12,x=8,g=16,C=16;let w=window.innerWidth-h-m,y=76,A=h-g-x*2;if(c&&c.width>0){const b=c.left+c.width/2,p=b-h/2,E=window.innerWidth-h-m;w=Math.max(m,Math.min(p,E)),y=window.innerHeight-c.top+C,A=Math.max(g,Math.min(b-w-x,h-g-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); }
@@ -90,7 +90,7 @@
90
90
  <p class="nudge-text">${t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}</p>
91
91
  <button class="nudge-close" aria-label="Dismiss">&#x2715;</button>
92
92
  </div>
93
- `,(o=f.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",b=>{b.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),f.addEventListener("click",()=>{var b;if(d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.isChatboxShown()){(b=n.getElementById("medassist-chatbox-input"))===null||b===void 0||b.focus();return}this.loadAndRender()}),n.appendChild(f)}dismissNudgePopup(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");e==null||e.remove()}applyCustomLauncherStyles(){var t,e,i,o;const n=this.shadowRoot;if(!n||this.displayMode==="full")return;const a=this.getAgentId(),d=(i=a?(e=(t=readAgentConfigCache(a))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_styles:void 0)!==null&&i!==void 0?i:"";this.setLauncherStyleTag("data-medassist-config-launcher",d);const r=n.querySelector('style[data-medassist-custom-launcher="true"]'),l=(o=this.getAttribute("custom-launcher-styles"))!==null&&o!==void 0?o:"";if(!l){r==null||r.remove();return}if(r){r.textContent=l;return}const c=document.createElement("style");c.setAttribute("data-medassist-custom-launcher","true"),c.textContent=l,n.appendChild(c)}setLauncherStyleTag(t,e){const i=this.shadowRoot;if(!i)return;const o=i.querySelector(`style[${t}="true"]`);if(!e){o==null||o.remove();return}if(o){o.textContent=e;return}const n=document.createElement("style");n.setAttribute(t,"true"),n.textContent=e;const a=i.querySelector('style[data-medassist-custom-launcher="true"]');i.insertBefore(n,a)}getAgentId(){return((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||""}async renderLauncher(){var t,e;if(this.displayMode==="full")return;const i=++this.launcherRenderSeq;this.renderButton();const o=this.getAttribute("icon-url");if(o){this.setLauncherIcon(o);const r=this.getAgentId();r&&this.scheduleIdle(()=>{this.getAgentConfig().then(l=>{!l||i!==this.launcherRenderSeq||(writeAgentConfigCache(r,l),this.updateLauncherView())})});return}const n=this.getAgentId();if(!n)return;const a=(e=(t=readAgentConfigCache(n))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.icon_img;a&&this.setLauncherIcon(a);const d=async()=>{var r;const l=await this.getAgentConfig().catch(()=>{});i===this.launcherRenderSeq&&(l&&writeAgentConfigCache(n,l),this.setLauncherIcon(((r=l==null?void 0:l.theme)===null||r===void 0?void 0:r.icon_img)||a))};a?this.scheduleIdle(()=>{d()}):await d()}setLauncherIcon(t){var e,i;const o=this.shadowRoot;if(!o)return;const n=o.querySelector("#medassist-open-btn img");n&&(t?n.src=t:n.removeAttribute("src")),(e=o.getElementById("medassist-open-btn"))===null||e===void 0||e.classList.remove("pending"),(i=o.getElementById("medassist-chatbox"))===null||i===void 0||i.classList.remove("pending"),this.updateLauncherView()}applyChatboxTheme(t){var e;const i=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).theme;let o;try{o=JSON.parse(this.getAttribute("theme")||"{}")}catch{o=void 0}const n=this.getAgentId(),a=n?(e=readAgentConfigCache(n))===null||e===void 0?void 0:e.theme:void 0,d=(i==null?void 0:i.primary)||(o==null?void 0:o.primary)||(a==null?void 0:a.accent);d&&(t.style.setProperty("--medassist-chatbox-accent",d),t.style.setProperty("--medassist-chatbox-on-accent",colorOnAccent(d))),((i==null?void 0:i.mode)||(o==null?void 0:o.mode)||(a==null?void 0:a.mode))==="dark"?t.setAttribute("data-mode","dark"):t.removeAttribute("data-mode")}renderButton(){var t;const e=this.shadowRoot;if(!e){console.error("Shadow root was not created");return}if(!e.querySelector("button")){e.innerHTML=`
93
+ `,(s=f.querySelector(".nudge-close"))===null||s===void 0||s.addEventListener("click",b=>{b.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),f.addEventListener("click",()=>{var b;if(d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.isChatboxShown()){(b=o.getElementById("medassist-chatbox-input"))===null||b===void 0||b.focus();return}this.loadAndRender()}),o.appendChild(f)}dismissNudgePopup(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");e==null||e.remove()}applyCustomLauncherStyles(){var t,e,i,s;const o=this.shadowRoot;if(!o||this.displayMode==="full")return;const a=this.getAgentId(),d=(i=a?(e=(t=readAgentConfigCache(a))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_styles:void 0)!==null&&i!==void 0?i:"";this.setLauncherStyleTag("data-medassist-config-launcher",d);const r=o.querySelector('style[data-medassist-custom-launcher="true"]'),l=(s=this.getAttribute("custom-launcher-styles"))!==null&&s!==void 0?s:"";if(!l){r==null||r.remove();return}if(r){r.textContent=l;return}const c=document.createElement("style");c.setAttribute("data-medassist-custom-launcher","true"),c.textContent=l,o.appendChild(c)}setLauncherStyleTag(t,e){const i=this.shadowRoot;if(!i)return;const s=i.querySelector(`style[${t}="true"]`);if(!e){s==null||s.remove();return}if(s){s.textContent=e;return}const o=document.createElement("style");o.setAttribute(t,"true"),o.textContent=e;const a=i.querySelector('style[data-medassist-custom-launcher="true"]');i.insertBefore(o,a)}getAgentId(){return((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||""}async renderLauncher(){var t,e;if(this.displayMode==="full")return;const i=++this.launcherRenderSeq;this.renderButton();const s=this.getAttribute("icon-url");if(s){this.setLauncherIcon(s);const r=this.getAgentId();r&&this.scheduleIdle(()=>{this.getAgentConfig().then(l=>{!l||i!==this.launcherRenderSeq||(writeAgentConfigCache(r,l),this.updateLauncherView())})});return}const o=this.getAgentId();if(!o)return;const a=(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.icon_img;a&&this.setLauncherIcon(a);const d=async()=>{var r;const l=await this.getAgentConfig().catch(()=>{});i===this.launcherRenderSeq&&(l&&writeAgentConfigCache(o,l),this.setLauncherIcon(((r=l==null?void 0:l.theme)===null||r===void 0?void 0:r.icon_img)||a))};a?this.scheduleIdle(()=>{d()}):await d()}setLauncherIcon(t){var e,i;const s=this.shadowRoot;if(!s)return;const o=s.querySelector("#medassist-open-btn img");o&&(t?o.src=t:o.removeAttribute("src")),(e=s.getElementById("medassist-open-btn"))===null||e===void 0||e.classList.remove("pending"),(i=s.getElementById("medassist-chatbox"))===null||i===void 0||i.classList.remove("pending"),this.updateLauncherView()}applyChatboxTheme(t){var e;const i=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).theme;let s;try{s=JSON.parse(this.getAttribute("theme")||"{}")}catch{s=void 0}const o=this.getAgentId(),a=o?(e=readAgentConfigCache(o))===null||e===void 0?void 0:e.theme:void 0,d=(i==null?void 0:i.primary)||(s==null?void 0:s.primary)||(a==null?void 0:a.accent);d&&(t.style.setProperty("--medassist-chatbox-accent",d),t.style.setProperty("--medassist-chatbox-on-accent",colorOnAccent(d))),((i==null?void 0:i.mode)||(s==null?void 0:s.mode)||(a==null?void 0:a.mode))==="dark"?t.setAttribute("data-mode","dark"):t.removeAttribute("data-mode")}renderButton(){var t;const e=this.shadowRoot;if(!e){console.error("Shadow root was not created");return}if(!e.querySelector("button")){e.innerHTML=`
94
94
  <style>
95
95
  #medassist-open-btn {
96
96
  width: 60px;
@@ -443,7 +443,7 @@
443
443
  </button>
444
444
  </form>
445
445
  <div id="medassist-widget-root" class="hidden"></div>
446
- `,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let o=!1;const n=e.querySelector(".medassist-chatbox-send");i==null||i.addEventListener("input",()=>{n&&(n.disabled=!i.value.trim()),this.syncChatboxPlaceholder(),this.syncChatboxPulse(),this.autosizeChatbox(),!o&&(o=!0,this.preloadWidgetAssets(),this.prefetchAuthTokens())});const a=e.getElementById("medassist-chatbox"),d=()=>{if(!this.chatStarted||this.loading||this.launcherState!=="idle")return!1;const r=this.getAgentId();return r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender(),!0};a==null||a.addEventListener("click",r=>{d()&&r.preventDefault()}),i==null||i.addEventListener("scroll",()=>this.updateChatboxFades()),i==null||i.addEventListener("keydown",r=>{r.key!=="Enter"||r.shiftKey||r.isComposing||(r.preventDefault(),!d()&&i.value.trim()&&(a==null||a.requestSubmit()))}),this.startPlaceholderRotation(),a==null||a.addEventListener("submit",r=>{r.preventDefault();const l=i==null?void 0:i.value.trim();if(!l&&d()||!l||this.loading)return;const c=this.getAgentId();c&&setNudgeCookie(c,"closed"),this.dismissNudgePopup(),this.loadAndRender(l)})}this.applyCustomLauncherStyles()}initializeFullMode(){const t=this.shadowRoot;if(!t){console.error("Shadow root is not available");return}t.getElementById("medassist-widget-root")||(t.innerHTML=`
446
+ `,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let s=!1;const o=e.querySelector(".medassist-chatbox-send");i==null||i.addEventListener("input",()=>{o&&(o.disabled=!i.value.trim()),this.syncChatboxPlaceholder(),this.syncChatboxPulse(),this.autosizeChatbox(),!s&&(s=!0,this.preloadWidgetAssets(),this.prefetchAuthTokens())});const a=e.getElementById("medassist-chatbox"),d=()=>{if(!this.chatStarted||this.loading||this.launcherState!=="idle")return!1;const r=this.getAgentId();return r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender(),!0};a==null||a.addEventListener("click",r=>{d()&&r.preventDefault()}),i==null||i.addEventListener("scroll",()=>this.updateChatboxFades()),i==null||i.addEventListener("keydown",r=>{r.key!=="Enter"||r.shiftKey||r.isComposing||(r.preventDefault(),!d()&&i.value.trim()&&(a==null||a.requestSubmit()))}),this.startPlaceholderRotation(),a==null||a.addEventListener("submit",r=>{r.preventDefault();const l=i==null?void 0:i.value.trim();if(!l&&d()||!l||this.loading)return;const c=this.getAgentId();c&&setNudgeCookie(c,"closed"),this.dismissNudgePopup(),this.loadAndRender(l)})}this.applyCustomLauncherStyles()}initializeFullMode(){const t=this.shadowRoot;if(!t){console.error("Shadow root is not available");return}t.getElementById("medassist-widget-root")||(t.innerHTML=`
447
447
  <style>
448
448
  :host {
449
449
  display: block;
@@ -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",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);
463
+ `)}async loadAndRender(t){var e,i,s,o;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 g=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,p=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=p.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=p.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=p.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),T=u=>{const v=Number(this.getAttribute(u));return Number.isFinite(v)&&v>0?v:void 0},N=T("override-widget-width"),B=T("override-widget-height"),G={...N!==void 0&&{overrideWidgetWidth:N},...B!==void 0&&{overrideWidgetHeight:B}},V={...A||{},...p.context||{}},K=p.authToken||this.getAttribute("auth-token")||void 0,_=p.agentId||r,X=p.baseUrl||C,P=typeof window!="undefined"?(s=window.EkaMedAssist)===null||s===void 0?void 0:s.onClose:void 0,Z=this.getAttribute("redirect-url")||void 0,I=p.redirectUrl||Z,Q=!!I||p.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;g=u.name||g,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||(p==null?void 0:p.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:p.title||g,iconUrl:l||p.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,...p.tools&&{tools:p.tools},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,...p.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(o=a.getElementById("medassist-chatbox"))===null||o===void 0?void 0:o.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 s=this.shadowRoot;let o=null;for(let c=0;c<30&&!o;c++)await nextFrame(),o=(e=s==null?void 0:s.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!o||typeof o.animate!="function")return;const a=o.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,r="50% 100%";if(i==="rise")o.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")o.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")o.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"){o.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),g=Math.min(t.height/2,28);o.animate([{transform:`translate(${c}px, ${h}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${g}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(o.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 s=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let o=s.chatboxPlaceholders;if(!Array.isArray(o))try{o=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{o=null}const a=Array.isArray(o)?o.filter(l=>typeof l=="string"&&!!l.trim()):[];if(a.length)return a;const d=s.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 s=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",s)}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"),s=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const o=s?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==o&&(e.textContent=o)}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 s=this.getChatboxPlaceholders();s.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%s.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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eka-care/medassist-widget-embed",
3
- "version": "0.2.119",
3
+ "version": "0.2.120",
4
4
  "description": "Embeddable MedAssist widget loader built with Web Components.",
5
5
  "author": "Geethanjali S",
6
6
  "license": "MIT",