@metricinsights/concierge
Version:
Metric Insights Concierge Component
12 lines (11 loc) • 34.7 kB
JavaScript
import e,{createContext as t,useState as s,useCallback as r,useContext as n,useRef as i,useEffect as a,useMemo as o}from"react";import c from"katex";import l from"markdown-it";import d,{Element as u,attributesToProps as h,domToReact as m}from"html-react-parser";import{marked as p}from"marked";import g from"clsx";var f,b={exports:{}},y={};var k,v={};
/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/"production"===process.env.NODE_ENV?b.exports=function x(){if(f)return y;f=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(t,s,r){var n=null;if(void 0!==r&&(n=""+r),void 0!==s.key&&(n=""+s.key),"key"in s)for(var i in r={},s)"key"!==i&&(r[i]=s[i]);else r=s;return s=r.ref,{$$typeof:e,type:t,key:n,ref:void 0!==s?s:null,props:r}}return y.Fragment=t,y.jsx=s,y.jsxs=s,y}():b.exports=function w(){return k||(k=1,"production"!==process.env.NODE_ENV&&function(){function t(e){if(null==e)return null;if("function"==typeof e)return e.$$typeof===_?null:e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case m:return"Fragment";case g:return"Profiler";case p:return"StrictMode";case k:return"Suspense";case x:return"SuspenseList";case j:return"Activity"}if("object"==typeof e)switch("number"==typeof e.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case h:return"Portal";case b:return(e.displayName||"Context")+".Provider";case f:return(e._context.displayName||"Context")+".Consumer";case y:var s=e.render;return(e=e.displayName)||(e=""!==(e=s.displayName||s.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case w:return null!==(s=e.displayName||null)?s:t(e.type)||"Memo";case R:s=e._payload,e=e._init;try{return t(e(s))}catch(e){}}return null}function s(e){return""+e}function r(e){try{s(e);var t=!1}catch(e){t=!0}if(t){var r=(t=console).error,n="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n),s(e)}}function n(e){if(e===m)return"<>";if("object"==typeof e&&null!==e&&e.$$typeof===R)return"<...>";try{var s=t(e);return s?"<"+s+">":"<...>"}catch(e){return"<...>"}}function i(){return Error("react-stack-top-frame")}function a(){var e=t(this.type);return A[e]||(A[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(e=this.props.ref)?e:null}function o(e,s,n,i,o,d,h,m){var p=s.children;if(void 0!==p)if(i)if(T(p)){for(i=0;i<p.length;i++)c(p[i]);Object.freeze&&Object.freeze(p)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else c(p);if(S.call(s,"key")){p=t(e);var g=Object.keys(s).filter((function(e){return"key"!==e}));i=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",N[p+i]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',i,p,g,p),N[p+i]=!0)}if(p=null,void 0!==n&&(r(n),p=""+n),function f(e){if(S.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(s)&&(r(s.key),p=""+s.key),"key"in s)for(var b in n={},s)"key"!==b&&(n[b]=s[b]);else n=s;return p&&function y(e,t){function s(){l||(l=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}s.isReactWarning=!0,Object.defineProperty(e,"key",{get:s,configurable:!0})}(n,"function"==typeof e?e.displayName||e.name||"Unknown":e),function v(e,t,s,r,n,i,o,c){return s=i.ref,e={$$typeof:u,type:e,key:t,props:i,_owner:n},null!==(void 0!==s?s:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:a}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:o}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:c}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(e,p,d,0,function k(){var e=E.A;return null===e?null:e.getOwner()}(),n,h,m)}function c(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var l,d=e,u=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),p=Symbol.for("react.strict_mode"),g=Symbol.for("react.profiler"),f=Symbol.for("react.consumer"),b=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),k=Symbol.for("react.suspense"),x=Symbol.for("react.suspense_list"),w=Symbol.for("react.memo"),R=Symbol.for("react.lazy"),j=Symbol.for("react.activity"),_=Symbol.for("react.client.reference"),E=d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,S=Object.prototype.hasOwnProperty,T=Array.isArray,I=console.createTask?console.createTask:function(){return null},A={},O=(d={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(d,i)(),M=I(n(i)),N={};v.Fragment=m,v.jsx=function(e,t,s,r,i){var a=1e4>E.recentlyCreatedOwnerStacks++;return o(e,t,s,!1,0,i,a?Error("react-stack-top-frame"):O,a?I(n(e)):M)},v.jsxs=function(e,t,s,r,i){var a=1e4>E.recentlyCreatedOwnerStacks++;return o(e,t,s,!0,0,i,a?Error("react-stack-top-frame"):O,a?I(n(e)):M)}}()),v}();var R=b.exports;const j=t(void 0),_=({children:e,defaultOpen:t=!1,defaultTheme:n="light",defaultPosition:i="bottom-right"})=>{const[a,o]=s(t),[c,l]=s(n),[d,u]=s(i),[h,m]=s(""),p={isOpen:a,toggleOpen:r((()=>{o((e=>!e))}),[]),close:r((()=>{o(!1)}),[]),open:r((()=>{o(!0)}),[]),theme:c,setTheme:l,position:d,setPosition:u,inputValue:h,setInputValue:m};return R.jsx(j.Provider,{value:p,children:e})},E=()=>{const e=n(j);if(!e)throw new Error("useUIContext must be used within a UIProvider");return e},S=t(void 0),T=({children:e,defaultMessages:t=[]})=>{const[n,i]=s(t),a=r(((e,t,s,r)=>{const n={id:e,content:t,blocks:r,timestamp:new Date,type:s};return i((e=>[...e,n])),n.id}),[]),o=r(((e,t)=>{a((new Date).getTime().toString(),e,t)}),[a]),c=r(((e,t)=>{i((s=>s.map((s=>s.id===e?{...s,...t}:s))))}),[]),l=r((()=>{i([])}),[]),d=r((e=>{i((t=>t.filter((t=>t.id!==e))))}),[]),u={messages:n,addMessage:a,addMessageWrapper:o,clearMessages:l,updateMessage:c,removeMessage:d};return R.jsx(S.Provider,{value:u,children:e})},I=()=>{const e=n(S);if(!e)throw new Error("useMessageContext must be used within a MessageProvider");return e},A=t(void 0),O={click:{},focus:{},blur:{},mouseenter:{},mouseleave:{},keydown:{},keyup:{}},M=({children:e})=>{const[t,n]=s(O),i=r(((e,s,r,n)=>{const i=e.type,a=t[i]?.[s];a&&a(e,r,n)}),[t]),a=r(((e,t)=>{const s=e.target,r=e.type,n=s.closest(`[data-on${r}-action]`);if(n){const s=n.getAttribute(`data-on${r}-action`),a=Object.fromEntries(Array.from(n.attributes).filter((e=>e.name.startsWith(`data-on${r}-`)&&!e.name.includes("-action"))).map((e=>[e.name.replace(`data-on${r}-`,""),e.value])));s&&i(e,s,a,t)}}),[i]),o=r(((e,t,s)=>{n((r=>({...r,[e]:{...r[e],[t]:s}})))}),[]),c=r(((e,t)=>{n((s=>{const r={...s};return delete r[e]?.[t],0===Object.keys(r[e]||{}).length&&delete r[e],r}))}),[]),l={handleEvent:a,handleAction:i,registerAction:o,unregisterAction:c};return R.jsx(A.Provider,{value:l,children:e})},N=()=>{const e=n(A);if(!e)throw new Error("useActionContext must be used within an ActionProvider");return e};class P{}class C extends Error{constructor(e){super(e),this.name="ParserRegistrationError"}}class $ extends P{constructor(e){super(),this.id="html",this.START_MARKER="%BEGIN_HTML%",this.END_MARKER="%END_HTML%",this.ALLOW_JS_IN_RESPONSE=!1,this.ALLOW_JS_IN_RESPONSE=e?.allowJsInResponse??!1}canParse(e,t){return e.slice(t,t+this.START_MARKER.length)===this.START_MARKER}parse(e,t){t+=this.START_MARKER.length;let s="",r=e.indexOf(this.END_MARKER,t);if(-1===r)return{result:null,newIndex:t};s=e.slice(t,r).trim();const n=t-this.START_MARKER.length;t=r+this.END_MARKER.length;const i=this.START_MARKER+s+this.END_MARKER;return this.ALLOW_JS_IN_RESPONSE||(s=s.replace(/<script[^>]*>([\s\S]*?)<\/script>/g,'<div style="display: none;">$1</div>')),(s.includes("action-badge")||s.includes("data-template"))&&(s.trim().startsWith("<div")||(s=`<div>${s}</div>`)),{result:{type:"html",content:s,startIndex:n,endIndex:t,raw:i},newIndex:t}}}class L extends P{constructor(){super(...arguments),this.id="latex",this.START_MARKER="\\[",this.END_MARKER="\\]",this.START_MARKER_1="$$",this.CODE_BLOCK_START="```",this.currentMarker=this.START_MARKER}canParse(e,t){if(e.startsWith(this.START_MARKER,t)){return(e.slice(0,t).match(new RegExp(this.CODE_BLOCK_START,"g"))||[]).length%2!=1}if(e.startsWith(this.START_MARKER_1,t)&&(e.slice(0,t).match(new RegExp(this.START_MARKER_1))?.length??0)%2==1){return(e.slice(0,t).match(new RegExp(this.CODE_BLOCK_START,"g"))||[]).length%2!=1&&(this.currentMarker=this.START_MARKER_1,!0)}return!1}parse(e,t){let s=this.currentMarker,r=this.currentMarker===this.START_MARKER_1?this.START_MARKER_1:this.END_MARKER;const n=t;t+=s.length;let i=e.indexOf(r,t);if(-1===i)return{result:null,newIndex:t};let a=e.slice(t,i).trim().replace(/^(\\\[)\s+/,"$1").replace(/\s+(\\\])?$/,"$1");t=i+r.length;const o=a.replace(/(?<!\\)(?:\\\\)*([%&])/g,"\\$1");return{result:{type:"latex",content:c.renderToString(o,{throwOnError:!1,displayMode:!0,maxSize:50}),startIndex:n,endIndex:t,raw:s+a+r},newIndex:t}}}class D extends P{constructor(e){if(super(),this.id="markdown",this.md=e?.mdInstance??new l(e?.mdOptions??{}),(e?.allowLatex??1)&&(this.md.inline.ruler.before("escape","inline_latex",((e,t)=>{const s=e.pos,r=e.posMax;if("$"===e.src[s]){let n=s+1,i=!1;for(;n<r;)if("\\\\"!==e.src.slice(n,n+2)){if("$"===e.src.slice(n,n+1)&&!i){const r=e.src.slice(s+1,n);if(!t){e.push("inline_latex","",0).content=r}return e.pos=n+1,!0}i=!1,n++}else i=!i,n+=2}if("\\("===e.src.slice(s,s+2)){let n=s+2,i=!1;for(;n<r;)if("\\\\"!==e.src.slice(n,n+2)){if("\\)"===e.src.slice(n,n+2)&&!i){const r=e.src.slice(s+2,n);if(!t){e.push("inline_latex","",0).content=r}return e.pos=n+2,!0}i=!1,n++}else i=!i,n+=2}return!1})),this.md.renderer.rules.inline_latex=(e,t,s,r,n)=>{try{return`<span class="inline-latex">${c.renderToString(e[t].content,{throwOnError:!1,displayMode:!1})}</span>`}catch{return n.renderToken(e,t,s)}}),e?.linkAttributes){const t=e.linkAttributes,s=/\/element\/\d+(\/segment\/\d+)?/i;this.md.renderer.rules.link_open=(e,r,n,i,a)=>{const o=e[r];if(s.test(o.attrGet("href")??"")&&o.attrJoin("class","element-link"),Object.keys(t).length>0)for(const[e,s]of Object.entries(t))"class"===e?o.attrJoin("class",s):o.attrSet(e,s);return a.renderToken(e,r,n)}}}canParse(e,t){return!0}parse(e,t){const s=t,r=e.slice(t),n=e.length;return{result:r.trim()?{type:"markdown",content:this.md.render(r),startIndex:s,endIndex:n,raw:r}:null,newIndex:n}}}class H extends P{constructor(e={}){super(),this.id="element",this.END_MARKER=" ";const t={linkify:!0,typographer:!0,html:!0,...e?.mdOptions};if(this.md=e?.mdInstance??new l(t),e?.linkAttributes){const t=e.linkAttributes,s=/\/element\/\d+(\/segment\/\d+)?/i;this.md.renderer.rules.link_open=(e,r,n,i,a)=>{const o=e[r];if(s.test(o.attrGet("href")??"")&&o.attrJoin("class","element-link"),Object.keys(t).length>0)for(const[e,s]of Object.entries(t))"class"===e?o.attrJoin("class",s):o.attrSet(e,s);return a.renderToken(e,r,n)}}}canParse(e,t){if("["!==e[t])return!1;if(0!==t&&"\n"!==e[t-1])return!1;const s=e.indexOf("](",t);if(-1===s)return!1;const r=s+2,n=e.indexOf(")",r);if(-1===n)return!1;const i=e.substring(r,n);return!!/element\/\d+(\/segment\/\d+)?/i.test(i)&&-1!==e.indexOf(this.END_MARKER,n)}parse(e,t){if(!this.canParse(e,t))return{result:null,newIndex:t};const s=t,r=e.indexOf(this.END_MARKER,t);if(-1===r)return{result:null,newIndex:t};const n=r+this.END_MARKER.length,i=e.substring(s,n),a=`<div class="element-content">${this.md.render(i)}</div>`;return{result:{type:this.id,content:a,startIndex:s,endIndex:n,raw:i},newIndex:n}}}class K{constructor(){this.parsers=new Map,this.register(new $,{priority:3}),this.register(new L,{priority:2}),this.register(new H,{priority:1}),this.register(new D({linkAttributes:{target:"__blank"}}),{priority:0})}isRegistered(e){return this.parsers.has(e.id)}canOverrideParser(e,t){return t instanceof e.constructor}getParserById(e){return this.parsers.get(e)?.parser}register(e,t={},s=!1){const r=this.parsers.get(e.id);if(r){if(!s)throw new C(`Parser with id '${e.id}' is already registered`);if(!this.canOverrideParser(r.parser,e))throw new C(`Parser with id '${e.id}' cannot be overridden by the provided parser`)}const n={priority:0,enabled:!0,...t};this.parsers.set(e.id,{parser:e,config:n})}unregister(e){if(!this.isRegistered(e))throw new C(`Parser with id '${e.id}' is not registered`);const t=this.parsers.get(e.id);t&&this.parsers.set(e.id,{...t,config:{...t.config,enabled:!1}})}setParserEnabled(e,t){if(!this.isRegistered(e))throw new C(`Parser with id '${e.id}' is not registered`);const s=this.parsers.get(e.id);s&&this.parsers.set(e.id,{...s,config:{...s.config,enabled:t}})}getOrderedParsers(){return Array.from(this.parsers.values()).filter((e=>e.config.enabled)).sort(((e,t)=>(t.config.priority??0)-(e.config.priority??0))).map((e=>e.parser))}getAllParsers(){return Array.from(this.parsers.values()).map((e=>e.parser))}getParserConfig(e){if(!this.isRegistered(e))throw new C(`Parser with id '${e.id}' is not registered`);return this.parsers.get(e.id).config}setParserConfig(e,t){if(!this.isRegistered(e))throw new C(`Parser with id '${e.id}' is not registered`);this.parsers.get(e.id).config=t}parse(e){const t=[],s=[],r=this.getOrderedParsers(),n=Array.from(this.parsers.values()).filter((e=>e.config.enabled)).sort(((e,t)=>(e.config.priority??0)-(t.config.priority??0)))[0]?.parser;for(const i of r){if(i===n)continue;let r=0;for(;r<e.length;)if(i.canParse(e,r)){const{result:n,newIndex:a}=i.parse(e,r);if(n){s.some((e=>n.startIndex>=e.start&&n.startIndex<e.end||n.endIndex>e.start&&n.endIndex<=e.end||n.startIndex<=e.start&&n.endIndex>=e.end))||(t.push(n),s.push({start:n.startIndex,end:n.endIndex})),r=a}else r++}else r++}if(s.sort(((e,t)=>e.start-t.start)),n){let r=0;for(const i of s){if(i.start>r){const s=e.slice(r,i.start);if(s.trim()){const{result:e}=n.parse(s,0);e&&t.push({...e,startIndex:r,endIndex:i.start})}}r=i.end}if(r<e.length){const s=e.slice(r);if(s.trim()){const{result:i}=n.parse(s,0);i&&t.push({...i,startIndex:r,endIndex:e.length})}}}return t.sort(((e,t)=>e.startIndex-t.startIndex))}}const q={"Content-Type":"application/json",Accept:"application/json"};class B{constructor(e){this._token=null,this.tokenRefreshInterval=null,this.lastRequestTimestamp=null;e={useStreaming:!0,headers:{"Content-Type":"application/json",Accept:"application/json"},...e},this.baseUrl="/ai/api/v1/concierge",this.headers={...q,...e?.headers},this.useStreaming=e?.useStreaming??!0,this.conversationTimestamp=Date.now(),this.contentParser=e?.contentParser??new K}destroy(){this.tokenRefreshInterval&&clearInterval(this.tokenRefreshInterval)}set token(e){this._token=e,this.tokenRefreshInterval&&clearInterval(this.tokenRefreshInterval),this.token.ttl&&(this.tokenRefreshInterval=setInterval((()=>this.refreshToken()),(this.token.ttl??300)/2*1e3))}get token(){if(!this._token)throw new Error("Token not initialized");return this._token}async getToken(){const e=await fetch("/api/get_token",{headers:this.headers}),t=await e.json();this.token={access_token:t.token,token_type:"legacy",ttl:300}}async refreshToken(){try{const e=Date.now();if(this.lastRequestTimestamp&&e-this.lastRequestTimestamp>12e5)return void(this.tokenRefreshInterval&&(clearInterval(this.tokenRefreshInterval),this.tokenRefreshInterval=null));await this.getToken()}catch(e){console.error("Failed to refresh token:",e),this.tokenRefreshInterval&&(clearInterval(this.tokenRefreshInterval),this.tokenRefreshInterval=null)}}buildHeaders(e){const t={...this.headers,...e};return this._token&&("access-token"===this._token.token_type?t.Authorization=`Bearer ${this._token.access_token}`:"legacy"===this._token.token_type&&(t.Token=`${this._token.access_token}`)),t}buildSearchParams(e,t){const s=new URLSearchParams;return s.set("q",encodeURIComponent(e)),s.set("conversation_ts",this.conversationTimestamp.toString()),this.useStreaming&&s.set("stream","1"),!1===t?.stream&&s.delete("stream"),s.toString()}async makeRequest(e){this.lastRequestTimestamp=Date.now(),this._token||await this.getToken();const t=this.buildHeaders(),s=await fetch(`${this.baseUrl}?${this.buildSearchParams(e)}`,{headers:t});if(!s.ok)throw console.error("[Request] Request failed:",s.status,s.statusText),new Error(`HTTP error! status: ${s.status}`);if(!s.body)throw console.error("[Request] Response body is null"),new Error("Response body is null");const r=s.headers.get("start-time"),n=s.headers.get("concierge-message-id");r&&(this.conversationTimestamp=Number(r));const i=await s.text(),a=this.parseStreamingBlocks(i,r??void 0,n??void 0);return{messageId:n,data:i,conversation_ts:r,blocks:a,raw:i}}async loadAdditionalContent(e){this.lastRequestTimestamp=Date.now(),this._token||await this.getToken();const t=await fetch(e,{headers:this.buildHeaders()});if(!t.ok)throw console.error("[Load more] Request failed:",t.status,t.statusText),new Error(`HTTP error! status: ${t.status}`);if(!t.body)throw console.error("[Load more] Response body is null"),new Error("Response body is null");const s=t.headers.get("start-time"),r=t.headers.get("concierge-message-id");s&&(this.conversationTimestamp=Number(s));const n=await t.text(),i=this.parseStreamingBlocks(n,s??void 0,r??void 0);return{messageId:r,data:n,conversation_ts:s,blocks:i,raw:n}}parseStreamingBlocks(e,t,s){const r=[];if(e.trim()){const n=this.contentParser.parse(e);for(const e in n){const i=n[e];i.startIndex+=0,i.endIndex+=0,"html"===i.type&&(i.content=i.content.replace("%BADGE_ID%",`ts_${t}_${s}_${e}`)),r.push(i)}}return r}async makeStreamingRequest(e,t){this.lastRequestTimestamp=Date.now(),this._token||await this.getToken();const s=this.buildHeaders(),r=await fetch(`${this.baseUrl}?${this.buildSearchParams(e)}`,{headers:s,signal:t});if(!r.ok)throw console.error("[Request] Request failed:",r.status,r.statusText),new Error(`HTTP error! status: ${r.status}`);if(!r.body)throw console.error("[Request] Response body is null"),new Error("Response body is null");const n=r.headers.get("start-time"),i=r.headers.get("concierge-message-id");n&&(this.conversationTimestamp=Number(n));const a=r.body.getReader(),o=new TextDecoder,c=this;return{messageId:i,conversation_ts:n,[Symbol.asyncIterator]:async function*(){let e="",t=[];try{for(;;){const{done:s,value:r}=await a.read();if(s){e.trim()&&(t=c.parseStreamingBlocks(e,n??void 0,i??void 0),t.length>0&&(yield{messageId:i,data:e,conversation_ts:n,blocks:t,raw:e}));break}const l=o.decode(r,{stream:!0});e+=l;const d=c.parseStreamingBlocks(e,n??void 0,i??void 0);d.length>0&&(t=d,yield{messageId:i,data:l,conversation_ts:n,blocks:d,raw:e})}}finally{a.releaseLock()}}.bind(this)}}async makeStreamingRequestXHR(e){this.lastRequestTimestamp=Date.now(),this._token||await this.getToken();const t=this.buildHeaders({Accept:"text/event-stream"});return new Promise(((s,r)=>{const n=new XMLHttpRequest,i=`${this.baseUrl}?${this.buildSearchParams(e)}`;let a=null,o="",c=[];n.open("GET",i,!0),Object.entries(t).forEach((([e,t])=>{n.setRequestHeader(e,t)})),n.responseType="text",n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.HEADERS_RECEIVED){a=n.getResponseHeader("concierge-message-id");const e=n.getResponseHeader("start-time");e&&(this.conversationTimestamp=Number(e))}},n.onprogress=e=>{if(e.target.responseText,n.readyState===XMLHttpRequest.LOADING){const e=n.responseText.slice(o.length);o+=e;const t=this.parseStreamingBlocks(o,n.getResponseHeader("start-time")??void 0,a??void 0);t.length>0&&(c=t)}},n.onload=()=>{n.status>=200&&n.status<300?o.trim()&&(c=this.parseStreamingBlocks(o,n.getResponseHeader("start-time")??void 0,a??void 0)):(console.error("[Streaming] Request failed:",n.status,n.statusText),r(new Error(`HTTP error! status: ${n.status}`)))},n.onerror=()=>{console.error("[Streaming] Network error occurred"),r(new Error("Network error occurred"))},n.send(),s({messageId:a,async*[Symbol.asyncIterator](){for(;n.readyState!==XMLHttpRequest.DONE;){if(c.length>0){const e=[...c];c=[],yield{data:"",conversation_ts:n.getResponseHeader("start-time")??void 0,message_id:a,blocks:e,raw:o}}await new Promise((e=>setTimeout(e,100)))}c.length>0&&(yield{data:o,conversation_ts:n.getResponseHeader("start-time")??void 0,message_id:a,blocks:c,raw:o})}})}))}resetConversationTimestamp(){this.conversationTimestamp=Date.now()}}const F=t(void 0),z=({children:e,apiOptions:t})=>{const[n,o]=s(new B(t)),[c,l]=s(!1),[d,u]=s(null),{addMessage:h,updateMessage:m,removeMessage:p}=I(),g=i(null);a((()=>(o(new B(t)),()=>{n&&n.destroy()})),[t]);const f=r((()=>{g.current&&(g.current.abort(),g.current=null,l(!1),u("Request cancelled"))}),[]),b=r((async e=>{try{if(!n)throw new Error("API not initialized");f(),g.current=new AbortController,l(!0),u(null),h((new Date).getTime().toString(),e,"user");const t=await n.makeStreamingRequest(e,g.current.signal);let s=h(t.messageId??(new Date).getTime().toString(),"","assistant");for await(const e of t){if(g.current?.signal.aborted)break;t.messageId&&t.messageId!==s&&(p(s),s=h(t.messageId,"","assistant")),e.blocks&&e.blocks.length>0&&m(s,{blocks:e.blocks})}}catch(e){e instanceof Error&&"AbortError"===e.name?console.log("Request was cancelled"):(console.error("Error sending message:",e),u("Failed to send message"))}finally{l(!1),g.current=null}}),[n,h,m,p,f]),y={api:n,isLoading:c,setIsLoading:l,error:d,setError:u,sendMessage:b,cancelRequest:f};return R.jsx(F.Provider,{value:y,children:e})},U=()=>{const e=n(F);if(!e)throw new Error("useAPIContext must be used within an APIProvider");return e};function V(e){const t=p.lexer(e).filter((e=>"space"!==e.type)),s={name:"",link:"",elementId:"",segmentId:"0",description:"",customFields:{}};if("paragraph"===t[0]?.type&&t[0].tokens){const e=t[0].tokens.find((e=>"link"===e.type));if(e){s.link=e.href;const t=e.tokens?.find((e=>"strong"===e.type));t&&(s.name=t.text);const r=e.href.match(/\/element\/(\d+)/i),n=e.href.match(/\/segment\/(\d+)/i);r&&(s.elementId=r[1]),n&&(s.segmentId=n[1])}const r=t[0].tokens.find((e=>"text"===e.type&&!e.text.includes("[")));r&&(s.description=r.text.trim())}if("paragraph"===t[1]?.type&&t[1].tokens){let e="",r="";if(t[1]?.tokens&&t[1].tokens.filter((e=>"space"===e.type)).every(((e,t)=>t%2!=0||"strong"===e.type))){for(const n of t[1].tokens)"strong"===n.type?(e&&r&&(s.customFields[e]=r.trim()),e=n.text.replace(":","").trim(),r=""):"text"===n.type&&(r+=n.text.replace(/^:/,"").trim());e&&r&&(s.customFields[e]=r.trim())}else{const e=t[1].tokens.filter((e=>"text"===e.type)).map((e=>e.text)).join("").split("\n");for(const t of e){const e=t.match(/^([^:]+):\s*(.+)$/);if(e){const[,t,r]=e;s.customFields[t.trim()]=r.trim()}}}}return s}const J=({href:e,children:t,...s})=>R.jsx("a",{href:e,className:"mi-element-link",...s,children:t}),W=(e,t)=>{if(e instanceof u&&"a"===e.name&&e.attribs?.class?.includes("mi-element-link")){const{href:s,children:r,...n}=e.attribs,i=h(n,e.name);return R.jsx(J,{href:s,...i,onClick:e=>e.preventDefault(),children:m(e.children,t)})}return e},X=({markdown:e,className:t,onClick:s,onElementLinkClick:r,...n})=>{const i=V(e);return R.jsxs("div",{className:g("mi-element",t),onClick:s,...n,children:[i.link&&R.jsx(J,{href:i.link,onClick:r,children:i.name}),R.jsx("p",{children:i.description}),Object.entries(i.customFields).length>0&&R.jsx("div",{className:"custom-fields",children:Object.entries(i.customFields).map((([e,t])=>R.jsxs("div",{className:"custom-field",children:[R.jsxs("strong",{children:[e,":"]})," ",t]},e)))}),R.jsx("p",{children:" "})]})},G=({isLoading:e,disabled:t,onStop:s})=>R.jsx("button",{type:e?"button":"submit",onClick:e?e=>{e.preventDefault(),s?.()}:void 0,disabled:t,className:"concierge-send-button",children:e?R.jsxs(R.Fragment,{children:[R.jsx("div",{className:"concierge-loading-spinner"}),R.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"concierge-stop-icon",children:R.jsx("rect",{x:"4",y:"4",width:"16",height:"16",fill:"currentColor"})})]}):R.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:R.jsx("path",{d:"M2.01 21L23 12L2.01 3L2 10L17 12L2 14L2.01 21Z",fill:"currentColor"})})}),Z=t(void 0),Y=()=>{const e=E(),t=I(),s=N(),n=U(),i=r((()=>{t.clearMessages(),n.api.resetConversationTimestamp(),e.setInputValue("")}),[t,n,e]);return{...e,...t,...s,...n,startNewChat:i}},Q=({onSend:e,onStop:t,placeholder:s="Type your message...",disabled:r=!1})=>{const{isLoading:n,inputValue:i,setInputValue:a}=Y();return R.jsxs("form",{onSubmit:async t=>{if(t.preventDefault(),i.trim()&&!n)try{await e(i),a("")}catch(e){console.error("Error sending message:",e)}},className:"concierge-input-container",children:[R.jsx("input",{type:"text",value:i,onChange:e=>a(e.target.value),placeholder:s,disabled:r||n,className:"concierge-input"}),R.jsx(G,{isLoading:n,disabled:!i.trim()&&!n||r,onStop:t})]})},ee=({className:e=""})=>R.jsxs("div",{className:`concierge-loading ${e}`,children:[R.jsx("div",{className:"concierge-loading-spinner"}),R.jsx("span",{children:"Loading..."})]}),te=(e,t)=>{if(!e||"object"!=typeof e||!("name"in e))return!1;const s=(e=>{let t="",s="",r="";const n={},i=e.match(/^([a-zA-Z0-9]+)/);i&&(t=i[1]);const a=e.match(/#([a-zA-Z0-9_-]+)/);a&&(r=a[1]);const o=e.match(/\.([a-zA-Z0-9_-]+)/g);o&&(s=o.map((e=>e.substring(1))).join(" "));const c=e.match(/\[([^\]]+)\]/g);return c&&c.forEach((e=>{const[t,s]=e.slice(1,-1).split("=");t&&s&&(n[t]=s.replace(/['"]/g,""))})),{tag:t,className:s,id:r,attributes:n}})(t),r=e;if(s.tag&&s.tag.toLowerCase()!==r.name.toLowerCase())return!1;if(s.id&&r.attribs?.id!==s.id)return!1;if(s.className){const e=r.attribs?.class?.split(" ")||[];if(!s.className.split(" ").every((t=>e.includes(t))))return!1}if(Object.keys(s.attributes).length>0)for(const[e,t]of Object.entries(s.attributes))if(!r.attribs||r.attribs[e]!==t)return!1;return!0},se={"a.element-link":W},re=(e,t,s)=>{const r={...se,...s},n={replace:e=>{if(r)for(const[t,s]of Object.entries(r))if(te(e,t)){return s(e,n)}return e},transform(e,s){const{key:r,...n}=t||{};if(n&&Object.keys(n).length>0&&"object"==typeof e)for(const[t,s]of Object.entries(n))e[t]=s;return e}};return d(e,n)},ne=t(void 0),ie=({children:t,defaultReplacers:s={}})=>{const[r,n]=e.useState(s),i={replacers:r,addReplacer:e.useCallback(((e,t)=>{n((s=>({...s,[e]:t})))}),[]),removeReplacer:e.useCallback((e=>{n((t=>{const{[e]:s,...r}=t;return r}))}),[]),clearReplacers:e.useCallback((()=>{n({})}),[])};return R.jsx(ne.Provider,{value:i,children:t})},ae=()=>{const e=n(ne);if(!e)throw new Error("useMessageReplacer must be used within a MessageReplacerProvider");return e},oe=({message:t,components:s,onEvent:r,onMessageBlock:n})=>{const{replacers:i}=ae();return R.jsxs("div",{className:`message ${t.type}`,children:[t.blocks&&t.blocks.length>0?R.jsx("div",{className:"message-blocks",onClick:e=>r(e,t),children:t.blocks.map(((r,a)=>{const o=s[r.type.charAt(0).toUpperCase()+r.type.slice(1)];return n&&n(t,r),o?R.jsx(o,{block:r,message:t},`${r.type}-${a}`):R.jsx(e.Fragment,{children:re(r.content,{},{"a.element-link":(e,t)=>{if(e instanceof u&&"a"===e.name&&e.attribs?.class?.includes("element-link"))return R.jsx(J,{href:e.attribs.href,...e.attribs,"data-onclick-action":"elementLinkClick",children:m(e.children,t)})},...i})},`${r.type}-${a}`)}))}):R.jsx("div",{className:"message-content",children:re(t.content,{},{...i})}),R.jsx("div",{className:"message-timestamp",children:t.timestamp.toLocaleTimeString()})]})},ce=({messages:e,components:t,onEvent:s,onMessageBlock:r,autoScroll:n=!0,className:o})=>{const c=i(null),l=i(null),d=i(new Set),u=()=>{c.current&&!!l.current&&l.current.scrollHeight>l.current.clientHeight&&n&&c.current.scrollIntoView({behavior:"smooth"})};return a((()=>{u()}),[e]),a((()=>{0===e.length&&d.current.clear()}),[e.length]),R.jsxs("div",{className:`concierge-messages only-one-badge ${o}`,ref:l,children:[e.map((e=>R.jsx(oe,{message:e,components:t,onEvent:s,onMessageBlock:r},e.id))),R.jsx("div",{ref:c})]})},le=({className:e="",ariaLabel:t,children:s})=>{const{isOpen:r,toggleOpen:n,position:i}=E();return R.jsx("button",{className:`concierge-toggle ${i} ${e}`,onClick:n,"aria-label":t||(r?"Close Concierge":"Open Concierge"),"aria-expanded":r,type:"button",children:s||R.jsx(R.Fragment,{children:r?R.jsx("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"currentColor","aria-hidden":"true",children:R.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}):R.jsx("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"currentColor","aria-hidden":"true",children:R.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"})})})})},de=({className:e="",ariaLabel:t="Close",onClick:s})=>{const{close:r}=E();return R.jsx("button",{className:`concierge-close ${e}`,onClick:()=>{s&&s(),r()},"aria-label":t,type:"button",children:R.jsx("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"currentColor","aria-hidden":"true",children:R.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})})})},ue=({...e})=>{const{startNewChat:t,messages:s}=Y();return s.length>0?R.jsx("button",{className:"concierge-new-chat-button",type:"button",title:"Start new chat",onClick:t,...e,children:"Start new chat"}):null},he={Text:({block:e})=>R.jsx("div",{children:e.content}),Element:({block:e})=>R.jsx(X,{markdown:e.raw}),Error:({block:e})=>R.jsx("div",{className:"concierge-error",children:e.content})},me=({title:e="Concierge",children:t,render:r,components:n={},onMessage:c,onMessageBlock:l})=>{const{isOpen:d,toggleOpen:h,theme:p,position:g}=E(),{messages:f,addMessage:b,clearMessages:y,updateMessage:k}=I(),{handleEvent:v}=N(),{isLoading:x,error:w,sendMessage:j,cancelRequest:_}=U(),{addReplacer:S}=ae(),[T,A]=s(""),O=i(new Set);a((()=>{S("a.see-more-block__button",((e,t)=>{if(e instanceof u&&"a"===e.name&&e.attribs?.class?.includes("see-more-block__button")&&e.attribs["data-onclick-url"]!==e.attribs.href){const{href:s,class:r,"data-onclick-url":n,...i}=e.attribs;return R.jsx(R.Fragment,{children:R.jsx("a",{className:r,href:n,"data-onclick-url":n,...i,children:m(e.children,t)},e.attribs?.id)})}return e})),S("div.data-template",((e,t)=>{if(e instanceof u&&"div"===e.name&&e.attribs?.class?.includes("data-template")){const{class:s,...r}=e.attribs;return R.jsx(R.Fragment,{children:R.jsx("div",{className:s,...r,children:m(e.children,t)},e.attribs?.id)})}return e}))}),[S]);const M=o((()=>Array.from(new Set([...Object.keys(n),...Object.keys(he)])).reduce(((e,t)=>(e[t]=n[t]||he[t],e)),{})),[n]);return a((()=>{if(c&&f.length>0){const e=f[f.length-1];O.current.has(e.id)||(c(e),O.current.add(e.id))}}),[f,c]),a((()=>{if(w&&f.length>0){const e=f[f.length-1];if("assistant"===e.type){const t={type:"error",content:w,startIndex:0,endIndex:w.length,raw:w};(e.blocks||[]).some((e=>"error"===e.type&&e.content===w))||k(e.id,{blocks:[...e.blocks||[],t]})}}}),[w,f,k]),a((()=>{0===f.length&&O.current.clear()}),[f.length]),r?R.jsx(R.Fragment,{children:r({addMessage:b,cancelRequest:_,clearMessages:y,sendMessage:j,setInput:A,toggleOpen:h,updateMessage:k,components:M,error:w,input:T,isLoading:x,isOpen:d,messages:f,position:g,theme:p})}):R.jsxs(R.Fragment,{children:[R.jsx(le,{}),R.jsxs("div",{className:`concierge-component ${p} ${g} ${d?"open":""}`,children:[R.jsxs("header",{className:"concierge-header",children:[R.jsx("h2",{className:"concierge-title",children:e}),R.jsx(de,{})]}),d&&R.jsxs(R.Fragment,{children:[R.jsxs("main",{className:"concierge-content",children:[R.jsx(ce,{messages:f,components:M,onEvent:(e,t)=>v(e,t),onMessageBlock:l}),x&&R.jsx(ee,{}),t]}),R.jsxs("footer",{className:"concierge-footer",children:[R.jsx(Q,{onSend:j,onStop:_,placeholder:"Type your message..."}),R.jsx(ue,{})]})]})]})]})},pe=({children:e,defaultOpen:t=!1,defaultTheme:s="light",defaultPosition:r="bottom-right",apiOptions:n,defaultMessages:i=[],defaultReplacers:a={}})=>R.jsx(T,{defaultMessages:i,children:R.jsx(z,{apiOptions:n,children:R.jsx(_,{defaultOpen:t,defaultTheme:s,defaultPosition:r,children:R.jsx(ie,{defaultReplacers:a,children:R.jsx(M,{children:e})})})})});var ge=Object.freeze({__proto__:null,CloseButton:de,ConciergeInput:Q,ConciergeMessages:ce,Element:X,ElementLink:J,Message:oe,NewChatButton:ue,SendButton:G,ToggleButton:le,elementLinkReplacer:W,parseElementMarkdown:V});function fe(e,t,s){if("assistant"===s.type&&t.url){e.preventDefault();const r=s.blocks?.filter((e=>!e.content.includes("see-more")));this.updateMessage(s.id,{blocks:r}),this.setIsLoading(!0),this.api.loadAdditionalContent(t.url).then((({blocks:e})=>{this.updateMessage(s.id,{blocks:[...r??[],...e]}),this.setIsLoading(!1)})).catch((e=>{this.setError(e.message),this.setIsLoading(!1)}))}}const be=()=>{const{api:e,updateMessage:t,setIsLoading:s,setError:n,isLoading:i}=Y();return{seeMoreAction:r(((r,a,o)=>{fe.bind({api:e,updateMessage:t,setIsLoading:s,setError:n,isLoading:i})(r,a,o)}),[e,t,s,n,i])}};export{z as APIProvider,M as ActionProvider,me as Concierge,ge as ConciergeComponents,Z as ConciergeContext,pe as ConciergeProvider,T as MessageProvider,ie as MessageReplacerProvider,_ as UIProvider,re as parseHtml,U as useAPIContext,N as useActionContext,Y as useConcierge,be as useConciergeActions,I as useMessageContext,ae as useMessageReplacer,E as useUIContext};
//# sourceMappingURL=index.js.map