userflow.js-self-hosted 0.1.1004175 → 0.1.1004182
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/ResourceCenterAssistantChat.js +1 -1
- package/bubble-frame.css +5 -1
- package/hash.txt +1 -1
- package/package.json +1 -1
- package/userflow.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./vendor.react.js";import{Z as t,$ as s,i as a}from"./userflow.js";import{u as n}from"./client-context.js";import{D as r,E as o,F as i,G as l,H as c,I as u,J as m,K as d}from"./vendor.fortawesome.pro-regular-svg-icons.js";import{p as g}from"./vendor.dompurify.js";import{m as f}from"./vendor.marked.js";import{o as b}from"./vendor.obj-str.js";import{A as p,G as h}from"./ResourceCenterApp.js";import{r as k,R as E}from"./bubble-frame.styl.js";import{D as _}from"./stylesheets.js";import{U as v,b as j}from"./flow-condition-types.js";import{r as w}from"./vendor.react-dom.js";import"./vendor.object-assign.js";import"./vendor.phoenix.js";import"./vendor.uuid.js";import"./vendor.i18next.js";import"./vendor.react-i18next.js";import"./vendor.babel.runtime.js";import"./flow-host.styl.js";import"./use-window-resize.js";import"./logomark.js";import"./ChecklistUI.js";import"./vendor.fortawesome.pro-solid-svg-icons.js";import"./BubbleToolbar.js";import"./use-element-rect.js";import"./vendor.date-fns.js";import"./vendor.scheduler.js";const I=[];const C=({assistant:t,lookupAttribute:s,history:a,setInput:n,contentElRef:r,scrolledToTop:o,userContent:i,setUserContent:l,onSubmitMessage:c,supportsFeedback:u,onSubmitRating:m,onSubmitFeedback:d,InsideMessage:g,reset:f,onContentScroll:h,onContentWheel:_,conversationId:v})=>e.createElement("div",{className:"userflowjs-assistant-chat"},e.createElement("div",{className:b({"userflowjs-assistant-chat__header":!0,"userflowjs-assistant-chat__header--content-scrolled":!o})},e.createElement("h2",{className:"userflowjs-assistant-chat__title"},t.title),e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--default",onClick:f},t.resetText)),e.createElement("div",{ref:r,className:"userflowjs-assistant-chat__content",onScroll:h,onWheel:_},!k(t.intro)&&e.createElement("div",{className:"userflowjs-assistant-chat__intro"},e.createElement(E,{doc:t.intro,lookupAttribute:s})),a.map(((s,n)=>e.createElement(S,{key:n,assistant:t,message:s,supportsFeedback:u,onSubmitRating:m,onSubmitFeedback:d,InsideMessage:g,conversationId:v,isLast:n===a.length-1})))),e.createElement("div",{className:"userflowjs-assistant-chat__prompt"},e.createElement(p,{textareaRef:n,placeholder:(0===a.length?t.promptEmptyPlaceholder:t.promptNonemptyPlaceholder)||"",value:i,onChange:l,onSubmit:()=>c(i)}))),S=({assistant:s,message:a,supportsFeedback:n,onSubmitRating:r,onSubmitFeedback:o,InsideMessage:i,conversationId:l,isLast:c})=>e.createElement("div",{className:"userflowjs-assistant-chat__message"},i&&e.createElement(i,{message:a}),e.createElement("div",{className:b({"userflowjs-assistant-chat__user-content":!0,"userflowjs-assistant-chat__user-content--enter":!!a.enterAnimation}),"data-assistant-conversation-id":l,"data-assistant-message-id":a.id},e.createElement("div",{style:{whiteSpace:"pre-wrap"}},a.userContent)),a.warning&&e.createElement("div",{className:"userflowjs-assistant-chat__error"},"Warning: ",a.warning),e.createElement("div",{className:"userflowjs-assistant-chat__assistant-content"},e.createElement("div",null,e.createElement(N,{html:a.assistantHtml})),a.error&&e.createElement("div",{className:"userflowjs-assistant-chat__error"},a.error)),a.sources&&a.sources.length>0&&e.createElement("div",{className:"userflowjs-assistant-chat__sources"},e.createElement("div",{className:"userflowjs-assistant-chat__sources-title"},s.sourcesText),a.sources.map(((t,s)=>e.createElement("a",{key:s,className:"userflowjs-assistant-chat__source",href:t.url,target:"_blank",rel:"noreferrer noopener"},t.title)))),n&&a.completed&&a.id&&(s.ratingMode===t.LIKE||s.ratingMode===t.SCALE&&c)&&e.createElement(M,{assistant:s,message:a,onSubmitRating:r,onSubmitFeedback:o})),M=({assistant:a,message:n,onSubmitRating:l,onSubmitFeedback:c})=>{const u=e.useRef(null),[m,d]=e.useState(""),g=()=>{n.id&&(c({messageId:n.id,feedback:m.trim()}),d(""))},f=a.ratingMode===t.LIKE?e.createElement("button",{className:"userflowjs-assistant-chat__rating-option",disabled:!0},e.createElement(_,{icon:n.rating==s.DISLIKE?r:o})):n.scaleRating&&n.scaleMax&&e.createElement("button",{className:b({"userflowjs-assistant-chat__rating-option":!0,"userflowjs-assistant-chat__rating-option--scale":!0}),disabled:!0},L(a,n.scaleRating,n.scaleMax));return e.createElement("div",{className:`userflowjs-assistant-chat__rating userflowjs-assistant-chat__rating--${a.ratingMode}`},a.ratingMode===t.SCALE&&e.createElement("div",{className:"userflowjs-assistant-chat__rating-question"},a.scaleQuestion),n.feedbackSubmitted?e.createElement("div",{className:"userflowjs-assistant-chat__rating-thanks"},f,e.createElement("div",{className:"userflowjs-assistant-chat__rating-thanks-message"},a.feedbackThanksText)):(a.ratingMode===t.LIKE?n.rating:n.scaleRating)?e.createElement(h,{textareaRef:u,className:"userflowjs-growing-textarea userflowjs-assistant-chat__feedback-textarea",mirrorClassName:"userflowjs-growing-textarea__mirror",textareaClassName:"userflowjs-textarea",placeholder:(a.ratingMode===t.LIKE?n.rating===s.LIKE?a.feedbackLikePlaceholder:a.feedbackDislikePlaceholder:a.scaleFeedbackPlaceholder)||"",value:m,onChange:d,onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||(e.preventDefault(),g())}},f,e.createElement("button",{className:"userflowjs-assistant-chat__feedback-submit",onClick:()=>g()},e.createElement(_,{icon:i}))):e.createElement("div",{className:"userflowjs-assistant-chat__rating-options"},a.ratingMode===t.LIKE?[s.LIKE,s.DISLIKE].map((a=>(!n.rating||n.rating===a)&&e.createElement("button",{key:a,className:"userflowjs-assistant-chat__rating-option",onClick:n.rating?void 0:()=>(e=>{const s=n.id;s&&(w.flushSync((()=>{l({ratingMode:t.LIKE,messageId:s,rating:e})})),u.current?.focus({preventScroll:!0}))})(a),disabled:!!n.rating,"data-testid":`assistant-chat-rating-${a}`},e.createElement(_,{icon:a==s.DISLIKE?r:o})))):function(e){let t=[];const s=e.scaleMax||5;for(let a=1;a<=s;a++)t.push({value:a,label:L(e,a,s)});return t}(a).map((({value:s,label:r})=>e.createElement("button",{key:s,className:b({"userflowjs-assistant-chat__rating-option":!0,"userflowjs-assistant-chat__rating-option--scale":!0,"userflowjs-assistant-chat__rating-option--selected":s===n.scaleRating}),onClick:n.scaleRating?void 0:()=>(e=>{const s=n.id;s&&(w.flushSync((()=>{l({ratingMode:t.SCALE,messageId:s,scaleRating:e,scaleMax:a.scaleMax})})),u.current?.focus({preventScroll:!0}))})(s),disabled:!!n.scaleRating,"data-testid":`assistant-chat-rating-${s}`},r)))))};function R(e){let t=e;const s=e=>e=(e=e.replace(/\s*[*_`]*$/,"")).replace(/(^|\n)\s*(\d+\.?|-|=)$/,"");t=s(t),t=t.replace(/\[([^\]\n]*)(\](\([^)\n]*)?)?$/,"$1"),t=s(t);const a=Array.from(t.matchAll(/\n( *)```/g));if(a.length%2==1){t+="\n"+a[a.length-1][1]+"```"}else{let e=0;for(let r=t.length-1;r>=0;r--)if("\n"===t[r]&&"\n"===t[r-1]){e=r;break}const s=[];let a=!1;const n=e=>null==e||e.match(/\W/);for(let r=e;r<t.length;r++){const o=t[r],i=o+t[r+1],l=i+t[r+2];let c=null;if((a||"***"!==l)&&(a||"___"!==l||!n(t[r-1])&&!n(t[r+3]))?(a||"**"!==i)&&(a||"__"!==i||!n(t[r-1])&&!n(t[r+2]))?(a||"*"!==o)&&(a||"_"!==o||!n(t[r-1])&&!n(t[r+1]))?"`"===o&&(c=o):c=o:c=i:c=l,null!=c){!!t.slice(e,r+c.length).match(/\[[^\]\n]*\]\([^)\n]*$/)||(s[s.length-1]===c?("`"===c&&(a=!1),s.pop()):("`"===c&&(a=!0),s.push(c))),r+=c.length-1}}t+=s.reverse().join("")}return t}function y(e,t){e=e.trim(),!1!==t&&(e=e.replace(/(\n *```)?$/," {{USERFLOWCHATBRAIN}}$1"));let s=g.sanitize(f.parse(e));if(!1!==t){let e="userflowjs-assistant-brain";t&&(e+=` userflowjs-assistant-brain--${t}`),s=s.replace("{{USERFLOWCHATBRAIN}}",`<span class="${e}"><span></span><span></span><span></span><span></span></span>`)}return s=s.replace(/<a href=/g,'<a target="_blank" rel="noopener noreferrer" href='),s}const N=({html:t})=>e.useMemo((()=>{if(!t)return null;return x((new DOMParser).parseFromString(t,"text/html").body)}),[t]);function x(t,s){if(t instanceof Element){if("BODY"===t.tagName)return e.createElement(e.Fragment,{key:s},A(t));{if(["script","style"].includes(t.tagName))return null;const a={key:s};for(const e of t.attributes){let t=e.name;t.startsWith("on")||("class"===t&&(t="className"),a[t]=e.value)}return e.createElement(t.tagName.toLowerCase(),a,A(t))}}return t instanceof Text?t.textContent:null}function A(e){const t=[];let s=0;for(const a of e.childNodes)t.push(x(a,s)),s++;return t}function L(t,s,a){if(t.scaleLabels)return t.scaleLabels[s-1]||s;{const t=F[a]&&F[a][s];return t?e.createElement(_,{icon:t,size:24}):s}}const F={2:{1:l,2:c},3:{1:l,2:u,3:c},4:{1:m,2:l,3:c,4:d},5:{1:m,2:l,3:u,4:c,5:d}},H=({block:s,session:r,assistantReply:o,initialUserContent:i})=>{const l=s.assistantFlowId,c=n(),u=function({assistant:s,lookupAttribute:a,initialConversationId:n,initialHistory:r,initialUserContent:o,onConversationIdChange:i,submitMessage:l,submitRating:c,submitFeedback:u,InsideMessage:m}){const[d,g]=e.useState(null),[f,b]=e.useState((()=>r?r.map((e=>({...e,assistantHtml:y(R(e.assistantContent),!1)}))):I)),[p,h]=e.useState(""),k=e.useRef(null),E=e.useRef(null),_=e.useRef(!0),j=e.useRef(n||null),[w,C]=e.useState(j.current),S=e.useCallback((e=>{j.current=e,C(e),i&&i(e)}),[i]),M=e.useCallback((()=>{d?.focus({preventScroll:!0})}),[d]);e.useEffect((()=>{M()}),[M]),e.useLayoutEffect((()=>{const e=E.current;e&&(e.scrollTop=Math.ceil(e.scrollHeight-e.clientHeight))}),[]);const N=e.useCallback((()=>{const e=E.current;e&&(_.current=!0,"function"==typeof e.scrollTo&&e.scrollTo({top:Math.ceil(e.scrollHeight-e.clientHeight),behavior:"smooth"}))}),[]),x=e.useRef(0);e.useLayoutEffect((()=>{const e=E.current;e&&e.scrollHeight!==x.current&&(x.current=e.scrollHeight,_.current&&N())}),[f,N]);const A=e.useCallback((()=>{k.current&&k.current()}),[]);e.useEffect((()=>()=>{A()}),[A]);const L=(e,t)=>{b((s=>s.map((s=>{if(e===s.id){const e=t(s);return{...s,...e}}return s}))))},F=e=>{b((t=>t.map(((s,a)=>{if(a===t.length-1){const t=e(s);return{...s,...t}}return s}))))},H=e.useCallback((async e=>{if(""===(e=e.trim()))return;A(),b((t=>[...t,{id:null,userContent:e,assistantContent:"",assistantHtml:y("","enter"),enterAnimation:!0,sources:[],completed:!1,rating:null,scaleRating:null,scaleMax:null,feedbackSubmitted:!1}])),h(""),N();let t=!1;const s=()=>{t=!0,k.current=null},a=l({conversationId:j.current,userContent:e,callback:e=>{if(t)console.log("Userflow.js AssistantChat got message after being done",e);else switch(e.kind){case"conversation_created":S(e.conversationId);break;case"message_created":F((()=>({id:e.messageId,warning:e.warning})));break;case"assistant_content_delta":F((t=>{const s=e.delta,a=t.assistantContent+s;return{assistantContent:a,assistantHtml:y(R(a))}}));break;case"done":s(),F((t=>({assistantHtml:y(t.assistantContent,"exit"),completed:!0,sources:e.sources})));break;case"error":s(),F((t=>({failed:!0,error:e.message,assistantHtml:y(R(t.assistantContent),!1)})));break;default:console.log("Userflow.js AssistantChat got unknown message",e)}}});k.current=()=>{s(),a.abort(),F((e=>({assistantHtml:y(R(e.assistantContent),!1)})))}}),[A,N,l,S]),T=e.useRef(!1);e.useEffect((()=>{T.current||(T.current=!0,o&&H(o))}),[H,o]);const K=e.useCallback((()=>{A(),S(null),b(I),M()}),[A,M,S]),[$,U]=e.useState(!0),D=e.useCallback((()=>{const e=E.current;e&&U(0===e.scrollTop)}),[]),P=e.useCallback((()=>{const e=E.current;e&&(_.current=Math.ceil(e.scrollHeight-e.clientHeight)==Math.ceil(e.scrollTop))}),[]);return{assistant:s,lookupAttribute:a,history:f,setInput:g,contentElRef:E,scrolledToTop:$,userContent:p,setUserContent:h,onSubmitMessage:H,supportsFeedback:!!c&&!!u,onSubmitRating:e=>{if(c){switch(e.ratingMode){case t.LIKE:L(e.messageId,(()=>({rating:e.rating})));break;case t.SCALE:L(e.messageId,(()=>({scaleRating:e.scaleRating,scaleMax:e.scaleMax})));break;default:throw new v(e)}c(e)}},onSubmitFeedback:e=>{u&&(L(e.messageId,(()=>({feedbackSubmitted:!0}))),u(e))},InsideMessage:m,reset:K,onContentScroll:D,onContentWheel:P,conversationId:w}}(e.useMemo((()=>({assistant:o.assistant,lookupAttribute:j(r.data),initialConversationId:o.conversationId,initialHistory:o.history,initialUserContent:i,onConversationIdChange:e=>{const t="assistantConversationId:"+l;e?a.setItem(t,e):a.removeItem(t)},submitMessage:({conversationId:e,userContent:t,callback:s})=>{c.assistantMessageInProgress=!0;const a=c.nextRef();c.send({kind:"SubmitAssistantMessage",ref:a,assistantFlowId:l,conversationId:e,userContent:t}).catch((e=>{s({kind:"error",message:e.humanMessage||"I'm sorry, but something went wrong. Please try again."})}));const n=()=>{c.assistantMessageInProgress=void 0,c.off("private:assistantMessageEvent",r),c.off("private:disconnect",o)},r=e=>{if(e.ref!==a)return;const{event:t}=e;s(t),"done"!=t.kind&&"error"!=t.kind||n()},o=()=>{s({kind:"error",message:"Sorry, my connection got disconnected. Please try again or contact my human friends."}),n()};return c.on("private:assistantMessageEvent",r),c.on("private:disconnect",o),{abort:()=>{c.send({kind:"AbortAssistantMessage"}),n()}}},submitRating:e=>{switch(e.ratingMode){case t.LIKE:c.send({kind:"SubmitAssistantRating",messageId:e.messageId,rating:e.rating});break;case t.SCALE:c.send({kind:"SubmitAssistantScaleRating",messageId:e.messageId,scaleRating:e.scaleRating,scaleMax:e.scaleMax});break;default:throw new v(e)}},submitFeedback:e=>{c.send({kind:"SubmitAssistantFeedback",messageId:e.messageId,feedback:e.feedback})}})),[o,l,c,i,r.data]));return e.createElement(e.Fragment,null,e.createElement(C,{...u}))};export{H as ResourceCenterAssistantChat};
|
|
1
|
+
import{r as e}from"./vendor.react.js";import{Z as t,$ as s,i as a}from"./userflow.js";import{u as n}from"./client-context.js";import{D as r,E as o,F as i,G as l,H as c,I as u,J as m,K as d}from"./vendor.fortawesome.pro-regular-svg-icons.js";import{p as g}from"./vendor.dompurify.js";import{m as f}from"./vendor.marked.js";import{o as p}from"./vendor.obj-str.js";import{A as b,G as h}from"./ResourceCenterApp.js";import{r as E,R as k}from"./bubble-frame.styl.js";import{D as _}from"./stylesheets.js";import{U as j,b as v}from"./flow-condition-types.js";import{r as w}from"./vendor.react-dom.js";import"./vendor.object-assign.js";import"./vendor.phoenix.js";import"./vendor.uuid.js";import"./vendor.i18next.js";import"./vendor.react-i18next.js";import"./vendor.babel.runtime.js";import"./flow-host.styl.js";import"./use-window-resize.js";import"./logomark.js";import"./ChecklistUI.js";import"./vendor.fortawesome.pro-solid-svg-icons.js";import"./BubbleToolbar.js";import"./use-element-rect.js";import"./vendor.date-fns.js";import"./vendor.scheduler.js";function I(e){const t=Intl.Segmenter;if(t){return/(\p{Emoji_Presentation}|\p{Extended_Pictographic})(\p{Emoji_Modifier_Base}?\p{Emoji_Modifier}?|\uFE0F\u200D(\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?\uFE0F\u200D)*\p{Emoji_Presentation}|\uFE0F\u200D\p{Extended_Pictographic})/u.test(e)&&1===[...(new t).segment(e)].length}return!1}const C=[];const S=({assistant:t,lookupAttribute:s,history:a,setInput:n,contentElRef:r,scrolledToTop:o,userContent:i,setUserContent:l,onSubmitMessage:c,supportsFeedback:u,onSubmitRating:m,onSubmitFeedback:d,InsideMessage:g,reset:f,onContentScroll:h,onContentWheel:_,conversationId:j})=>e.createElement("div",{className:"userflowjs-assistant-chat"},e.createElement("div",{className:p({"userflowjs-assistant-chat__header":!0,"userflowjs-assistant-chat__header--content-scrolled":!o})},e.createElement("h2",{className:"userflowjs-assistant-chat__title"},t.title),e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--default",onClick:f},t.resetText)),e.createElement("div",{ref:r,className:"userflowjs-assistant-chat__content",onScroll:h,onWheel:_},!E(t.intro)&&e.createElement("div",{className:"userflowjs-assistant-chat__intro"},e.createElement(k,{doc:t.intro,lookupAttribute:s})),a.map(((s,n)=>e.createElement(M,{key:n,assistant:t,message:s,supportsFeedback:u,onSubmitRating:m,onSubmitFeedback:d,InsideMessage:g,conversationId:j,isLast:n===a.length-1})))),e.createElement("div",{className:"userflowjs-assistant-chat__prompt"},e.createElement(b,{textareaRef:n,placeholder:(0===a.length?t.promptEmptyPlaceholder:t.promptNonemptyPlaceholder)||"",value:i,onChange:l,onSubmit:()=>c(i)}))),M=({assistant:s,message:a,supportsFeedback:n,onSubmitRating:r,onSubmitFeedback:o,InsideMessage:i,conversationId:l,isLast:c})=>e.createElement("div",{className:"userflowjs-assistant-chat__message"},i&&e.createElement(i,{message:a}),e.createElement("div",{className:p({"userflowjs-assistant-chat__user-content":!0,"userflowjs-assistant-chat__user-content--enter":!!a.enterAnimation}),"data-assistant-conversation-id":l,"data-assistant-message-id":a.id},e.createElement("div",{style:{whiteSpace:"pre-wrap"}},a.userContent)),a.warning&&e.createElement("div",{className:"userflowjs-assistant-chat__error"},"Warning: ",a.warning),e.createElement("div",{className:"userflowjs-assistant-chat__assistant-content"},e.createElement("div",null,e.createElement(x,{html:a.assistantHtml})),a.error&&e.createElement("div",{className:"userflowjs-assistant-chat__error"},a.error)),a.sources&&a.sources.length>0&&e.createElement("div",{className:"userflowjs-assistant-chat__sources"},e.createElement("div",{className:"userflowjs-assistant-chat__sources-title"},s.sourcesText),a.sources.map(((t,s)=>e.createElement("a",{key:s,className:"userflowjs-assistant-chat__source",href:t.url,target:"_blank",rel:"noreferrer noopener"},t.title)))),n&&a.completed&&a.id&&(s.ratingMode===t.LIKE||s.ratingMode===t.SCALE&&c)&&e.createElement(R,{assistant:s,message:a,onSubmitRating:r,onSubmitFeedback:o})),R=({assistant:a,message:n,onSubmitRating:l,onSubmitFeedback:c})=>{const u=e.useRef(null),[m,d]=e.useState(""),g=()=>{n.id&&(c({messageId:n.id,feedback:m.trim()}),d(""))},f=a.ratingMode===t.LIKE?e.createElement("button",{className:"userflowjs-assistant-chat__rating-option",disabled:!0},e.createElement(_,{icon:n.rating==s.DISLIKE?r:o})):n.scaleRating&&n.scaleMax&&e.createElement("button",{className:p({"userflowjs-assistant-chat__rating-option":!0,"userflowjs-assistant-chat__rating-option--scale":!0}),disabled:!0},L(a,n.scaleRating,n.scaleMax));return e.createElement("div",{className:`userflowjs-assistant-chat__rating userflowjs-assistant-chat__rating--${a.ratingMode}`},a.ratingMode===t.SCALE&&e.createElement("div",{className:"userflowjs-assistant-chat__rating-question"},a.scaleQuestion),n.feedbackSubmitted?e.createElement("div",{className:"userflowjs-assistant-chat__rating-thanks"},f,e.createElement("div",{className:"userflowjs-assistant-chat__rating-thanks-message"},a.feedbackThanksText)):(a.ratingMode===t.LIKE?n.rating:n.scaleRating)?e.createElement(h,{textareaRef:u,className:"userflowjs-growing-textarea userflowjs-assistant-chat__feedback-textarea",mirrorClassName:"userflowjs-growing-textarea__mirror",textareaClassName:"userflowjs-textarea",placeholder:(a.ratingMode===t.LIKE?n.rating===s.LIKE?a.feedbackLikePlaceholder:a.feedbackDislikePlaceholder:a.scaleFeedbackPlaceholder)||"",value:m,onChange:d,onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||(e.preventDefault(),g())}},f,e.createElement("button",{className:"userflowjs-assistant-chat__feedback-submit",onClick:()=>g()},e.createElement(_,{icon:i}))):e.createElement("div",{className:"userflowjs-assistant-chat__rating-options"},a.ratingMode===t.LIKE?[s.LIKE,s.DISLIKE].map((a=>(!n.rating||n.rating===a)&&e.createElement("button",{key:a,className:"userflowjs-assistant-chat__rating-option",onClick:n.rating?void 0:()=>(e=>{const s=n.id;s&&(w.flushSync((()=>{l({ratingMode:t.LIKE,messageId:s,rating:e})})),u.current?.focus({preventScroll:!0}))})(a),disabled:!!n.rating,"data-testid":`assistant-chat-rating-${a}`},e.createElement(_,{icon:a==s.DISLIKE?r:o})))):function(e){let t=[];const s=e.scaleMax||5;for(let a=1;a<=s;a++)t.push({value:a,label:L(e,a,s)});return t}(a).map((({value:s,label:r})=>e.createElement("button",{key:s,className:p({"userflowjs-assistant-chat__rating-option":!0,"userflowjs-assistant-chat__rating-option--large-scale":I(r||"")}),onClick:n.scaleRating?void 0:()=>(e=>{const s=n.id;s&&(w.flushSync((()=>{l({ratingMode:t.SCALE,messageId:s,scaleRating:e,scaleMax:a.scaleMax})})),u.current?.focus({preventScroll:!0}))})(s),disabled:!!n.scaleRating,"data-testid":`assistant-chat-rating-${s}`},r)))))};function y(e){let t=e;const s=e=>e=(e=e.replace(/\s*[*_`]*$/,"")).replace(/(^|\n)\s*(\d+\.?|-|=)$/,"");t=s(t),t=t.replace(/\[([^\]\n]*)(\](\([^)\n]*)?)?$/,"$1"),t=s(t);const a=Array.from(t.matchAll(/\n( *)```/g));if(a.length%2==1){t+="\n"+a[a.length-1][1]+"```"}else{let e=0;for(let r=t.length-1;r>=0;r--)if("\n"===t[r]&&"\n"===t[r-1]){e=r;break}const s=[];let a=!1;const n=e=>null==e||e.match(/\W/);for(let r=e;r<t.length;r++){const o=t[r],i=o+t[r+1],l=i+t[r+2];let c=null;if((a||"***"!==l)&&(a||"___"!==l||!n(t[r-1])&&!n(t[r+3]))?(a||"**"!==i)&&(a||"__"!==i||!n(t[r-1])&&!n(t[r+2]))?(a||"*"!==o)&&(a||"_"!==o||!n(t[r-1])&&!n(t[r+1]))?"`"===o&&(c=o):c=o:c=i:c=l,null!=c){!!t.slice(e,r+c.length).match(/\[[^\]\n]*\]\([^)\n]*$/)||(s[s.length-1]===c?("`"===c&&(a=!1),s.pop()):("`"===c&&(a=!0),s.push(c))),r+=c.length-1}}t+=s.reverse().join("")}return t}function N(e,t){e=e.trim(),!1!==t&&(e=e.replace(/(\n *```)?$/," {{USERFLOWCHATBRAIN}}$1"));let s=g.sanitize(f.parse(e));if(!1!==t){let e="userflowjs-assistant-brain";t&&(e+=` userflowjs-assistant-brain--${t}`),s=s.replace("{{USERFLOWCHATBRAIN}}",`<span class="${e}"><span></span><span></span><span></span><span></span></span>`)}return s=s.replace(/<a href=/g,'<a target="_blank" rel="noopener noreferrer" href='),s}const x=({html:t})=>e.useMemo((()=>{if(!t)return null;return A((new DOMParser).parseFromString(t,"text/html").body)}),[t]);function A(t,s){if(t instanceof Element){if("BODY"===t.tagName)return e.createElement(e.Fragment,{key:s},F(t));{if(["script","style"].includes(t.tagName))return null;const a={key:s};for(const e of t.attributes){let t=e.name;t.startsWith("on")||("class"===t&&(t="className"),a[t]=e.value)}return e.createElement(t.tagName.toLowerCase(),a,F(t))}}return t instanceof Text?t.textContent:null}function F(e){const t=[];let s=0;for(const a of e.childNodes)t.push(A(a,s)),s++;return t}function L(t,s,a){if(t.scaleLabels)return t.scaleLabels[s-1]||s;{const t=H[a]&&H[a][s];return t?e.createElement(_,{icon:t,size:24}):s}}const H={2:{1:l,2:c},3:{1:l,2:u,3:c},4:{1:m,2:l,3:c,4:d},5:{1:m,2:l,3:u,4:c,5:d}},T=({block:s,session:r,assistantReply:o,initialUserContent:i})=>{const l=s.assistantFlowId,c=n(),u=function({assistant:s,lookupAttribute:a,initialConversationId:n,initialHistory:r,initialUserContent:o,onConversationIdChange:i,submitMessage:l,submitRating:c,submitFeedback:u,InsideMessage:m}){const[d,g]=e.useState(null),[f,p]=e.useState((()=>r?r.map((e=>({...e,assistantHtml:N(y(e.assistantContent),!1)}))):C)),[b,h]=e.useState(""),E=e.useRef(null),k=e.useRef(null),_=e.useRef(!0),v=e.useRef(n||null),[w,I]=e.useState(v.current),S=e.useCallback((e=>{v.current=e,I(e),i&&i(e)}),[i]),M=e.useCallback((()=>{d?.focus({preventScroll:!0})}),[d]);e.useEffect((()=>{M()}),[M]),e.useLayoutEffect((()=>{const e=k.current;e&&(e.scrollTop=Math.ceil(e.scrollHeight-e.clientHeight))}),[]);const R=e.useCallback((()=>{const e=k.current;e&&(_.current=!0,"function"==typeof e.scrollTo&&e.scrollTo({top:Math.ceil(e.scrollHeight-e.clientHeight),behavior:"smooth"}))}),[]),x=e.useRef(0);e.useLayoutEffect((()=>{const e=k.current;e&&e.scrollHeight!==x.current&&(x.current=e.scrollHeight,_.current&&R())}),[f,R]);const A=e.useCallback((()=>{E.current&&E.current()}),[]);e.useEffect((()=>()=>{A()}),[A]);const F=(e,t)=>{p((s=>s.map((s=>{if(e===s.id){const e=t(s);return{...s,...e}}return s}))))},L=e=>{p((t=>t.map(((s,a)=>{if(a===t.length-1){const t=e(s);return{...s,...t}}return s}))))},H=e.useCallback((async e=>{if(""===(e=e.trim()))return;A(),p((t=>[...t,{id:null,userContent:e,assistantContent:"",assistantHtml:N("","enter"),enterAnimation:!0,sources:[],completed:!1,rating:null,scaleRating:null,scaleMax:null,feedbackSubmitted:!1}])),h(""),R();let t=!1;const s=()=>{t=!0,E.current=null},a=l({conversationId:v.current,userContent:e,callback:e=>{if(t)console.log("Userflow.js AssistantChat got message after being done",e);else switch(e.kind){case"conversation_created":S(e.conversationId);break;case"message_created":L((()=>({id:e.messageId,warning:e.warning})));break;case"assistant_content_delta":L((t=>{const s=e.delta,a=t.assistantContent+s;return{assistantContent:a,assistantHtml:N(y(a))}}));break;case"done":s(),L((t=>({assistantHtml:N(t.assistantContent,"exit"),completed:!0,sources:e.sources})));break;case"error":s(),L((t=>({failed:!0,error:e.message,assistantHtml:N(y(t.assistantContent),!1)})));break;default:console.log("Userflow.js AssistantChat got unknown message",e)}}});E.current=()=>{s(),a.abort(),L((e=>({assistantHtml:N(y(e.assistantContent),!1)})))}}),[A,R,l,S]),T=e.useRef(!1);e.useEffect((()=>{T.current||(T.current=!0,o&&H(o))}),[H,o]);const K=e.useCallback((()=>{A(),S(null),p(C),M()}),[A,M,S]),[P,D]=e.useState(!0),$=e.useCallback((()=>{const e=k.current;e&&D(0===e.scrollTop)}),[]),U=e.useCallback((()=>{const e=k.current;e&&(_.current=Math.ceil(e.scrollHeight-e.clientHeight)==Math.ceil(e.scrollTop))}),[]);return{assistant:s,lookupAttribute:a,history:f,setInput:g,contentElRef:k,scrolledToTop:P,userContent:b,setUserContent:h,onSubmitMessage:H,supportsFeedback:!!c&&!!u,onSubmitRating:e=>{if(c){switch(e.ratingMode){case t.LIKE:F(e.messageId,(()=>({rating:e.rating})));break;case t.SCALE:F(e.messageId,(()=>({scaleRating:e.scaleRating,scaleMax:e.scaleMax})));break;default:throw new j(e)}c(e)}},onSubmitFeedback:e=>{u&&(F(e.messageId,(()=>({feedbackSubmitted:!0}))),u(e))},InsideMessage:m,reset:K,onContentScroll:$,onContentWheel:U,conversationId:w}}(e.useMemo((()=>({assistant:o.assistant,lookupAttribute:v(r.data),initialConversationId:o.conversationId,initialHistory:o.history,initialUserContent:i,onConversationIdChange:e=>{const t="assistantConversationId:"+l;e?a.setItem(t,e):a.removeItem(t)},submitMessage:({conversationId:e,userContent:t,callback:s})=>{c.assistantMessageInProgress=!0;const a=c.nextRef();c.send({kind:"SubmitAssistantMessage",ref:a,assistantFlowId:l,conversationId:e,userContent:t}).catch((e=>{s({kind:"error",message:e.humanMessage||"I'm sorry, but something went wrong. Please try again."})}));const n=()=>{c.assistantMessageInProgress=void 0,c.off("private:assistantMessageEvent",r),c.off("private:disconnect",o)},r=e=>{if(e.ref!==a)return;const{event:t}=e;s(t),"done"!=t.kind&&"error"!=t.kind||n()},o=()=>{s({kind:"error",message:"Sorry, my connection got disconnected. Please try again or contact my human friends."}),n()};return c.on("private:assistantMessageEvent",r),c.on("private:disconnect",o),{abort:()=>{c.send({kind:"AbortAssistantMessage"}),n()}}},submitRating:e=>{switch(e.ratingMode){case t.LIKE:c.send({kind:"SubmitAssistantRating",messageId:e.messageId,rating:e.rating});break;case t.SCALE:c.send({kind:"SubmitAssistantScaleRating",messageId:e.messageId,scaleRating:e.scaleRating,scaleMax:e.scaleMax});break;default:throw new j(e)}},submitFeedback:e=>{c.send({kind:"SubmitAssistantFeedback",messageId:e.messageId,feedback:e.feedback})}})),[o,l,c,i,r.data]));return e.createElement(e.Fragment,null,e.createElement(S,{...u}))};export{T as ResourceCenterAssistantChat};
|
package/bubble-frame.css
CHANGED
|
@@ -2021,12 +2021,16 @@ a.userflowjs-resource-center-block--clickable:hover {
|
|
|
2021
2021
|
justify-content: center;
|
|
2022
2022
|
}
|
|
2023
2023
|
.userflowjs-assistant-chat__rating--SCALE .userflowjs-assistant-chat__rating-options .userflowjs-assistant-chat__rating-option {
|
|
2024
|
-
padding: 0 0.75rem;
|
|
2024
|
+
padding: 0.25rem 0.75rem;
|
|
2025
|
+
height: 2rem;
|
|
2025
2026
|
}
|
|
2026
2027
|
.userflowjs-assistant-chat__rating--SCALE .userflowjs-assistant-chat__rating-options .userflowjs-assistant-chat__rating-option svg {
|
|
2027
2028
|
width: 24px;
|
|
2028
2029
|
height: 24px;
|
|
2029
2030
|
}
|
|
2031
|
+
.userflowjs-assistant-chat__rating--SCALE .userflowjs-assistant-chat__rating-options .userflowjs-assistant-chat__rating-option--large-scale {
|
|
2032
|
+
font-size: calc(var(--userflow-font-size) * 1.75);
|
|
2033
|
+
}
|
|
2030
2034
|
.userflowjs-assistant-chat__rating-question {
|
|
2031
2035
|
opacity: 0.5;
|
|
2032
2036
|
font-size: calc(var(--userflow-font-size) * 0.875);
|
package/hash.txt
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
e9d0d45f98e3dec9169d5d3b2598fa52669289ec
|
package/package.json
CHANGED
package/userflow.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as e}from"./vendor.phoenix.js";import{v as t}from"./vendor.uuid.js";let s;const i={},n=function(e,t){if(!t)return e();if(void 0===s){const e=document.createElement("link").relList;s=e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}return Promise.all(t.map((e=>{if(e in i)return;i[e]=!0;const t=e.endsWith(".css"),n=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${n}`))return;const o=document.createElement("link");return o.rel=t?"stylesheet":s,t||(o.as="script",o.crossOrigin=""),o.href=e,document.head.appendChild(o),t?new Promise(((e,t)=>{o.addEventListener("load",e),o.addEventListener("error",t)})):void 0}))).then((()=>e()))};class o extends Error{constructor(e,t,s){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t,this.humanMessage=s}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}isSupported(){if("undefined"==typeof window)return!1;try{return null!=window[this.type]}catch{return!1}}getItem(e){return e=this.formatKey(e),this.isSupported()?window[this.type].getItem(e):null}setItem(e,t){e=this.formatKey(e),this.isSupported()&&window[this.type].setItem(e,t)}removeItem(e){if(e=this.formatKey(e),this.isSupported())return window[this.type].removeItem(e)}clear(){if(this.isSupported())return window[this.type].clear()}}const a=new r("localStorage"),c=new r("sessionStorage");function l(e){window.location.href=e}function d(){return window.location.href}var h,u,E;function T(e){window.postMessage(e,window.origin)}function S(e){const t=t=>{if(t.source!==window||t.origin!==window.origin)return;const i=t.data;i&&"object"==typeof i&&"string"==typeof i.kind&&i.kind.startsWith("userflow:")&&!0===e(i)&&s()};window.addEventListener("message",t);const s=()=>window.removeEventListener("message",t);return s}(h||(h={})).INPUT="INPUT",(E=u||(u={})).AUTO="AUTO",E.MANUAL="MANUAL";const f=new Set;let w=!1;function p(e){return function(){if(w)return;w=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),I()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{I()}))}(),f.add(e),()=>{g(e)}}function g(e){f.delete(e)}function I(){f.forEach((e=>e()))}class C{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){T({kind:"userflow:crxSendProxyMessage",direction:"targetToBuilder",message:e})}onBuilderMessage(e){return this.unregisterOnMessage=S(e),!1}async captureScreenshot(e,t,s,i){T({kind:"userflow:crxScreenshot",x:e,y:t,width:s,height:i,devicePixelRatio:window.devicePixelRatio});var n;return(await(n=e=>"userflow:crxScreenshotResult"===e.kind?e:null,new Promise((e=>{S((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,A,U,L,R,N,v,O,y,_,b,D,M,F,B,P,x,H,G,W,$,V,K,j,z,Y,J,X,Z,Q,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,Ee,Te,Se,fe,we,pe,ge,Ie,Ce,me,ke,Ae,Ue,Le,Re,Ne,ve,Oe,ye,_e,be,De,Me,Fe,Be,Pe,xe,He,Ge,We,$e,Ve,Ke,je,ze,Ye,Je,Xe,Ze;(k=m||(m={})).ACTION="ACTION",k.LAUNCHER_DEACTIVATED="LAUNCHER_DEACTIVATED",k.REPLACED="REPLACED",k.SNOOZED="SNOOZED",k.TOOLTIP_TARGET_MISSING="TOOLTIP_TARGET_MISSING",k.USERFLOWJS="USERFLOWJS",k.USER_CLOSED="USER_CLOSED",(U=A||(A={})).SECOND="SECOND",U.MINUTE="MINUTE",U.HOUR="HOUR",U.DAY="DAY",(R=L||(L={})).ACTION="ACTION",R.DRAFT="DRAFT",R.LINK="LINK",R.LAUNCHER_SEEN="LAUNCHER_SEEN",R.RESOURCE_CENTER="RESOURCE_CENTER",R.USERFLOWJS="USERFLOWJS",(v=N||(N={})).LIKE="LIKE",v.DISLIKE="DISLIKE",(y=O||(O={})).STRING="STRING",y.BOOLEAN="BOOLEAN",y.NUMBER="NUMBER",y.DATETIME="DATETIME",y.LIST="LIST",y.RANDOM_AB="RANDOM_AB",y.RANDOM_NUMBER="RANDOM_NUMBER",(b=_||(_={})).FLOW="FLOW",b.BANNER="BANNER",b.CHECKLIST="CHECKLIST",b.LAUNCHER="LAUNCHER",b.RESOURCE_CENTER="RESOURCE_CENTER",(M=D||(D={})).ALWAYS_TRUE="ALWAYS_TRUE",M.ATTRIBUTE="ATTRIBUTE",M.CLAUSE="CLAUSE",M.ELEMENT="ELEMENT",M.FILLED_IN_INPUT="FILLED_IN_INPUT",M.FLOW="FLOW",M.INPUT_VALUE="INPUT_VALUE",M.PAGE="PAGE",M.SEGMENT="SEGMENT",M.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(F||(F={})),(B||(B={})).INPUT="INPUT",(x=P||(P={})).ABSOLUTE_EQ="ABSOLUTE_EQ",x.ABSOLUTE_GT="ABSOLUTE_GT",x.ABSOLUTE_LT="ABSOLUTE_LT",x.AND="AND",x.BETWEEN="BETWEEN",x.CONTAINS="CONTAINS",x.EMPTY="EMPTY",x.ENDS_WITH="ENDS_WITH",x.EQ="EQ",x.EXCLUDES_ALL="EXCLUDES_ALL",x.EXCLUDES_ANY="EXCLUDES_ANY",x.FALSE="FALSE",x.GT="GT",x.GTE="GTE",x.INCLUDES_ALL="INCLUDES_ALL",x.INCLUDES_ANY="INCLUDES_ANY",x.LT="LT",x.LTE="LTE",x.NE="NE",x.NOT_CONTAINS="NOT_CONTAINS",x.NOT_EMPTY="NOT_EMPTY",x.NOT_REGEX="NOT_REGEX",x.OR="OR",x.REGEX="REGEX",x.RELATIVE_EQ="RELATIVE_EQ",x.RELATIVE_GT="RELATIVE_GT",x.RELATIVE_LT="RELATIVE_LT",x.STARTS_WITH="STARTS_WITH",x.TRUE="TRUE",x.URL="URL",(G=H||(H={})).CLICK="CLICK",G.DISABLED="DISABLED",G.MOUSEDOWN="MOUSEDOWN",G.NOT_CLICK="NOT_CLICK",G.NOT_DISABLED="NOT_DISABLED",G.NOT_PRESENT="NOT_PRESENT",G.PRESENT="PRESENT",($=W||(W={})).ASSET="ASSET",$.CARTOON="CARTOON",$.NONE="NONE",$.URL="URL",(K=V||(V={})).INSIDE="INSIDE",K.OUTSIDE="OUTSIDE",(z=j||(j={})).TOP_LEFT="TOP_LEFT",z.TOP_CENTER="TOP_CENTER",z.TOP_RIGHT="TOP_RIGHT",z.BOTTOM_RIGHT="BOTTOM_RIGHT",z.BOTTOM_CENTER="BOTTOM_CENTER",z.BOTTOM_LEFT="BOTTOM_LEFT",z.CENTER="CENTER",(J=Y||(Y={})).GOOGLE="GOOGLE",J.STANDARD="STANDARD",(Z=X||(X={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",Z.DISMISS="DISMISS",(q=Q||(Q={})).DISMISS="DISMISS",q.NONE="NONE",(te=ee||(ee={})).DEFAULT="DEFAULT",te.PLAINTEXT="PLAINTEXT",(ie=se||(se={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",ie.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",ie.NONE="NONE",(oe=ne||(ne={})).BUBBLE="BUBBLE",oe.END="END",oe.ERROR="ERROR",oe.FLAG="FLAG",(ae=re||(re={})).MANUAL="MANUAL",ae.NONE="NONE",ae.SYNTHETIC="SYNTHETIC",(le=ce||(ce={})).BUBBLE="BUBBLE",le.HIDDEN="HIDDEN",le.MODAL="MODAL",le.TOOLTIP="TOOLTIP",(he=de||(de={})).ABOVE="ABOVE",he.BELOW="BELOW",he.LEFT="LEFT",he.RIGHT="RIGHT",(Ee=ue||(ue={})).CLOSE_FLOW="CLOSE_FLOW",Ee.EVAL_JS="EVAL_JS",Ee.GO_TO_STEP="GO_TO_STEP",Ee.NAVIGATE="NAVIGATE",Ee.SET_ATTRIBUTE="SET_ATTRIBUTE",Ee.SNOOZE="SNOOZE",Ee.START_FLOW="START_FLOW",(Se=Te||(Te={})).NEW_TAB="NEW_TAB",Se.SAME_TAB="SAME_TAB",(we=fe||(fe={})).SET="SET",we.SET_DATETIME="SET_DATETIME",we.SET_DATETIME_ONCE="SET_DATETIME_ONCE",we.SET_ONCE="SET_ONCE",we.ADD="ADD",we.SUBTRACT="SUBTRACT",we.APPEND="APPEND",we.PREPEND="PREPEND",we.REMOVE="REMOVE",we.UNSET="UNSET",(ge=pe||(pe={})).MULTILINE_TEXT="MULTILINE_TEXT",ge.MULTIPLE_CHOICE="MULTIPLE_CHOICE",ge.NPS="NPS",ge.SCALE="SCALE",ge.STARS="STARS",ge.TEXT="TEXT",(Ce=Ie||(Ie={})).ACTION="ACTION",Ce.ANNOUNCEMENTS="ANNOUNCEMENTS",Ce.ASSISTANT="ASSISTANT",Ce.CHECKLIST="CHECKLIST",Ce.CONTACT="CONTACT",Ce.DIVIDER="DIVIDER",Ce.FLOWS="FLOWS",Ce.KNOWLEDGE_BASE="KNOWLEDGE_BASE",Ce.MESSAGE="MESSAGE",Ce.SUBPAGE="SUBPAGE",(ke=me||(me={})).CRISP="CRISP",ke.CUSTOM="CUSTOM",ke.FRESHCHAT="FRESHCHAT",ke.HELPSCOUT="HELPSCOUT",ke.HUBSPOT="HUBSPOT",ke.INTERCOM="INTERCOM",ke.ZENDESK="ZENDESK",ke.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ue=Ae||(Ae={})).BUTTON="BUTTON",Ue.INPUT="INPUT",(Re=Le||(Le={})).SILENT="SILENT",Re.BADGE="BADGE",Re.POPOUT="POPOUT",(ve=Ne||(Ne={})).LAUNCHER_CLICK="LAUNCHER_CLICK",ve.LAUNCHER_HOVER="LAUNCHER_HOVER",ve.TARGET_CLICK="TARGET_CLICK",ve.TARGET_HOVER="TARGET_HOVER",ve.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",ve.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(ye=Oe||(Oe={})).ACTIVATE="ACTIVATE",ye.DEACTIVATE="DEACTIVATE",ye.NEVER="NEVER",(be=_e||(_e={})).AUTO="AUTO",be.TOP="TOP",be.RIGHT="RIGHT",be.BOTTOM="BOTTOM",be.LEFT="LEFT",(Me=De||(De={})).START="START",Me.CENTER="CENTER",Me.END="END",(Be=Fe||(Fe={})).PERCENT="PERCENT",Be.PX="PX",(xe=Pe||(Pe={})).BEACON="BEACON",xe.BUTTON="BUTTON",xe.HIDDEN="HIDDEN",xe.ICON="ICON",(Ge=He||(He={})).LAUNCHER="LAUNCHER",Ge.TARGET="TARGET",($e=We||(We={})).BODY_FIRST="BODY_FIRST",$e.BODY_LAST="BODY_LAST",$e.ELEMENT_FIRST="ELEMENT_FIRST",$e.ELEMENT_LAST="ELEMENT_LAST",$e.ELEMENT_BEFORE="ELEMENT_BEFORE",$e.ELEMENT_AFTER="ELEMENT_AFTER",(Ke=Ve||(Ve={})).START="START",Ke.CENTER="CENTER",Ke.SPACE_BETWEEN="SPACE_BETWEEN",(ze=je||(je={})).NONE="NONE",ze.LIKE="LIKE",ze.SCALE="SCALE",(Je=Ye||(Ye={})).ACTIVE="ACTIVE",Je.COMPLETED="COMPLETED",Je.ENDED="ENDED",Je.NOT_SEEN="NOT_SEEN",(Ze=Xe||(Xe={})).HIGHLIGHT="HIGHLIGHT",Ze.MODAL="MODAL",Ze.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Qe={customInputs:[],customNavigate:null,urlFilter:null,customScrollIntoView:null,scrollPadding:null,inferenceAttributeNames:["data-for","data-id","data-testid","data-test-id","for","id","name","placeholder","role"],inferenceAttributeFilters:{id:[e=>!e.match(/\d$/)],"data-id":[e=>!e.match(/\d$/)]},inferenceClassNameFilters:[e=>!e.startsWith("css-")],baseZIndex:1234500,evalJsDisabled:!1};function qe(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function et(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function tt(){let e=d();if(Qe.urlFilter){if(e=Qe.urlFilter(e),"string"!=typeof e)throw new o("Userflow.js: URL filter returned non-string value. Please check your userflow.setUrlFilter() implementation.");try{new URL(e)}catch(t){throw new o("Userflow.js: URL filter returned an invalid URL. Please check your userflow.setUrlFilter() implementation.\nReturned URL: "+e+"\nError message: "+t.message)}}return e}let st="";try{st=localStorage.getItem("debug")||""}catch(Tt){}const it=st.split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),nt=rt("log");let ot;function rt(e){return function(t,...s){if(it){const i=performance.now(),n=ot?Math.round(i-ot):0;ot=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#1a57e6;","","color:#1a57e6;",...s)}}}nt.group=rt("group"),nt.groupCollapsed=rt("groupCollapsed"),nt.groupEnd=function(){it&&console.groupEnd()};const at=()=>n((()=>import("./ResourceCenterApp.js").then((function(e){return e.R}))),[new URL("ResourceCenterApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("flow-host.styl.js",import.meta.url).toString(),new URL("bubble-frame.styl.js",import.meta.url).toString(),new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString(),new URL("stylesheets.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("vendor.obj-str.js",import.meta.url).toString(),new URL("use-window-resize.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("logomark.js",import.meta.url).toString(),new URL("ChecklistUI.js",import.meta.url).toString(),new URL("BubbleToolbar.js",import.meta.url).toString(),new URL("use-element-rect.js",import.meta.url).toString()]);function ct(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class lt{constructor(e){this.observers=new Set,this._value=e}get value(){return this._value}update(e){if(e!==this._value){this._value=e;for(const e of this.observers)e()}}observe(e){return this.observers.add(e),()=>this.observers.delete(e)}}const dt=["page:before-change","page:change","turbo:before-cache","turbo:load","turbo:visit","turbolinks:before-cache","turbolinks:load","turbolinks:visit"],ht=()=>n((()=>import("./BannerApp.js")),[new URL("BannerApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("vendor.obj-str.js",import.meta.url).toString(),new URL("stylesheets.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString(),new URL("bubble-frame.styl.js",import.meta.url).toString(),new URL("flow-host.styl.js",import.meta.url).toString(),new URL("use-selector-element-monitoring.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("use-window-resize.js",import.meta.url).toString(),new URL("use-element-rect.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]),ut=import.meta.url;class Et{constructor(){this.clientToken=null,this.externalId=null,this.signature=null,this.groupId=null,this.groupSignature=null,this._socketStatus="disconnected",this.socket=null,this.channel=null,this.featureFlags=new Set,this.logrocketAppId=null,this.debounceInactiveDisconnectTimeout=void 0,this.inBatch=!1,this.endBatchTimeout=void 0,this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=0,this.clientClock=1,this.serverClock=1,this.flowSession=null,this.flowSessionClock=0,this.checklistSession=null,this.checklistExpanded=!1,this.checklistExpandPending=!1,this.checklistSessionClock=0,this.bannerSession=null,this.resourceCenterSession=null,this.resourceCenterOpen=!1,this.resourceCenterLauncherHidden=!1,this.launcherSessions=[],this.activeLauncherFlowId=null,this.notifications=[],this.notificationIdCounter=0,this.sessionStorageState=null,this.clientContext=null,this.flushUrlChangeTimeout=void 0,this.onFirstIdentifyRun=!1,this.onFirstIdentifyTimeout=void 0,this.firstIdentifyCallback=null,this.ui=null,this.unackedTasks=new Set,this.clientConditions=new Map,this.trackers=new Map,this.conditionWaitTimers=new Map,this.listeners=new Map,this.targetEnv=null,this.idempotencyKeysSeen=new Set,this.testUserIdentified=!1,this.cspIssueReported=!1,this.uiDisabled=!1,this.audio=null,this.audioReady=!1,this.pageTrackingDisabled=!1,this.refCounter=1,this.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{nt(`builder ${e.kind} message received`,e);const t="idempotencyKey"in e&&"string"==typeof e.idempotencyKey?e.idempotencyKey:null;if(t&&this.idempotencyKeysSeen.has(t))return;const s=()=>{t&&this.idempotencyKeysSeen.add(t)};switch(e.kind){case"userflow:selectElement":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:selectElementAck",idempotencyKey:e.idempotencyKey}),void this.setSessionStorageState((t=>({...t,isTargetTab:!0,activeApp:"elementSelection",elementSelection:{mode:"select",elementType:e.elementType}})));case"userflow:selectElementCancel":return void this.setSessionStorageState((e=>({...e,activeApp:null,elementSelection:null})));case"userflow:startFlowWithToken":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:startFlowWithTokenAck",idempotencyKey:e.idempotencyKey}),this.setSessionStorageState((e=>({...e,isTargetTab:!0,activeApp:null,testStartConditionToken:void 0}))),c.setItem("previewFlowId",e.flowId),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void(e.testStartCondition?this.setSessionStorageState((t=>({...t,activeApp:"startConditionTesting",testStartConditionToken:e.token}))):this.onceIdentified((()=>{if(this.startFlowWithToken(e.token),e.isResourceCenter){const t=()=>{const s=this.resourceCenterSession;s&&s.draftMode&&s.flow.id===e.flowId&&(this.openResourceCenter(),this.off("resourceCenterChanged",t))};this.on("resourceCenterChanged",t),t()}})));case"userflow:testTracker":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:testTrackerAck",idempotencyKey:e.idempotencyKey}),this.setSessionStorageState((e=>({...e,isTargetTab:!0}))),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void this.setSessionStorageState((t=>({...t,activeApp:"trackerTesting",trackerTesting:{trackerName:e.trackerName,token:e.token,events:0}})));case"userflow:testTrackerCancel":return void this.setSessionStorageState((e=>({...e,activeApp:null,trackerTesting:null})))}},this.onUrlChange=()=>{this.externalId&&(window.clearTimeout(this.flushUrlChangeTimeout),this.flushUrlChangeTimeout=window.setTimeout((()=>this.flushUrlChange()),50))},this.onUserActivity=()=>this.ensureConnected(),this.remountIfNecessary=()=>{this.ui?.container&&!document.contains(this.ui.container)&&(nt("remounting UI because container was missing"),this.remount())},nt("constructor, build=1004175"),p(this.onUrlChange),this.setTargetEnv(new C),this.checkTestUserAtBoot(),this.toggleUI();for(const e of dt)document.addEventListener(e,this.remountIfNecessary)}get socketStatus(){return this._socketStatus}destroy(){nt("destroy"),this.reset(),g(this.onUrlChange),this.destroyTargetEnv();for(const e of dt)document.removeEventListener(e,this.remountIfNecessary)}setTargetEnv(e){this.destroyTargetEnv(),this.targetEnv=e,e.onBuilderMessage(this.onBuilderMessage)}destroyTargetEnv(){this.targetEnv&&(this.targetEnv.destroy(),this.targetEnv=null)}getTargetEnv(){if(!this.targetEnv)throw new o("Userflow.js: Cannot call getTargetEnv when protocol is not set");return this.targetEnv}setSessionStorageState(e){const t=e(this.getSessionStorageState());c.setItem("userflowClientState",JSON.stringify(t)),this.sessionStorageState=t,this.toggleUI()}getSessionStorageState(){let e=this.sessionStorageState;if(!e){const t=c.getItem("userflowClientState");if(t)try{e=JSON.parse(t)}catch(Tt){console.error("Userflow.js: Parse ElementSelectionState error:",Tt)}e||(e={testUser:null,activeApp:null,elementSelection:null,trackerTesting:null}),this.sessionStorageState=e}return e}checkTestUserAtBoot(){const e=this.getSessionStorageState().testUser;e&&(nt("checkTestUserAtBoot identifying test user"),this.identifyTestUser(e))}async identifyTestUser(e){this.setSessionStorageState((t=>({...t,testUser:e}))),this.reset(),this.init(e.clientToken),this.testUserIdentified=!0,this.externalId=e.id;const t=[this.identify(e.id,{name:e.name,email:e.email,signed_up_at:{set_once:(new Date).toISOString(),data_type:"datetime"}},{signature:e.signature})],{group:s}=e;s&&(this.groupId=s.id,t.push(this.group(s.id,{name:s.name},{signature:s.signature}))),await Promise.all(t)}resetTestUser(){this.setSessionStorageState((e=>({...e,testUser:null})))}init(e){if(nt("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?nt("init() ignoring new token since a test user has been identified"):(this.clientToken&&(nt("init() resetting due to new client token"),this.reset()),this.clientToken=e))}ensureInit(){if(!this.clientToken)throw new o("You must call userflow.init() first")}ensureIdentified(){if(this.ensureInit(),!this.externalId)throw new o("You must call userflow.identify() first");return this.externalId}ensureGroup(){if(this.ensureIdentified(),!this.groupId)throw new o("You must call userflow.group() first");return this.groupId}ensureConnected(){if(!this.clientToken||!this.externalId)return;if(this.debounceInactiveDisconnect(),this.socket)return;this._socketStatus="connecting",nt("connecting to socket");let t=Qe.serverEndpoint||"e.userflow.com";"js.getuserflow.com"===new URL(ut).hostname&&"e.userflow.com"===t&&(t="e.getuserflow.com");const s="wss://"+t+"/end-users/"+this.clientToken+"/socket";this.socket=new e(s,{reconnectAfterMs:e=>[100,500,1e3,5e3][e-1]||1e4,timeout:2e4}),this.socket.connect(),this.socket.onOpen((()=>{nt("socket opened")})),this.socket.onClose((()=>{this.emit("private:disconnect")})),this.socket.onError((e=>{console.log("Userflow.js socket error",e),this.reportCspIssue()})),this.channel=this.socket.channel(`end_users:${this.externalId}`,(()=>this.makeChannelJoinPayload())),this.channel.join().receive("ok",(e=>{this.logrocketAppId=e.logrocketAppId,this.featureFlags=new Set(e.featureFlags),nt("channel joined"),"connected"!==this._socketStatus&&(this._socketStatus="connected")})).receive("error",(e=>{["company_closed","invalid_client_token","invalid_user_external_id","incorrect_user_signature","rate_limit_exceeded","user_signature_required"].includes(e.code)?(console.error(`Userflow.js resetting due to: [${e.code}] ${e.message}`),this.reset(),this.clientToken=null):"invalid_protocol_version"===e.code?(console.error(`Userflow.js destroying due to: [${e.code}] ${e.message}`),this.destroy()):console.log("Userflow.js channel join error",e)})),this.channel.on("server_message",(e=>this.handleServerMessage(e))),this.channel.on("server_error",(e=>{console.log(`Userflow.js server error (${e.code}): ${e.message}`+(e.details&&e.details.length>0?"\nDetails:\n"+e.details.map((e=>(e.path?`${e.path}: `:"")+e.message)):""))}))}makeChannelJoinPayload(){const e=this.buildClientContext();this.clientContext=e;const t={protocolVersion:2,userflowClientBuild:"1004175",signature:this.signature,groupExternalId:this.groupId,groupSignature:this.groupSignature,flowSessionId:this.flowSession?.id||null,checklistSessionId:this.checklistSession?.id||null,bannerSessionId:this.bannerSession?.id||null,resourceCenterSessionId:this.resourceCenterSession?.id||null,launchers:this.launcherSessions.map((e=>({flowId:e.flow.id}))),trackers:Array.from(this.trackers.values()).map((e=>({flowId:e.tracker.flowId}))),hasDraftSession:this.hasDraftSession(),clientConditions:Array.from(this.clientConditions.values()).map((e=>({conditionId:e.condition.id,isTrue:e.isTrue}))),previewFlowId:c.getItem("previewFlowId"),clientContext:e};return nt("channel join payload",t),t}disconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.socket&&this.socket.disconnect(),this._socketStatus="disconnected",this.socket=null,this.channel=null}debounceInactiveDisconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.debounceInactiveDisconnectTimeout=window.setTimeout((()=>{this.hasDraftSession()||this.assistantMessageInProgress?this.debounceInactiveDisconnect():(nt("disconnecting from socket due to inactivity"),this.disconnect())}),3e5)}hasDraftSession(){return!!this.flowSession?.draftMode||!!this.checklistSession?.draftMode||!!this.bannerSession?.draftMode||!!this.resourceCenterSession?.draftMode||this.launcherSessions.some((e=>e.draftMode))}async send(e,{batch:t,endBatch:s,handlesRejection:i}={}){return this.inBatch&&["ToggleClientCondition","UpdateClientContext"].includes(e.kind)||this.checkPushRateLimit(),this.ensureConnected(),t&&!this.inBatch&&(this.inBatch=!0,this.sendRaw({kind:"BeginBatch"})),this.inBatch&&(window.clearTimeout(this.endBatchTimeout),s?this.endBatch():this.endBatchTimeout=window.setTimeout((()=>{this.endBatch()}),50)),this.sendRaw(e,{handlesRejection:i})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel){const s=`Userflow.js: send() should not be called if channel is not set. Message kind=${e.kind}`;if(t)throw Error(s);return void console.log(s,"\nClient message:",e)}nt(`push ${e.kind} message`,e);const n=this.clientClock,r=()=>{this.serverClock=n,this.channel?.off("phx_error",a)},a=this.channel.on("phx_error",(s=>{r();const n=`Userflow.js send ${e.kind} got phx_error`;"connected"===this._socketStatus&&console.log(n,"\nClient message:",e,"\nError:",s),t&&i(new o(n))}));this.channel.push("client_message",e).receive("ok",(e=>{r(),s(e)})).receive("error",(s=>{r();const n=`Userflow.js error reply (${s.code}): ${s.message}`;console.log(n,"\nClient message:",e,"\nError:",s),t&&i(new o(n,s.code,s.message))}))}))}endBatch(){this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}checkPushRateLimit(){const e=Date.now();if(this.pushRateLimitMinuteExpires<e&&(this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=e+6e4),this.pushRateLimitMinute>=100)throw new o("This Userflow.js client has reached a maximum of 100 operations in the last 1 minute. This is usually due to one of the following:\n\n - Excessive calls to Userflow.js. Check if any of userflow.track(), userflow.identify(), userflow.updateUser() or similar are called repeatedly.\n - The URL changing too frequently. Look into https://userflow.com/docs/userflow-js#seturlfilter and filter out the changing part of the URL.\n - The user legitimately being very active, in which case you can just ignore this error.\n \n If in doubt, reach out to us at support@userflow.com.");this.pushRateLimitMinute++}handleServerMessage(e){nt(`received ${e.kind} message`,e);const{serverClock:t,flowSession:s,flowSessionClock:i,checklistSession:n,checklistSessionClock:o,bannerSession:r,resourceCenterSession:a}=this;switch(e.kind){case"CheckSessionsAck":case"ServerDebug":return;case"AddLauncher":{const{session:t}=e,s=this.launcherSessions.findIndex((e=>e.flow.id===t.flow.id));return this.launcherSessions=-1===s?[...this.launcherSessions,t]:[...this.launcherSessions.slice(0,s),t,...this.launcherSessions.slice(s+1)],void this.toggleUI()}case"AddTracker":return void this.addTracker(e.tracker);case"AssistantMessageEventWrapper":return void this.emit("private:assistantMessageEvent",e);case"CancelConditionWaitTimer":return window.clearTimeout(this.conditionWaitTimers.get(e.conditionId)),void this.conditionWaitTimers.delete(e.conditionId);case"ChecklistTaskCompleted":return void this.unackedTasks.add(e.taskCvid);case"ForceGoToStep":return i>t?void nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`):void(s?.id===e.sessionId&&this.emit("gotostep",{session:s,step:{id:e.stepId}}));case"RemoveLauncher":return void(this.removeLauncher(e.flowId)&&this.toggleUI());case"RemoveTracker":return void this.removeTracker(e.flowId);case"SetBannerSession":return this.setBannerSession(e.session),void this.toggleUI();case"SetChecklistSession":return void(o<=t||n?.id===e.session.id?(this.setChecklistSession(e.session,t),this.toggleUI()):nt(`ignoring ${e.kind} message due to stale clock checklistSessionClock=${o} > serverClock=${t}`));case"SetFlowSession":return void(i<=t||s?.id===e.session.id?(this.setFlowSession(e.session,t),this.toggleUI()):nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`));case"SetResourceCenterSession":return this.setResourceCenterSession(e.session),void this.toggleUI();case"StartConditionWaitTimer":if(!this.conditionWaitTimers.has(e.conditionId)){const t=window.setTimeout((()=>{this.conditionWaitTimers.delete(e.conditionId),this.send({kind:"FireConditionWaitTimer",conditionId:e.conditionId},{batch:!0})}),1e3*parseFloat(e.waitTime));this.conditionWaitTimers.set(e.conditionId,t)}return;case"TestStartConditionSuccess":return void this.emit("private:testStartConditionSuccess");case"TrackClientCondition":return void this.trackClientCondition(e.condition);case"UnsetBannerSession":return void(r?.id===e.sessionId&&(this.setBannerSession(null),this.toggleUI()));case"UnsetChecklistSession":return o>t?void nt(`ignoring ${e.kind} message due to stale clock checklistSessionClock=${o} > serverClock=${t}`):void(n?.id===e.sessionId&&(this.setChecklistSession(null,t),this.toggleUI()));case"UnsetFlowSession":return i>t?void nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`):void(s?.id===e.sessionId&&(this.setFlowSession(null,t),this.toggleUI()));case"UnsetResourceCenterSession":return void(a?.id===e.sessionId&&(this.setResourceCenterSession(null),this.toggleUI()));case"UntrackClientCondition":return void this.untrackClientCondition(e.conditionId);default:return void console.warn("Userflow.js: Received unknown message",e)}}async identify(e,t={},{signature:s}={}){if(nt("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)nt("identify() ignored since a test user has been identified");else{if("number"==typeof e)e=String(e);else if(!e||"string"!=typeof e)throw new o(`userflow.identify: First argument must be a non-empty string representing the user's ID in your database. Value received: ${JSON.stringify(e)}`);this.externalId&&e!==this.externalId&&(nt("identify resetting due to new externalId"),this.reset()),this.externalId=e,this.signature=s||null,this.observeUserActivity(),await Promise.all([this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(t)},{batch:!0}),this.onFirstIdentify()]),this.emit("private:identified")}}async identifyAnonymous(e={},s={}){if(!a.isSupported())throw new o("userflow.identifyAnonymous() is not supported when localStorage access is denied.");const i="anonymousId";let n=a.getItem(i);n||(n="anon-"+t(),a.setItem(i,n)),await this.identify(n,e,s)}async updateUser(e={},t={}){nt("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if(nt("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)nt("group() ignored since a test user has been identified");else{if("number"==typeof e)e=String(e);else if(!e||"string"!=typeof e)throw new o(`userflow.group: First argument must be a non-empty string representing the group's ID in your database. Value received: ${JSON.stringify(e)}`);this.groupId=e,this.groupSignature=s||null,await this.send({kind:"UpsertGroup",groupExternalId:e,groupSignature:this.groupSignature,groupAttributes:this.normalizeAttributes(t),membershipAttributes:this.normalizeAttributes(i)},{batch:!0})}}async updateGroup(e={},t={}){nt("updateGroup");const s=this.ensureGroup();await this.send({kind:"UpsertGroup",groupExternalId:s,groupSignature:this.groupSignature,membershipAttributes:this.normalizeAttributes(t.membership),groupAttributes:this.normalizeAttributes(e)},{batch:!0})}normalizeAttributes(e){if(null==e)return{};if("object"!=typeof e)throw new o("Userflow: 'attributes' must be an object.");const t={};for(const s in e){if(!e.hasOwnProperty(s))continue;if("traits"===s){const i=e[s];Object.assign(t,this.extractLegacyTraits(i));continue}let i=e[s];if("string"==typeof i||"number"==typeof i||"boolean"==typeof i||null==i||Array.isArray(i))t[s]=this.normalizeAttributeLiteralOrList(s,i);else{if("object"!=typeof i||null==i)throw new o(`Userflow: Invalid value for '${s}' attribute.`);if("set"in i)t[s]={set:this.normalizeAttributeLiteralOrList(s,i.set),dataType:this.normalizeDataType(s,i.data_type||i.dataType)};else if("set_once"in i||"setOnce"in i)t[s]={setOnce:this.normalizeAttributeLiteralOrList(s,i.set_once??i.setOnce),dataType:this.normalizeDataType(s,i.data_type||i.dataType)};else if("add"in i){const e=i.add;if("string"!=typeof e&&"number"!=typeof e)throw new o(`Userflow: Invalid 'add' value for '${s}' attribute. Must be a number or string.`);t[s]={add:e}}else if("subtract"in i){const e=i.subtract;if("string"!=typeof e&&"number"!=typeof e)throw new o(`Userflow: Invalid 'subtract' value for '${s}' attribute. Must be a number or string.`);t[s]={subtract:e}}else if("append"in i)t[s]={append:this.normalizeAttributeLiteralOrList(s,i.append)};else if("prepend"in i)t[s]={prepend:this.normalizeAttributeLiteralOrList(s,i.prepend)};else{if(!("remove"in i))throw new o(`Userflow: Invalid value for '${s}' attribute.`);t[s]={remove:this.normalizeAttributeLiteralOrList(s,i.remove)}}}}return t}normalizeAttributeLiteralOrList(e,t){return Array.isArray(t)?t.map((t=>this.normalizeAttributeLiteral(e,t))):this.normalizeAttributeLiteral(e,t)}normalizeAttributeLiteral(e,t){if(null==t)return null;if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;throw new o(`Userflow: Invalid value for '${e}' attribute.`)}normalizeDataType(e,t){if(!t)return null;switch(t){case"string":return O.STRING;case"number":return O.NUMBER;case"boolean":return O.BOOLEAN;case"datetime":return O.DATETIME}throw new o(`Userflow: Invalid data_type for '${e}' attribute.`)}extractLegacyTraits(e){if(!e)return{};if(!Array.isArray(e)){const t=[];for(const s in e)e.hasOwnProperty(s)&&t.push({name:s,value:e[s]});e=t}return e.reduce(((e,{name:t,value:s,dataType:i})=>{if("string"!=typeof t||t.length>100||!t.match(/^[a-z0-9_]+$/))return this.warn("Userflow.identify: Invalid trait name (must be string, no more than 100 characters, and only consist of a-z, 0-9 and underscores). The trait will be ignored. Name was:",t),e;if("string"==typeof s);else if("boolean"==typeof s)i||(i="boolean"),s=s?"true":"false";else{if("number"!=typeof s)return this.warn(`userflow.identify: The value of trait '${t}' is invalid (must be a string, a boolean or a number). The trait will be ignored. Value was:`,s),e;i||(i=Number.isInteger(s)?"integer":"decimal"),s=String(s)}let n=null;if(i)switch(i){case"string":n=O.STRING;break;case"boolean":n=O.BOOLEAN;break;case"integer":case"decimal":n=O.NUMBER;break;case"datetime":n=O.DATETIME;break;default:return this.warn(`userflow.identify: The data type of trait '${t}' is invalid (must be a 'string', 'boolean', 'integer', 'decimal' or 'datetime'). The trait will be ignored. Data type was:`,i),e}return e[t]={set:s,dataType:n},e}),{})}async track(e,t={},{userOnly:s}={}){nt(`track '${e}'`,t),this.ensureIdentified(),await this.send({kind:"TrackEvent",userOnly:!!s,name:e,attributes:this.normalizeEventAttributes(t)},{batch:!0})}normalizeEventAttributes(e){const t=this.normalizeAttributes(e);for(const s in t){if(!t.hasOwnProperty(s))continue;const e=t[s];if(null!=e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e&&!Array.isArray(e)&&!("set"in e))throw new o(`Userflow: Invalid value for '${s}' attribute. Event attributes only support literal values, list values and 'set' changes.`)}return t}onFirstIdentify(){this.onFirstIdentifyRun||(this.onFirstIdentifyRun=!0,this.onFirstIdentifyTimeout=window.setTimeout((()=>{this.trackPageViewed(),this.firstIdentifyCallback?(this.firstIdentifyCallback(),this.firstIdentifyCallback=null):this.checkUrlForStartFlow()}),0))}onceIdentified(e){this.isIdentified()?e():this.firstIdentifyCallback=e}checkUrlForStartFlow(){const e=new URL(d()),t=e.searchParams.get("userflow")||e.searchParams.get("studio1_flow")||e.searchParams.get("studio1_walkthrough");t&&(nt(`url contained flow ${t}`),this.startFlow({flowId:t,startReason:L.LINK,batch:!0}),e.searchParams.delete("userflow"),e.searchParams.delete("studio1_flow"),e.searchParams.delete("studio1_walkthrough"),window.history.replaceState({},"",e.toString()),this.clientContext=this.buildClientContext(),this.pushUpdateClientContext())}flushUrlChange(){const e=this.buildClientContext();this.clientContext&&e.pageUrl===this.clientContext.pageUrl||(this.clientContext=e,this.pushUpdateClientContext(),this.trackPageViewed(),this.checkUrlForStartFlow())}async trackPageViewed(){this.pageTrackingDisabled||this.track("page_viewed",{})}buildClientContext(){return{pageUrl:tt(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight}}pushUpdateClientContext(){this.send({kind:"UpdateClientContext",clientContext:this.clientContext},{batch:!0})}ackCompletedTask(e){this.unackedTasks.delete(e)}taskIsUnacked(e){return this.unackedTasks.has(e)}isIdentified(){return null!=this.externalId}on(e,t){let s=this.listeners.get(e);s||(s=new Set,this.listeners.set(e,s)),s.add(t)}off(e,t){const s=this.listeners.get(e);s&&s.delete(t)}emit(e,...t){const s=this.listeners.get(e);if(s){Array.from(s).forEach((e=>e(...t)))}}observeUserActivity(){document.addEventListener("mouseover",this.onUserActivity),document.addEventListener("pointerdown",this.onUserActivity),document.addEventListener("keydown",this.onUserActivity)}unobserveUserActivity(){document.removeEventListener("mouseover",this.onUserActivity),document.removeEventListener("pointerdown",this.onUserActivity),document.removeEventListener("keydown",this.onUserActivity)}reset(){nt("reset"),this.externalId=null,this.groupId=null,this.sessionStorageState=null,this.setFlowSession(null,0),this.setChecklistSession(null,0),this.setBannerSession(null),this.setResourceCenterSession(null),this.launcherSessions=[],this.activeLauncherFlowId=null,this.notifications=[],this.unackedTasks=new Set,this.onFirstIdentifyRun=!1,window.clearTimeout(this.onFirstIdentifyTimeout),this.onFirstIdentifyTimeout=void 0,this.clientContext=null,this.unobserveUserActivity(),window.clearTimeout(this.flushUrlChangeTimeout),this.flushUrlChangeTimeout=void 0,this.clientConditions.forEach(((e,t)=>{this.untrackClientCondition(t)})),this.firstIdentifyCallback=null,this.testUserIdentified=!1,a.removeItem("anonymousId"),this.unmountUI(),this.disconnect(),this.inBatch=!1,window.clearTimeout(this.endBatchTimeout),this.endBatchTimeout=void 0,this.clientClock=1,this.serverClock=1,this.titleMonitored=void 0,this.titleObserver&&(this.titleObserver.disconnect(),this.titleObserver=void 0)}async startFlow({flowId:e,stepCvid:t,startReason:s,once:i,batch:n,replaceCurrent:o}){if(this.ensureIdentified(),o&&this.flowSession&&this.endFlow(this.flowSession,{endReason:m.REPLACED,batch:!0}),nt(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return nt("startFlow matches current checklist, so showing it instead"),void this.showChecklist();const r={kind:"StartFlow",flowId:e,stepCvid:t,startReason:s,once:!!i};await this.send(r,{batch:n})}async startFlowWithToken(e){this.ensureIdentified(),nt("startFlowWithToken",{token:e}),await this.send({kind:"StartFlowWithToken",token:e},{batch:!0})}optimisticClockUIUpdate(e){this.clientClock++,e(),this.toggleUI()}async showChecklist(){this.resourceCenterEmbedsChecklist()?this.openResourceCenter():(this.unmarkExpandPending(),this.checklistSession&&!this.checklistExpanded&&(this.ensureIdentified(),this.checklistExpanded=!0,this.toggleUI(),c.setItem(`checklistExpanded:${this.checklistSession.id}`,"1"),await this.send({kind:"ShowChecklist",sessionId:this.checklistSession.id},{batch:!0})))}async hideChecklist(){this.resourceCenterEmbedsChecklist()?this.closeResourceCenter():this.checklistSession&&this.checklistExpanded&&(this.ensureIdentified(),this.checklistExpanded=!1,this.toggleUI(),c.removeItem(`checklistExpanded:${this.checklistSession.id}`),await this.send({kind:"HideChecklist",sessionId:this.checklistSession.id},{batch:!0}))}async unmarkExpandPending(){this.checklistSession&&this.checklistExpandPending&&(this.checklistExpandPending=!1,await this.send({kind:"UnmarkExpandPending",sessionId:this.checklistSession.id},{batch:!0}))}async openResourceCenter(){this.resourceCenterEmbedsChecklist()&&this.unmarkExpandPending(),this.resourceCenterSession&&!this.resourceCenterOpen&&(this.ensureIdentified(),this.resourceCenterOpen=!0,this.toggleUI(),this.emit("resourceCenterChanged"),c.setItem(`resourceCenterOpen:${this.resourceCenterSession.id}`,"1"),await this.send({kind:"OpenResourceCenter",sessionId:this.resourceCenterSession.id},{batch:!0}))}async closeResourceCenter(){this.resourceCenterSession&&this.resourceCenterOpen&&(this.ensureIdentified(),this.resourceCenterOpen=!1,this.toggleUI(),this.emit("resourceCenterChanged"),c.removeItem(`resourceCenterOpen:${this.resourceCenterSession.id}`),await this.send({kind:"CloseResourceCenter",sessionId:this.resourceCenterSession.id},{batch:!0}))}toggleResourceCenter(){this.resourceCenterOpen?this.closeResourceCenter():this.openResourceCenter()}setResourceCenterLauncherHidden(e){this.resourceCenterLauncherHidden=e,this.toggleUI()}getResourceCenterState(){if(!this.resourceCenterSession)return null;const e=this.resourceCenterEmbedsChecklist(),{checklistSession:t}=this,s=this.resourceCenterSession.version.resourceCenter?.blocks.find((e=>e.type===Ie.ANNOUNCEMENTS));return{isOpen:this.resourceCenterOpen,hasChecklist:e,uncompletedChecklistTaskCount:e&&t?ct(t):0,unreadAnnouncementCount:s?.unreadAnnouncementCount||0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Ie.CHECKLIST))}async endFlow(e,{endReason:t,batch:s}){this.ensureIdentified(),this.optimisticClockUIUpdate((()=>{const{clientClock:t}=this;this.flowSession?.id===e.id&&this.setFlowSession(null,t),this.checklistSession?.id===e.id&&this.setChecklistSession(null,t),this.bannerSession?.id===e.id&&this.setBannerSession(null),this.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===_.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===_.FLOW&&this.emit("flowEnded",{flow:n,endReason:t});const o={kind:"EndFlow",sessionId:e.id,endReason:t};await this.send(o,{batch:s})}async goToStep(e,t){nt("goToStep",e.id,t.name||t.id),this.ensureIdentified();const s=this.send({kind:"GoToStep",sessionId:e.id,stepId:t.id});e.currentStep=t,this.emit("gotostep",{session:e,step:t}),await s}async endAllFlows(){nt("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){nt("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===_.CHECKLIST&&this.endFlow(e,{endReason:m.USERFLOWJS})}setFlowSession(e,t=this.clientClock){const s=this.flowSession;this.flowSession=e,this.flowSessionClock=t,e&&!s&&(this.hideChecklist(),this.closeResourceCenter()),null==e&&this.originalActiveElement&&("function"==typeof this.originalActiveElement.focus&&this.originalActiveElement.focus(),this.originalActiveElement=void 0)}setChecklistSession(e,t=this.clientClock){const s=this.checklistSession;this.checklistSession=e,this.checklistSessionClock=t,null===e&&(this.checklistExpanded=!1,this.checklistExpandPending=!1),e&&e.id!==s?.id&&(this.checklistExpanded=!!c.getItem(`checklistExpanded:${e.id}`),e.expandPending&&(this.checklistExpandPending=!0)),this.emit("checklistChanged"),this.emit("resourceCenterChanged")}setBannerSession(e){this.bannerSession=e}setResourceCenterSession(e){const t=this.resourceCenterSession;e="function"==typeof e?e(this.resourceCenterSession):e,this.resourceCenterSession=e,null===e&&(this.resourceCenterOpen=!1),t&&t.id!==e?.id&&c.removeItem(`resourceCenterOpen:${t.id}`),e&&e.id!==t?.id&&(this.resourceCenterOpen=!!c.getItem(`resourceCenterOpen:${e.id}`)),this.emit("resourceCenterChanged")}launcherSeen(e){this.send({kind:"StartFlow",flowId:e,startReason:L.LAUNCHER_SEEN,once:!1})}activateLauncher(e){const t=this.activeLauncherFlowId&&this.launcherSessions.find((e=>e.flow.id===this.activeLauncherFlowId));t&&this.deactivateLauncher(t),this.activeLauncherFlowId=e.flow.id,this.toggleUI(),this.send({kind:"ActivateLauncher",flowId:e.flow.id})}deactivateLauncher(e){const{launcher:t}=e.version;e.flow.id===this.activeLauncherFlowId&&(t?.dismissOn===Oe.DEACTIVATE?this.dismissLauncher(e,{endReason:m.LAUNCHER_DEACTIVATED}):(this.activeLauncherFlowId=null,this.toggleUI()))}dismissLauncher(e,{endReason:t}){const s=e.flow.id;this.removeLauncher(s),this.toggleUI(),this.send({kind:"DismissLauncher",flowId:s,endReason:t})}removeLauncher(e){const t=this.launcherSessions.findIndex((t=>t.flow.id===e));return-1!==t&&(this.launcherSessions=[...this.launcherSessions.slice(0,t),...this.launcherSessions.slice(t+1)],e===this.activeLauncherFlowId&&(this.activeLauncherFlowId=null),!0)}async toggleUI(){const e=this.getSessionStorageState();this.flowSession||!this.checklistExpandPending&&!this.checklistSession?.version.checklist?.tasks.some((e=>this.taskIsUnacked(e.cvid)))||this.showChecklist(),e.isTargetTab&&this.monitorTitle(),this.emit("uistatechange"),this.shouldBeMounted()?await this.mountUI():this.unmountUI()}shouldBeMounted(){if(this.uiDisabled)return!1;return!!this.getSessionStorageState().activeApp||!!this.flowSession||!!this.checklistSession&&(this.checklistExpanded||!!this.checklistSession?.version.checklist?.launcherEnabled)||!!this.bannerSession||!!this.resourceCenterSession&&(this.resourceCenterOpen||!this.resourceCenterLauncherHidden)||this.launcherSessions.length>0||this.notifications.length>0}async mountUI(){if(!this.ui){const e=await this.createUI();this.shouldBeMounted()&&!this.ui&&(nt("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&(nt("unmount UI"),this.ui.unmount(),this.ui=null)}remount(){this.unmountUI(),this.toggleUI()}async createUI(){try{const e=n((()=>import("./ui.js")),[new URL("ui.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]);this.bannerSession&&ht(),this.resourceCenterSession&&at();const{RealUI:t}=await e;return new t(this)}catch(Tt){throw this.reportCspIssue(),Tt}}async trackClientCondition(e){if(this.clientConditions.has(e.id))return;nt("track client condition",e),this.clientConditions.set(e.id,{condition:e,isTrue:null});const{conditionTypes:t}=await n((()=>import("./flow-condition-types.js").then((function(e){return e.v}))),[new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString()]),s=t[e.type],i=this.clientConditions.get(e.id);i&&(i.untrack=s.track({sessionData:new lt([]),condition:e,callback:t=>{i.isTrue!==t&&(nt("client condition truthiness changed",t,i.condition),i.isTrue=t,this.send({kind:"ToggleClientCondition",conditionId:e.id,isTrue:t},{batch:!0}))}}))}untrackClientCondition(e){const t=this.clientConditions.get(e);t&&(nt("untrack client condition",t.condition),t.untrack&&t.untrack(),this.clientConditions.delete(e))}async addTracker(e){let t=this.trackers.get(e.flowId);t?t.tracker=e:this.trackers.set(e.flowId,{tracker:e,isTrue:!1});const{conditionTypes:s}=await n((()=>import("./flow-condition-types.js").then((function(e){return e.v}))),[new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString()]),i=this.trackers.get(e.flowId);if(!i)return;const{tracker:o}=i,{condition:r}=o,a=s[r.type];i.untrack&&i.untrack(),i.untrack=a.track({sessionData:new lt(o.data),condition:r,flipBackEvents:!0,callback:e=>{const t=i.isTrue;i.isTrue=e,!t&&e&&this.send({kind:"TrackTrackerEvent",token:o.token},{batch:!0})},description:`event tracker ${o.flowId}`}),this.emit("private:trackerStarted")}removeTracker(e){const t=this.trackers.get(e);t&&(t.untrack&&t.untrack(),this.trackers.delete(e),this.emit("private:trackerStopped"))}monitorTitle(){if(this.titleMonitored)return;this.titleMonitored=!0,this.fixTitle();const e=document.querySelector("title");if(e){const t=new MutationObserver((()=>{this.fixTitle()}));t.observe(e,{childList:!0}),this.titleObserver=t}}fixTitle(){const e=document.title,t="[Userflow Preview] "+e.replace(/\[Userflow Preview\] /,"");e!==t&&(document.title=t)}reportCspIssue(){const e=this.getSessionStorageState();!this.testUserIdentified&&!e.activeApp||this.cspIssueReported||(this.cspIssueReported=!0,nt("csp issue detected"),T({kind:"userflow:crxCspIssueDetected"}))}getAudio(){return this.audio||(this.audio=new Audio),this.audio}playAudio(e){if(document.hidden)return;const t=this.getAudio();e&&(t.src=e);const s=t.play();this.audioReady=!0,s&&s.catch((e=>{e.name}))}pauseAudio(){const e=this.audio;e&&!e.paused&&e.pause()}async getStepSpeech(e,t){return(await this.send({kind:"GetStepSpeechV2",syntheticVoice:e,text:t})).url}featureFlagEnabled(e){return this.featureFlags.has(e)}showNotification(e,t,s){const i={id:++this.notificationIdCounter,label:e,message:t,type:s};this.notifications=[...this.notifications,i],this.toggleUI()}dismissNotification(e){this.notifications=this.notifications.filter((t=>t.id!==e)),this.toggleUI()}warn(...e){console.warn(...e)}nextRef(){return this.refCounter++}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new Et;return{_stubbed:!1,init(t){e.init(t)},identify:(t,s={},i={})=>e.identify(t,s,i),identifyAnonymous:(t={},s={})=>e.identifyAnonymous(t,s),isIdentified:()=>e.isIdentified(),updateUser:(t,s={})=>e.updateUser(t,s),group:(t,s={},i={})=>e.group(t,s,i),updateGroup:(t,s={})=>e.updateGroup(t,s),track:(t,s={},i={})=>e.track(t,s,i),start:(t,{once:s}={})=>e.startFlow({flowId:t,startReason:L.USERFLOWJS,once:s}),startFlow:e=>(console.warn("Userflow.js: userflow.startFlow() has been deprecated. Use userflow.start() instead."),window.userflow.start(e)),startWalk:e=>(console.warn("Userflow.js: userflow.startWalk() has been deprecated. Use userflow.start() instead."),window.userflow.start(e)),endAll:()=>e.endAllFlows(),endChecklist:()=>e.endChecklist(),endAllFlows:()=>window.userflow.endAll(),async endFlow(){console.warn("Userflow.js: userflow.endFlow() has been deprecated and no longer has any effect.")},async endWalk(){console.warn("Userflow.js: userflow.endWalk() has been deprecated and no longer has any effect.")},openResourceCenter(){e.openResourceCenter()},closeResourceCenter(){e.closeResourceCenter()},toggleResourceCenter(){e.toggleResourceCenter()},setResourceCenterLauncherHidden(t){e.setResourceCenterLauncherHidden(t)},getResourceCenterState:()=>e.getResourceCenterState(),setWalkPosition(){console.warn("Userflow.js: userflow.setWalkPosition() has been deprecated and no longer has any effect.")},reset(){e.reset()},remount(){e.remount()},on(t,s){e.on(t,s)},off(t,s){e.off(t,s)},setCustomInputSelector(e){console.warn("Userflow.js: userflow.setCustomInputSelector() has been deprecated. Use userflow.registerCustomInput() instead. See docs: https://userflow.com/docs/userflow-js"),e&&Qe.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Qe.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Qe.customNavigate=e},setUrlFilter(e){Qe.urlFilter=e},setInferenceAttributeNames(e){Qe.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Qe.inferenceAttributeFilters[e]=qe(t)},setInferenceClassNameFilter(e){Qe.inferenceClassNameFilters=qe(e)},setScrollPadding(e){Qe.scrollPadding=e},setCustomScrollIntoView(e){Qe.customScrollIntoView=e},prepareAudio(){e.playAudio(null)},setShadowDomEnabled(e){console.warn("Userflow.js: userflow.setShadowDomEnabled() has been deprecated. Please remove this call from your Userflow.js snippet. Shadow DOM is supported by default now.")},setPageTrackingDisabled(t){e.pageTrackingDisabled=t},setBaseZIndex(e){Qe.baseZIndex=e},setServerEndpoint(e){Qe.serverEndpoint=e},disableEvalJs(){Qe.evalJsDisabled=!0},_setTargetEnv(t){e.setTargetEnv(t)}}}());window.userflow=e,window.studio1=e,function(){const e=window.userflow,t=window.USERFLOWJS_QUEUE;if(delete window.USERFLOWJS_QUEUE,!t||0===t.length)return;nt(`processing ${t.length} items in the queue`);for(const[s,i,n]of t){if("function"!=typeof e[s]){console.error(`Userflow.js: Invalid method '${s}' in queue`);continue}const t=e[s](...n);i&&t&&"function"==typeof t.then&&t.then(i.resolve,i.reject)}nt("queue processed")}()}export{N as $,Le as A,ht as B,me as C,Y as D,m as E,P as F,a as G,We as H,X as I,ne as J,ce as K,j as L,Q as M,de as N,Pe as O,Ne as P,_e as Q,at as R,L as S,dt as T,o as U,re as V,He as W,De as X,Fe as Y,je as Z,n as _,B as a,F as b,Qe as c,nt as d,D as e,H as f,tt as g,Ie as h,c as i,ct as j,se as k,ee as l,ue as m,Ae as n,p as o,_ as p,d as q,Te as r,l as s,et as t,g as u,fe as v,pe as w,lt as x,V as y,W as z};export default window.userflow;
|
|
1
|
+
import{S as e}from"./vendor.phoenix.js";import{v as t}from"./vendor.uuid.js";let s;const i={},n=function(e,t){if(!t)return e();if(void 0===s){const e=document.createElement("link").relList;s=e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}return Promise.all(t.map((e=>{if(e in i)return;i[e]=!0;const t=e.endsWith(".css"),n=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${n}`))return;const o=document.createElement("link");return o.rel=t?"stylesheet":s,t||(o.as="script",o.crossOrigin=""),o.href=e,document.head.appendChild(o),t?new Promise(((e,t)=>{o.addEventListener("load",e),o.addEventListener("error",t)})):void 0}))).then((()=>e()))};class o extends Error{constructor(e,t,s){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t,this.humanMessage=s}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}isSupported(){if("undefined"==typeof window)return!1;try{return null!=window[this.type]}catch{return!1}}getItem(e){return e=this.formatKey(e),this.isSupported()?window[this.type].getItem(e):null}setItem(e,t){e=this.formatKey(e),this.isSupported()&&window[this.type].setItem(e,t)}removeItem(e){if(e=this.formatKey(e),this.isSupported())return window[this.type].removeItem(e)}clear(){if(this.isSupported())return window[this.type].clear()}}const a=new r("localStorage"),c=new r("sessionStorage");function l(e){window.location.href=e}function d(){return window.location.href}var h,u,E;function T(e){window.postMessage(e,window.origin)}function S(e){const t=t=>{if(t.source!==window||t.origin!==window.origin)return;const i=t.data;i&&"object"==typeof i&&"string"==typeof i.kind&&i.kind.startsWith("userflow:")&&!0===e(i)&&s()};window.addEventListener("message",t);const s=()=>window.removeEventListener("message",t);return s}(h||(h={})).INPUT="INPUT",(E=u||(u={})).AUTO="AUTO",E.MANUAL="MANUAL";const f=new Set;let w=!1;function p(e){return function(){if(w)return;w=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),I()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{I()}))}(),f.add(e),()=>{g(e)}}function g(e){f.delete(e)}function I(){f.forEach((e=>e()))}class C{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){T({kind:"userflow:crxSendProxyMessage",direction:"targetToBuilder",message:e})}onBuilderMessage(e){return this.unregisterOnMessage=S(e),!1}async captureScreenshot(e,t,s,i){T({kind:"userflow:crxScreenshot",x:e,y:t,width:s,height:i,devicePixelRatio:window.devicePixelRatio});var n;return(await(n=e=>"userflow:crxScreenshotResult"===e.kind?e:null,new Promise((e=>{S((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,A,U,L,R,N,v,O,y,_,b,D,M,F,B,P,x,H,G,W,$,V,K,j,z,Y,J,X,Z,Q,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,Ee,Te,Se,fe,we,pe,ge,Ie,Ce,me,ke,Ae,Ue,Le,Re,Ne,ve,Oe,ye,_e,be,De,Me,Fe,Be,Pe,xe,He,Ge,We,$e,Ve,Ke,je,ze,Ye,Je,Xe,Ze;(k=m||(m={})).ACTION="ACTION",k.LAUNCHER_DEACTIVATED="LAUNCHER_DEACTIVATED",k.REPLACED="REPLACED",k.SNOOZED="SNOOZED",k.TOOLTIP_TARGET_MISSING="TOOLTIP_TARGET_MISSING",k.USERFLOWJS="USERFLOWJS",k.USER_CLOSED="USER_CLOSED",(U=A||(A={})).SECOND="SECOND",U.MINUTE="MINUTE",U.HOUR="HOUR",U.DAY="DAY",(R=L||(L={})).ACTION="ACTION",R.DRAFT="DRAFT",R.LINK="LINK",R.LAUNCHER_SEEN="LAUNCHER_SEEN",R.RESOURCE_CENTER="RESOURCE_CENTER",R.USERFLOWJS="USERFLOWJS",(v=N||(N={})).LIKE="LIKE",v.DISLIKE="DISLIKE",(y=O||(O={})).STRING="STRING",y.BOOLEAN="BOOLEAN",y.NUMBER="NUMBER",y.DATETIME="DATETIME",y.LIST="LIST",y.RANDOM_AB="RANDOM_AB",y.RANDOM_NUMBER="RANDOM_NUMBER",(b=_||(_={})).FLOW="FLOW",b.BANNER="BANNER",b.CHECKLIST="CHECKLIST",b.LAUNCHER="LAUNCHER",b.RESOURCE_CENTER="RESOURCE_CENTER",(M=D||(D={})).ALWAYS_TRUE="ALWAYS_TRUE",M.ATTRIBUTE="ATTRIBUTE",M.CLAUSE="CLAUSE",M.ELEMENT="ELEMENT",M.FILLED_IN_INPUT="FILLED_IN_INPUT",M.FLOW="FLOW",M.INPUT_VALUE="INPUT_VALUE",M.PAGE="PAGE",M.SEGMENT="SEGMENT",M.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(F||(F={})),(B||(B={})).INPUT="INPUT",(x=P||(P={})).ABSOLUTE_EQ="ABSOLUTE_EQ",x.ABSOLUTE_GT="ABSOLUTE_GT",x.ABSOLUTE_LT="ABSOLUTE_LT",x.AND="AND",x.BETWEEN="BETWEEN",x.CONTAINS="CONTAINS",x.EMPTY="EMPTY",x.ENDS_WITH="ENDS_WITH",x.EQ="EQ",x.EXCLUDES_ALL="EXCLUDES_ALL",x.EXCLUDES_ANY="EXCLUDES_ANY",x.FALSE="FALSE",x.GT="GT",x.GTE="GTE",x.INCLUDES_ALL="INCLUDES_ALL",x.INCLUDES_ANY="INCLUDES_ANY",x.LT="LT",x.LTE="LTE",x.NE="NE",x.NOT_CONTAINS="NOT_CONTAINS",x.NOT_EMPTY="NOT_EMPTY",x.NOT_REGEX="NOT_REGEX",x.OR="OR",x.REGEX="REGEX",x.RELATIVE_EQ="RELATIVE_EQ",x.RELATIVE_GT="RELATIVE_GT",x.RELATIVE_LT="RELATIVE_LT",x.STARTS_WITH="STARTS_WITH",x.TRUE="TRUE",x.URL="URL",(G=H||(H={})).CLICK="CLICK",G.DISABLED="DISABLED",G.MOUSEDOWN="MOUSEDOWN",G.NOT_CLICK="NOT_CLICK",G.NOT_DISABLED="NOT_DISABLED",G.NOT_PRESENT="NOT_PRESENT",G.PRESENT="PRESENT",($=W||(W={})).ASSET="ASSET",$.CARTOON="CARTOON",$.NONE="NONE",$.URL="URL",(K=V||(V={})).INSIDE="INSIDE",K.OUTSIDE="OUTSIDE",(z=j||(j={})).TOP_LEFT="TOP_LEFT",z.TOP_CENTER="TOP_CENTER",z.TOP_RIGHT="TOP_RIGHT",z.BOTTOM_RIGHT="BOTTOM_RIGHT",z.BOTTOM_CENTER="BOTTOM_CENTER",z.BOTTOM_LEFT="BOTTOM_LEFT",z.CENTER="CENTER",(J=Y||(Y={})).GOOGLE="GOOGLE",J.STANDARD="STANDARD",(Z=X||(X={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",Z.DISMISS="DISMISS",(q=Q||(Q={})).DISMISS="DISMISS",q.NONE="NONE",(te=ee||(ee={})).DEFAULT="DEFAULT",te.PLAINTEXT="PLAINTEXT",(ie=se||(se={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",ie.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",ie.NONE="NONE",(oe=ne||(ne={})).BUBBLE="BUBBLE",oe.END="END",oe.ERROR="ERROR",oe.FLAG="FLAG",(ae=re||(re={})).MANUAL="MANUAL",ae.NONE="NONE",ae.SYNTHETIC="SYNTHETIC",(le=ce||(ce={})).BUBBLE="BUBBLE",le.HIDDEN="HIDDEN",le.MODAL="MODAL",le.TOOLTIP="TOOLTIP",(he=de||(de={})).ABOVE="ABOVE",he.BELOW="BELOW",he.LEFT="LEFT",he.RIGHT="RIGHT",(Ee=ue||(ue={})).CLOSE_FLOW="CLOSE_FLOW",Ee.EVAL_JS="EVAL_JS",Ee.GO_TO_STEP="GO_TO_STEP",Ee.NAVIGATE="NAVIGATE",Ee.SET_ATTRIBUTE="SET_ATTRIBUTE",Ee.SNOOZE="SNOOZE",Ee.START_FLOW="START_FLOW",(Se=Te||(Te={})).NEW_TAB="NEW_TAB",Se.SAME_TAB="SAME_TAB",(we=fe||(fe={})).SET="SET",we.SET_DATETIME="SET_DATETIME",we.SET_DATETIME_ONCE="SET_DATETIME_ONCE",we.SET_ONCE="SET_ONCE",we.ADD="ADD",we.SUBTRACT="SUBTRACT",we.APPEND="APPEND",we.PREPEND="PREPEND",we.REMOVE="REMOVE",we.UNSET="UNSET",(ge=pe||(pe={})).MULTILINE_TEXT="MULTILINE_TEXT",ge.MULTIPLE_CHOICE="MULTIPLE_CHOICE",ge.NPS="NPS",ge.SCALE="SCALE",ge.STARS="STARS",ge.TEXT="TEXT",(Ce=Ie||(Ie={})).ACTION="ACTION",Ce.ANNOUNCEMENTS="ANNOUNCEMENTS",Ce.ASSISTANT="ASSISTANT",Ce.CHECKLIST="CHECKLIST",Ce.CONTACT="CONTACT",Ce.DIVIDER="DIVIDER",Ce.FLOWS="FLOWS",Ce.KNOWLEDGE_BASE="KNOWLEDGE_BASE",Ce.MESSAGE="MESSAGE",Ce.SUBPAGE="SUBPAGE",(ke=me||(me={})).CRISP="CRISP",ke.CUSTOM="CUSTOM",ke.FRESHCHAT="FRESHCHAT",ke.HELPSCOUT="HELPSCOUT",ke.HUBSPOT="HUBSPOT",ke.INTERCOM="INTERCOM",ke.ZENDESK="ZENDESK",ke.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ue=Ae||(Ae={})).BUTTON="BUTTON",Ue.INPUT="INPUT",(Re=Le||(Le={})).SILENT="SILENT",Re.BADGE="BADGE",Re.POPOUT="POPOUT",(ve=Ne||(Ne={})).LAUNCHER_CLICK="LAUNCHER_CLICK",ve.LAUNCHER_HOVER="LAUNCHER_HOVER",ve.TARGET_CLICK="TARGET_CLICK",ve.TARGET_HOVER="TARGET_HOVER",ve.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",ve.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(ye=Oe||(Oe={})).ACTIVATE="ACTIVATE",ye.DEACTIVATE="DEACTIVATE",ye.NEVER="NEVER",(be=_e||(_e={})).AUTO="AUTO",be.TOP="TOP",be.RIGHT="RIGHT",be.BOTTOM="BOTTOM",be.LEFT="LEFT",(Me=De||(De={})).START="START",Me.CENTER="CENTER",Me.END="END",(Be=Fe||(Fe={})).PERCENT="PERCENT",Be.PX="PX",(xe=Pe||(Pe={})).BEACON="BEACON",xe.BUTTON="BUTTON",xe.HIDDEN="HIDDEN",xe.ICON="ICON",(Ge=He||(He={})).LAUNCHER="LAUNCHER",Ge.TARGET="TARGET",($e=We||(We={})).BODY_FIRST="BODY_FIRST",$e.BODY_LAST="BODY_LAST",$e.ELEMENT_FIRST="ELEMENT_FIRST",$e.ELEMENT_LAST="ELEMENT_LAST",$e.ELEMENT_BEFORE="ELEMENT_BEFORE",$e.ELEMENT_AFTER="ELEMENT_AFTER",(Ke=Ve||(Ve={})).START="START",Ke.CENTER="CENTER",Ke.SPACE_BETWEEN="SPACE_BETWEEN",(ze=je||(je={})).NONE="NONE",ze.LIKE="LIKE",ze.SCALE="SCALE",(Je=Ye||(Ye={})).ACTIVE="ACTIVE",Je.COMPLETED="COMPLETED",Je.ENDED="ENDED",Je.NOT_SEEN="NOT_SEEN",(Ze=Xe||(Xe={})).HIGHLIGHT="HIGHLIGHT",Ze.MODAL="MODAL",Ze.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Qe={customInputs:[],customNavigate:null,urlFilter:null,customScrollIntoView:null,scrollPadding:null,inferenceAttributeNames:["data-for","data-id","data-testid","data-test-id","for","id","name","placeholder","role"],inferenceAttributeFilters:{id:[e=>!e.match(/\d$/)],"data-id":[e=>!e.match(/\d$/)]},inferenceClassNameFilters:[e=>!e.startsWith("css-")],baseZIndex:1234500,evalJsDisabled:!1};function qe(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function et(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function tt(){let e=d();if(Qe.urlFilter){if(e=Qe.urlFilter(e),"string"!=typeof e)throw new o("Userflow.js: URL filter returned non-string value. Please check your userflow.setUrlFilter() implementation.");try{new URL(e)}catch(t){throw new o("Userflow.js: URL filter returned an invalid URL. Please check your userflow.setUrlFilter() implementation.\nReturned URL: "+e+"\nError message: "+t.message)}}return e}let st="";try{st=localStorage.getItem("debug")||""}catch(Tt){}const it=st.split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),nt=rt("log");let ot;function rt(e){return function(t,...s){if(it){const i=performance.now(),n=ot?Math.round(i-ot):0;ot=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#1a57e6;","","color:#1a57e6;",...s)}}}nt.group=rt("group"),nt.groupCollapsed=rt("groupCollapsed"),nt.groupEnd=function(){it&&console.groupEnd()};const at=()=>n((()=>import("./ResourceCenterApp.js").then((function(e){return e.R}))),[new URL("ResourceCenterApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("flow-host.styl.js",import.meta.url).toString(),new URL("bubble-frame.styl.js",import.meta.url).toString(),new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString(),new URL("stylesheets.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("vendor.obj-str.js",import.meta.url).toString(),new URL("use-window-resize.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("logomark.js",import.meta.url).toString(),new URL("ChecklistUI.js",import.meta.url).toString(),new URL("BubbleToolbar.js",import.meta.url).toString(),new URL("use-element-rect.js",import.meta.url).toString()]);function ct(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class lt{constructor(e){this.observers=new Set,this._value=e}get value(){return this._value}update(e){if(e!==this._value){this._value=e;for(const e of this.observers)e()}}observe(e){return this.observers.add(e),()=>this.observers.delete(e)}}const dt=["page:before-change","page:change","turbo:before-cache","turbo:load","turbo:visit","turbolinks:before-cache","turbolinks:load","turbolinks:visit"],ht=()=>n((()=>import("./BannerApp.js")),[new URL("BannerApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("vendor.obj-str.js",import.meta.url).toString(),new URL("stylesheets.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString(),new URL("bubble-frame.styl.js",import.meta.url).toString(),new URL("flow-host.styl.js",import.meta.url).toString(),new URL("use-selector-element-monitoring.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("use-window-resize.js",import.meta.url).toString(),new URL("use-element-rect.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]),ut=import.meta.url;class Et{constructor(){this.clientToken=null,this.externalId=null,this.signature=null,this.groupId=null,this.groupSignature=null,this._socketStatus="disconnected",this.socket=null,this.channel=null,this.featureFlags=new Set,this.logrocketAppId=null,this.debounceInactiveDisconnectTimeout=void 0,this.inBatch=!1,this.endBatchTimeout=void 0,this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=0,this.clientClock=1,this.serverClock=1,this.flowSession=null,this.flowSessionClock=0,this.checklistSession=null,this.checklistExpanded=!1,this.checklistExpandPending=!1,this.checklistSessionClock=0,this.bannerSession=null,this.resourceCenterSession=null,this.resourceCenterOpen=!1,this.resourceCenterLauncherHidden=!1,this.launcherSessions=[],this.activeLauncherFlowId=null,this.notifications=[],this.notificationIdCounter=0,this.sessionStorageState=null,this.clientContext=null,this.flushUrlChangeTimeout=void 0,this.onFirstIdentifyRun=!1,this.onFirstIdentifyTimeout=void 0,this.firstIdentifyCallback=null,this.ui=null,this.unackedTasks=new Set,this.clientConditions=new Map,this.trackers=new Map,this.conditionWaitTimers=new Map,this.listeners=new Map,this.targetEnv=null,this.idempotencyKeysSeen=new Set,this.testUserIdentified=!1,this.cspIssueReported=!1,this.uiDisabled=!1,this.audio=null,this.audioReady=!1,this.pageTrackingDisabled=!1,this.refCounter=1,this.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{nt(`builder ${e.kind} message received`,e);const t="idempotencyKey"in e&&"string"==typeof e.idempotencyKey?e.idempotencyKey:null;if(t&&this.idempotencyKeysSeen.has(t))return;const s=()=>{t&&this.idempotencyKeysSeen.add(t)};switch(e.kind){case"userflow:selectElement":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:selectElementAck",idempotencyKey:e.idempotencyKey}),void this.setSessionStorageState((t=>({...t,isTargetTab:!0,activeApp:"elementSelection",elementSelection:{mode:"select",elementType:e.elementType}})));case"userflow:selectElementCancel":return void this.setSessionStorageState((e=>({...e,activeApp:null,elementSelection:null})));case"userflow:startFlowWithToken":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:startFlowWithTokenAck",idempotencyKey:e.idempotencyKey}),this.setSessionStorageState((e=>({...e,isTargetTab:!0,activeApp:null,testStartConditionToken:void 0}))),c.setItem("previewFlowId",e.flowId),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void(e.testStartCondition?this.setSessionStorageState((t=>({...t,activeApp:"startConditionTesting",testStartConditionToken:e.token}))):this.onceIdentified((()=>{if(this.startFlowWithToken(e.token),e.isResourceCenter){const t=()=>{const s=this.resourceCenterSession;s&&s.draftMode&&s.flow.id===e.flowId&&(this.openResourceCenter(),this.off("resourceCenterChanged",t))};this.on("resourceCenterChanged",t),t()}})));case"userflow:testTracker":return s(),this.getTargetEnv().postBuilderMessage({kind:"userflow:testTrackerAck",idempotencyKey:e.idempotencyKey}),this.setSessionStorageState((e=>({...e,isTargetTab:!0}))),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void this.setSessionStorageState((t=>({...t,activeApp:"trackerTesting",trackerTesting:{trackerName:e.trackerName,token:e.token,events:0}})));case"userflow:testTrackerCancel":return void this.setSessionStorageState((e=>({...e,activeApp:null,trackerTesting:null})))}},this.onUrlChange=()=>{this.externalId&&(window.clearTimeout(this.flushUrlChangeTimeout),this.flushUrlChangeTimeout=window.setTimeout((()=>this.flushUrlChange()),50))},this.onUserActivity=()=>this.ensureConnected(),this.remountIfNecessary=()=>{this.ui?.container&&!document.contains(this.ui.container)&&(nt("remounting UI because container was missing"),this.remount())},nt("constructor, build=1004182"),p(this.onUrlChange),this.setTargetEnv(new C),this.checkTestUserAtBoot(),this.toggleUI();for(const e of dt)document.addEventListener(e,this.remountIfNecessary)}get socketStatus(){return this._socketStatus}destroy(){nt("destroy"),this.reset(),g(this.onUrlChange),this.destroyTargetEnv();for(const e of dt)document.removeEventListener(e,this.remountIfNecessary)}setTargetEnv(e){this.destroyTargetEnv(),this.targetEnv=e,e.onBuilderMessage(this.onBuilderMessage)}destroyTargetEnv(){this.targetEnv&&(this.targetEnv.destroy(),this.targetEnv=null)}getTargetEnv(){if(!this.targetEnv)throw new o("Userflow.js: Cannot call getTargetEnv when protocol is not set");return this.targetEnv}setSessionStorageState(e){const t=e(this.getSessionStorageState());c.setItem("userflowClientState",JSON.stringify(t)),this.sessionStorageState=t,this.toggleUI()}getSessionStorageState(){let e=this.sessionStorageState;if(!e){const t=c.getItem("userflowClientState");if(t)try{e=JSON.parse(t)}catch(Tt){console.error("Userflow.js: Parse ElementSelectionState error:",Tt)}e||(e={testUser:null,activeApp:null,elementSelection:null,trackerTesting:null}),this.sessionStorageState=e}return e}checkTestUserAtBoot(){const e=this.getSessionStorageState().testUser;e&&(nt("checkTestUserAtBoot identifying test user"),this.identifyTestUser(e))}async identifyTestUser(e){this.setSessionStorageState((t=>({...t,testUser:e}))),this.reset(),this.init(e.clientToken),this.testUserIdentified=!0,this.externalId=e.id;const t=[this.identify(e.id,{name:e.name,email:e.email,signed_up_at:{set_once:(new Date).toISOString(),data_type:"datetime"}},{signature:e.signature})],{group:s}=e;s&&(this.groupId=s.id,t.push(this.group(s.id,{name:s.name},{signature:s.signature}))),await Promise.all(t)}resetTestUser(){this.setSessionStorageState((e=>({...e,testUser:null})))}init(e){if(nt("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?nt("init() ignoring new token since a test user has been identified"):(this.clientToken&&(nt("init() resetting due to new client token"),this.reset()),this.clientToken=e))}ensureInit(){if(!this.clientToken)throw new o("You must call userflow.init() first")}ensureIdentified(){if(this.ensureInit(),!this.externalId)throw new o("You must call userflow.identify() first");return this.externalId}ensureGroup(){if(this.ensureIdentified(),!this.groupId)throw new o("You must call userflow.group() first");return this.groupId}ensureConnected(){if(!this.clientToken||!this.externalId)return;if(this.debounceInactiveDisconnect(),this.socket)return;this._socketStatus="connecting",nt("connecting to socket");let t=Qe.serverEndpoint||"e.userflow.com";"js.getuserflow.com"===new URL(ut).hostname&&"e.userflow.com"===t&&(t="e.getuserflow.com");const s="wss://"+t+"/end-users/"+this.clientToken+"/socket";this.socket=new e(s,{reconnectAfterMs:e=>[100,500,1e3,5e3][e-1]||1e4,timeout:2e4}),this.socket.connect(),this.socket.onOpen((()=>{nt("socket opened")})),this.socket.onClose((()=>{this.emit("private:disconnect")})),this.socket.onError((e=>{console.log("Userflow.js socket error",e),this.reportCspIssue()})),this.channel=this.socket.channel(`end_users:${this.externalId}`,(()=>this.makeChannelJoinPayload())),this.channel.join().receive("ok",(e=>{this.logrocketAppId=e.logrocketAppId,this.featureFlags=new Set(e.featureFlags),nt("channel joined"),"connected"!==this._socketStatus&&(this._socketStatus="connected")})).receive("error",(e=>{["company_closed","invalid_client_token","invalid_user_external_id","incorrect_user_signature","rate_limit_exceeded","user_signature_required"].includes(e.code)?(console.error(`Userflow.js resetting due to: [${e.code}] ${e.message}`),this.reset(),this.clientToken=null):"invalid_protocol_version"===e.code?(console.error(`Userflow.js destroying due to: [${e.code}] ${e.message}`),this.destroy()):console.log("Userflow.js channel join error",e)})),this.channel.on("server_message",(e=>this.handleServerMessage(e))),this.channel.on("server_error",(e=>{console.log(`Userflow.js server error (${e.code}): ${e.message}`+(e.details&&e.details.length>0?"\nDetails:\n"+e.details.map((e=>(e.path?`${e.path}: `:"")+e.message)):""))}))}makeChannelJoinPayload(){const e=this.buildClientContext();this.clientContext=e;const t={protocolVersion:2,userflowClientBuild:"1004182",signature:this.signature,groupExternalId:this.groupId,groupSignature:this.groupSignature,flowSessionId:this.flowSession?.id||null,checklistSessionId:this.checklistSession?.id||null,bannerSessionId:this.bannerSession?.id||null,resourceCenterSessionId:this.resourceCenterSession?.id||null,launchers:this.launcherSessions.map((e=>({flowId:e.flow.id}))),trackers:Array.from(this.trackers.values()).map((e=>({flowId:e.tracker.flowId}))),hasDraftSession:this.hasDraftSession(),clientConditions:Array.from(this.clientConditions.values()).map((e=>({conditionId:e.condition.id,isTrue:e.isTrue}))),previewFlowId:c.getItem("previewFlowId"),clientContext:e};return nt("channel join payload",t),t}disconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.socket&&this.socket.disconnect(),this._socketStatus="disconnected",this.socket=null,this.channel=null}debounceInactiveDisconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.debounceInactiveDisconnectTimeout=window.setTimeout((()=>{this.hasDraftSession()||this.assistantMessageInProgress?this.debounceInactiveDisconnect():(nt("disconnecting from socket due to inactivity"),this.disconnect())}),3e5)}hasDraftSession(){return!!this.flowSession?.draftMode||!!this.checklistSession?.draftMode||!!this.bannerSession?.draftMode||!!this.resourceCenterSession?.draftMode||this.launcherSessions.some((e=>e.draftMode))}async send(e,{batch:t,endBatch:s,handlesRejection:i}={}){return this.inBatch&&["ToggleClientCondition","UpdateClientContext"].includes(e.kind)||this.checkPushRateLimit(),this.ensureConnected(),t&&!this.inBatch&&(this.inBatch=!0,this.sendRaw({kind:"BeginBatch"})),this.inBatch&&(window.clearTimeout(this.endBatchTimeout),s?this.endBatch():this.endBatchTimeout=window.setTimeout((()=>{this.endBatch()}),50)),this.sendRaw(e,{handlesRejection:i})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel){const s=`Userflow.js: send() should not be called if channel is not set. Message kind=${e.kind}`;if(t)throw Error(s);return void console.log(s,"\nClient message:",e)}nt(`push ${e.kind} message`,e);const n=this.clientClock,r=()=>{this.serverClock=n,this.channel?.off("phx_error",a)},a=this.channel.on("phx_error",(s=>{r();const n=`Userflow.js send ${e.kind} got phx_error`;"connected"===this._socketStatus&&console.log(n,"\nClient message:",e,"\nError:",s),t&&i(new o(n))}));this.channel.push("client_message",e).receive("ok",(e=>{r(),s(e)})).receive("error",(s=>{r();const n=`Userflow.js error reply (${s.code}): ${s.message}`;console.log(n,"\nClient message:",e,"\nError:",s),t&&i(new o(n,s.code,s.message))}))}))}endBatch(){this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}checkPushRateLimit(){const e=Date.now();if(this.pushRateLimitMinuteExpires<e&&(this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=e+6e4),this.pushRateLimitMinute>=100)throw new o("This Userflow.js client has reached a maximum of 100 operations in the last 1 minute. This is usually due to one of the following:\n\n - Excessive calls to Userflow.js. Check if any of userflow.track(), userflow.identify(), userflow.updateUser() or similar are called repeatedly.\n - The URL changing too frequently. Look into https://userflow.com/docs/userflow-js#seturlfilter and filter out the changing part of the URL.\n - The user legitimately being very active, in which case you can just ignore this error.\n \n If in doubt, reach out to us at support@userflow.com.");this.pushRateLimitMinute++}handleServerMessage(e){nt(`received ${e.kind} message`,e);const{serverClock:t,flowSession:s,flowSessionClock:i,checklistSession:n,checklistSessionClock:o,bannerSession:r,resourceCenterSession:a}=this;switch(e.kind){case"CheckSessionsAck":case"ServerDebug":return;case"AddLauncher":{const{session:t}=e,s=this.launcherSessions.findIndex((e=>e.flow.id===t.flow.id));return this.launcherSessions=-1===s?[...this.launcherSessions,t]:[...this.launcherSessions.slice(0,s),t,...this.launcherSessions.slice(s+1)],void this.toggleUI()}case"AddTracker":return void this.addTracker(e.tracker);case"AssistantMessageEventWrapper":return void this.emit("private:assistantMessageEvent",e);case"CancelConditionWaitTimer":return window.clearTimeout(this.conditionWaitTimers.get(e.conditionId)),void this.conditionWaitTimers.delete(e.conditionId);case"ChecklistTaskCompleted":return void this.unackedTasks.add(e.taskCvid);case"ForceGoToStep":return i>t?void nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`):void(s?.id===e.sessionId&&this.emit("gotostep",{session:s,step:{id:e.stepId}}));case"RemoveLauncher":return void(this.removeLauncher(e.flowId)&&this.toggleUI());case"RemoveTracker":return void this.removeTracker(e.flowId);case"SetBannerSession":return this.setBannerSession(e.session),void this.toggleUI();case"SetChecklistSession":return void(o<=t||n?.id===e.session.id?(this.setChecklistSession(e.session,t),this.toggleUI()):nt(`ignoring ${e.kind} message due to stale clock checklistSessionClock=${o} > serverClock=${t}`));case"SetFlowSession":return void(i<=t||s?.id===e.session.id?(this.setFlowSession(e.session,t),this.toggleUI()):nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`));case"SetResourceCenterSession":return this.setResourceCenterSession(e.session),void this.toggleUI();case"StartConditionWaitTimer":if(!this.conditionWaitTimers.has(e.conditionId)){const t=window.setTimeout((()=>{this.conditionWaitTimers.delete(e.conditionId),this.send({kind:"FireConditionWaitTimer",conditionId:e.conditionId},{batch:!0})}),1e3*parseFloat(e.waitTime));this.conditionWaitTimers.set(e.conditionId,t)}return;case"TestStartConditionSuccess":return void this.emit("private:testStartConditionSuccess");case"TrackClientCondition":return void this.trackClientCondition(e.condition);case"UnsetBannerSession":return void(r?.id===e.sessionId&&(this.setBannerSession(null),this.toggleUI()));case"UnsetChecklistSession":return o>t?void nt(`ignoring ${e.kind} message due to stale clock checklistSessionClock=${o} > serverClock=${t}`):void(n?.id===e.sessionId&&(this.setChecklistSession(null,t),this.toggleUI()));case"UnsetFlowSession":return i>t?void nt(`ignoring ${e.kind} message due to stale clock flowSessionClock=${i} > serverClock=${t}`):void(s?.id===e.sessionId&&(this.setFlowSession(null,t),this.toggleUI()));case"UnsetResourceCenterSession":return void(a?.id===e.sessionId&&(this.setResourceCenterSession(null),this.toggleUI()));case"UntrackClientCondition":return void this.untrackClientCondition(e.conditionId);default:return void console.warn("Userflow.js: Received unknown message",e)}}async identify(e,t={},{signature:s}={}){if(nt("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)nt("identify() ignored since a test user has been identified");else{if("number"==typeof e)e=String(e);else if(!e||"string"!=typeof e)throw new o(`userflow.identify: First argument must be a non-empty string representing the user's ID in your database. Value received: ${JSON.stringify(e)}`);this.externalId&&e!==this.externalId&&(nt("identify resetting due to new externalId"),this.reset()),this.externalId=e,this.signature=s||null,this.observeUserActivity(),await Promise.all([this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(t)},{batch:!0}),this.onFirstIdentify()]),this.emit("private:identified")}}async identifyAnonymous(e={},s={}){if(!a.isSupported())throw new o("userflow.identifyAnonymous() is not supported when localStorage access is denied.");const i="anonymousId";let n=a.getItem(i);n||(n="anon-"+t(),a.setItem(i,n)),await this.identify(n,e,s)}async updateUser(e={},t={}){nt("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if(nt("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)nt("group() ignored since a test user has been identified");else{if("number"==typeof e)e=String(e);else if(!e||"string"!=typeof e)throw new o(`userflow.group: First argument must be a non-empty string representing the group's ID in your database. Value received: ${JSON.stringify(e)}`);this.groupId=e,this.groupSignature=s||null,await this.send({kind:"UpsertGroup",groupExternalId:e,groupSignature:this.groupSignature,groupAttributes:this.normalizeAttributes(t),membershipAttributes:this.normalizeAttributes(i)},{batch:!0})}}async updateGroup(e={},t={}){nt("updateGroup");const s=this.ensureGroup();await this.send({kind:"UpsertGroup",groupExternalId:s,groupSignature:this.groupSignature,membershipAttributes:this.normalizeAttributes(t.membership),groupAttributes:this.normalizeAttributes(e)},{batch:!0})}normalizeAttributes(e){if(null==e)return{};if("object"!=typeof e)throw new o("Userflow: 'attributes' must be an object.");const t={};for(const s in e){if(!e.hasOwnProperty(s))continue;if("traits"===s){const i=e[s];Object.assign(t,this.extractLegacyTraits(i));continue}let i=e[s];if("string"==typeof i||"number"==typeof i||"boolean"==typeof i||null==i||Array.isArray(i))t[s]=this.normalizeAttributeLiteralOrList(s,i);else{if("object"!=typeof i||null==i)throw new o(`Userflow: Invalid value for '${s}' attribute.`);if("set"in i)t[s]={set:this.normalizeAttributeLiteralOrList(s,i.set),dataType:this.normalizeDataType(s,i.data_type||i.dataType)};else if("set_once"in i||"setOnce"in i)t[s]={setOnce:this.normalizeAttributeLiteralOrList(s,i.set_once??i.setOnce),dataType:this.normalizeDataType(s,i.data_type||i.dataType)};else if("add"in i){const e=i.add;if("string"!=typeof e&&"number"!=typeof e)throw new o(`Userflow: Invalid 'add' value for '${s}' attribute. Must be a number or string.`);t[s]={add:e}}else if("subtract"in i){const e=i.subtract;if("string"!=typeof e&&"number"!=typeof e)throw new o(`Userflow: Invalid 'subtract' value for '${s}' attribute. Must be a number or string.`);t[s]={subtract:e}}else if("append"in i)t[s]={append:this.normalizeAttributeLiteralOrList(s,i.append)};else if("prepend"in i)t[s]={prepend:this.normalizeAttributeLiteralOrList(s,i.prepend)};else{if(!("remove"in i))throw new o(`Userflow: Invalid value for '${s}' attribute.`);t[s]={remove:this.normalizeAttributeLiteralOrList(s,i.remove)}}}}return t}normalizeAttributeLiteralOrList(e,t){return Array.isArray(t)?t.map((t=>this.normalizeAttributeLiteral(e,t))):this.normalizeAttributeLiteral(e,t)}normalizeAttributeLiteral(e,t){if(null==t)return null;if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;throw new o(`Userflow: Invalid value for '${e}' attribute.`)}normalizeDataType(e,t){if(!t)return null;switch(t){case"string":return O.STRING;case"number":return O.NUMBER;case"boolean":return O.BOOLEAN;case"datetime":return O.DATETIME}throw new o(`Userflow: Invalid data_type for '${e}' attribute.`)}extractLegacyTraits(e){if(!e)return{};if(!Array.isArray(e)){const t=[];for(const s in e)e.hasOwnProperty(s)&&t.push({name:s,value:e[s]});e=t}return e.reduce(((e,{name:t,value:s,dataType:i})=>{if("string"!=typeof t||t.length>100||!t.match(/^[a-z0-9_]+$/))return this.warn("Userflow.identify: Invalid trait name (must be string, no more than 100 characters, and only consist of a-z, 0-9 and underscores). The trait will be ignored. Name was:",t),e;if("string"==typeof s);else if("boolean"==typeof s)i||(i="boolean"),s=s?"true":"false";else{if("number"!=typeof s)return this.warn(`userflow.identify: The value of trait '${t}' is invalid (must be a string, a boolean or a number). The trait will be ignored. Value was:`,s),e;i||(i=Number.isInteger(s)?"integer":"decimal"),s=String(s)}let n=null;if(i)switch(i){case"string":n=O.STRING;break;case"boolean":n=O.BOOLEAN;break;case"integer":case"decimal":n=O.NUMBER;break;case"datetime":n=O.DATETIME;break;default:return this.warn(`userflow.identify: The data type of trait '${t}' is invalid (must be a 'string', 'boolean', 'integer', 'decimal' or 'datetime'). The trait will be ignored. Data type was:`,i),e}return e[t]={set:s,dataType:n},e}),{})}async track(e,t={},{userOnly:s}={}){nt(`track '${e}'`,t),this.ensureIdentified(),await this.send({kind:"TrackEvent",userOnly:!!s,name:e,attributes:this.normalizeEventAttributes(t)},{batch:!0})}normalizeEventAttributes(e){const t=this.normalizeAttributes(e);for(const s in t){if(!t.hasOwnProperty(s))continue;const e=t[s];if(null!=e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e&&!Array.isArray(e)&&!("set"in e))throw new o(`Userflow: Invalid value for '${s}' attribute. Event attributes only support literal values, list values and 'set' changes.`)}return t}onFirstIdentify(){this.onFirstIdentifyRun||(this.onFirstIdentifyRun=!0,this.onFirstIdentifyTimeout=window.setTimeout((()=>{this.trackPageViewed(),this.firstIdentifyCallback?(this.firstIdentifyCallback(),this.firstIdentifyCallback=null):this.checkUrlForStartFlow()}),0))}onceIdentified(e){this.isIdentified()?e():this.firstIdentifyCallback=e}checkUrlForStartFlow(){const e=new URL(d()),t=e.searchParams.get("userflow")||e.searchParams.get("studio1_flow")||e.searchParams.get("studio1_walkthrough");t&&(nt(`url contained flow ${t}`),this.startFlow({flowId:t,startReason:L.LINK,batch:!0}),e.searchParams.delete("userflow"),e.searchParams.delete("studio1_flow"),e.searchParams.delete("studio1_walkthrough"),window.history.replaceState({},"",e.toString()),this.clientContext=this.buildClientContext(),this.pushUpdateClientContext())}flushUrlChange(){const e=this.buildClientContext();this.clientContext&&e.pageUrl===this.clientContext.pageUrl||(this.clientContext=e,this.pushUpdateClientContext(),this.trackPageViewed(),this.checkUrlForStartFlow())}async trackPageViewed(){this.pageTrackingDisabled||this.track("page_viewed",{})}buildClientContext(){return{pageUrl:tt(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight}}pushUpdateClientContext(){this.send({kind:"UpdateClientContext",clientContext:this.clientContext},{batch:!0})}ackCompletedTask(e){this.unackedTasks.delete(e)}taskIsUnacked(e){return this.unackedTasks.has(e)}isIdentified(){return null!=this.externalId}on(e,t){let s=this.listeners.get(e);s||(s=new Set,this.listeners.set(e,s)),s.add(t)}off(e,t){const s=this.listeners.get(e);s&&s.delete(t)}emit(e,...t){const s=this.listeners.get(e);if(s){Array.from(s).forEach((e=>e(...t)))}}observeUserActivity(){document.addEventListener("mouseover",this.onUserActivity),document.addEventListener("pointerdown",this.onUserActivity),document.addEventListener("keydown",this.onUserActivity)}unobserveUserActivity(){document.removeEventListener("mouseover",this.onUserActivity),document.removeEventListener("pointerdown",this.onUserActivity),document.removeEventListener("keydown",this.onUserActivity)}reset(){nt("reset"),this.externalId=null,this.groupId=null,this.sessionStorageState=null,this.setFlowSession(null,0),this.setChecklistSession(null,0),this.setBannerSession(null),this.setResourceCenterSession(null),this.launcherSessions=[],this.activeLauncherFlowId=null,this.notifications=[],this.unackedTasks=new Set,this.onFirstIdentifyRun=!1,window.clearTimeout(this.onFirstIdentifyTimeout),this.onFirstIdentifyTimeout=void 0,this.clientContext=null,this.unobserveUserActivity(),window.clearTimeout(this.flushUrlChangeTimeout),this.flushUrlChangeTimeout=void 0,this.clientConditions.forEach(((e,t)=>{this.untrackClientCondition(t)})),this.firstIdentifyCallback=null,this.testUserIdentified=!1,a.removeItem("anonymousId"),this.unmountUI(),this.disconnect(),this.inBatch=!1,window.clearTimeout(this.endBatchTimeout),this.endBatchTimeout=void 0,this.clientClock=1,this.serverClock=1,this.titleMonitored=void 0,this.titleObserver&&(this.titleObserver.disconnect(),this.titleObserver=void 0)}async startFlow({flowId:e,stepCvid:t,startReason:s,once:i,batch:n,replaceCurrent:o}){if(this.ensureIdentified(),o&&this.flowSession&&this.endFlow(this.flowSession,{endReason:m.REPLACED,batch:!0}),nt(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return nt("startFlow matches current checklist, so showing it instead"),void this.showChecklist();const r={kind:"StartFlow",flowId:e,stepCvid:t,startReason:s,once:!!i};await this.send(r,{batch:n})}async startFlowWithToken(e){this.ensureIdentified(),nt("startFlowWithToken",{token:e}),await this.send({kind:"StartFlowWithToken",token:e},{batch:!0})}optimisticClockUIUpdate(e){this.clientClock++,e(),this.toggleUI()}async showChecklist(){this.resourceCenterEmbedsChecklist()?this.openResourceCenter():(this.unmarkExpandPending(),this.checklistSession&&!this.checklistExpanded&&(this.ensureIdentified(),this.checklistExpanded=!0,this.toggleUI(),c.setItem(`checklistExpanded:${this.checklistSession.id}`,"1"),await this.send({kind:"ShowChecklist",sessionId:this.checklistSession.id},{batch:!0})))}async hideChecklist(){this.resourceCenterEmbedsChecklist()?this.closeResourceCenter():this.checklistSession&&this.checklistExpanded&&(this.ensureIdentified(),this.checklistExpanded=!1,this.toggleUI(),c.removeItem(`checklistExpanded:${this.checklistSession.id}`),await this.send({kind:"HideChecklist",sessionId:this.checklistSession.id},{batch:!0}))}async unmarkExpandPending(){this.checklistSession&&this.checklistExpandPending&&(this.checklistExpandPending=!1,await this.send({kind:"UnmarkExpandPending",sessionId:this.checklistSession.id},{batch:!0}))}async openResourceCenter(){this.resourceCenterEmbedsChecklist()&&this.unmarkExpandPending(),this.resourceCenterSession&&!this.resourceCenterOpen&&(this.ensureIdentified(),this.resourceCenterOpen=!0,this.toggleUI(),this.emit("resourceCenterChanged"),c.setItem(`resourceCenterOpen:${this.resourceCenterSession.id}`,"1"),await this.send({kind:"OpenResourceCenter",sessionId:this.resourceCenterSession.id},{batch:!0}))}async closeResourceCenter(){this.resourceCenterSession&&this.resourceCenterOpen&&(this.ensureIdentified(),this.resourceCenterOpen=!1,this.toggleUI(),this.emit("resourceCenterChanged"),c.removeItem(`resourceCenterOpen:${this.resourceCenterSession.id}`),await this.send({kind:"CloseResourceCenter",sessionId:this.resourceCenterSession.id},{batch:!0}))}toggleResourceCenter(){this.resourceCenterOpen?this.closeResourceCenter():this.openResourceCenter()}setResourceCenterLauncherHidden(e){this.resourceCenterLauncherHidden=e,this.toggleUI()}getResourceCenterState(){if(!this.resourceCenterSession)return null;const e=this.resourceCenterEmbedsChecklist(),{checklistSession:t}=this,s=this.resourceCenterSession.version.resourceCenter?.blocks.find((e=>e.type===Ie.ANNOUNCEMENTS));return{isOpen:this.resourceCenterOpen,hasChecklist:e,uncompletedChecklistTaskCount:e&&t?ct(t):0,unreadAnnouncementCount:s?.unreadAnnouncementCount||0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Ie.CHECKLIST))}async endFlow(e,{endReason:t,batch:s}){this.ensureIdentified(),this.optimisticClockUIUpdate((()=>{const{clientClock:t}=this;this.flowSession?.id===e.id&&this.setFlowSession(null,t),this.checklistSession?.id===e.id&&this.setChecklistSession(null,t),this.bannerSession?.id===e.id&&this.setBannerSession(null),this.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===_.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===_.FLOW&&this.emit("flowEnded",{flow:n,endReason:t});const o={kind:"EndFlow",sessionId:e.id,endReason:t};await this.send(o,{batch:s})}async goToStep(e,t){nt("goToStep",e.id,t.name||t.id),this.ensureIdentified();const s=this.send({kind:"GoToStep",sessionId:e.id,stepId:t.id});e.currentStep=t,this.emit("gotostep",{session:e,step:t}),await s}async endAllFlows(){nt("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){nt("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===_.CHECKLIST&&this.endFlow(e,{endReason:m.USERFLOWJS})}setFlowSession(e,t=this.clientClock){const s=this.flowSession;this.flowSession=e,this.flowSessionClock=t,e&&!s&&(this.hideChecklist(),this.closeResourceCenter()),null==e&&this.originalActiveElement&&("function"==typeof this.originalActiveElement.focus&&this.originalActiveElement.focus(),this.originalActiveElement=void 0)}setChecklistSession(e,t=this.clientClock){const s=this.checklistSession;this.checklistSession=e,this.checklistSessionClock=t,null===e&&(this.checklistExpanded=!1,this.checklistExpandPending=!1),e&&e.id!==s?.id&&(this.checklistExpanded=!!c.getItem(`checklistExpanded:${e.id}`),e.expandPending&&(this.checklistExpandPending=!0)),this.emit("checklistChanged"),this.emit("resourceCenterChanged")}setBannerSession(e){this.bannerSession=e}setResourceCenterSession(e){const t=this.resourceCenterSession;e="function"==typeof e?e(this.resourceCenterSession):e,this.resourceCenterSession=e,null===e&&(this.resourceCenterOpen=!1),t&&t.id!==e?.id&&c.removeItem(`resourceCenterOpen:${t.id}`),e&&e.id!==t?.id&&(this.resourceCenterOpen=!!c.getItem(`resourceCenterOpen:${e.id}`)),this.emit("resourceCenterChanged")}launcherSeen(e){this.send({kind:"StartFlow",flowId:e,startReason:L.LAUNCHER_SEEN,once:!1})}activateLauncher(e){const t=this.activeLauncherFlowId&&this.launcherSessions.find((e=>e.flow.id===this.activeLauncherFlowId));t&&this.deactivateLauncher(t),this.activeLauncherFlowId=e.flow.id,this.toggleUI(),this.send({kind:"ActivateLauncher",flowId:e.flow.id})}deactivateLauncher(e){const{launcher:t}=e.version;e.flow.id===this.activeLauncherFlowId&&(t?.dismissOn===Oe.DEACTIVATE?this.dismissLauncher(e,{endReason:m.LAUNCHER_DEACTIVATED}):(this.activeLauncherFlowId=null,this.toggleUI()))}dismissLauncher(e,{endReason:t}){const s=e.flow.id;this.removeLauncher(s),this.toggleUI(),this.send({kind:"DismissLauncher",flowId:s,endReason:t})}removeLauncher(e){const t=this.launcherSessions.findIndex((t=>t.flow.id===e));return-1!==t&&(this.launcherSessions=[...this.launcherSessions.slice(0,t),...this.launcherSessions.slice(t+1)],e===this.activeLauncherFlowId&&(this.activeLauncherFlowId=null),!0)}async toggleUI(){const e=this.getSessionStorageState();this.flowSession||!this.checklistExpandPending&&!this.checklistSession?.version.checklist?.tasks.some((e=>this.taskIsUnacked(e.cvid)))||this.showChecklist(),e.isTargetTab&&this.monitorTitle(),this.emit("uistatechange"),this.shouldBeMounted()?await this.mountUI():this.unmountUI()}shouldBeMounted(){if(this.uiDisabled)return!1;return!!this.getSessionStorageState().activeApp||!!this.flowSession||!!this.checklistSession&&(this.checklistExpanded||!!this.checklistSession?.version.checklist?.launcherEnabled)||!!this.bannerSession||!!this.resourceCenterSession&&(this.resourceCenterOpen||!this.resourceCenterLauncherHidden)||this.launcherSessions.length>0||this.notifications.length>0}async mountUI(){if(!this.ui){const e=await this.createUI();this.shouldBeMounted()&&!this.ui&&(nt("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&(nt("unmount UI"),this.ui.unmount(),this.ui=null)}remount(){this.unmountUI(),this.toggleUI()}async createUI(){try{const e=n((()=>import("./ui.js")),[new URL("ui.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("vendor.react-dom.js",import.meta.url).toString(),new URL("vendor.scheduler.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]);this.bannerSession&&ht(),this.resourceCenterSession&&at();const{RealUI:t}=await e;return new t(this)}catch(Tt){throw this.reportCspIssue(),Tt}}async trackClientCondition(e){if(this.clientConditions.has(e.id))return;nt("track client condition",e),this.clientConditions.set(e.id,{condition:e,isTrue:null});const{conditionTypes:t}=await n((()=>import("./flow-condition-types.js").then((function(e){return e.v}))),[new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString()]),s=t[e.type],i=this.clientConditions.get(e.id);i&&(i.untrack=s.track({sessionData:new lt([]),condition:e,callback:t=>{i.isTrue!==t&&(nt("client condition truthiness changed",t,i.condition),i.isTrue=t,this.send({kind:"ToggleClientCondition",conditionId:e.id,isTrue:t},{batch:!0}))}}))}untrackClientCondition(e){const t=this.clientConditions.get(e);t&&(nt("untrack client condition",t.condition),t.untrack&&t.untrack(),this.clientConditions.delete(e))}async addTracker(e){let t=this.trackers.get(e.flowId);t?t.tracker=e:this.trackers.set(e.flowId,{tracker:e,isTrue:!1});const{conditionTypes:s}=await n((()=>import("./flow-condition-types.js").then((function(e){return e.v}))),[new URL("flow-condition-types.js",import.meta.url).toString(),new URL("vendor.date-fns.js",import.meta.url).toString()]),i=this.trackers.get(e.flowId);if(!i)return;const{tracker:o}=i,{condition:r}=o,a=s[r.type];i.untrack&&i.untrack(),i.untrack=a.track({sessionData:new lt(o.data),condition:r,flipBackEvents:!0,callback:e=>{const t=i.isTrue;i.isTrue=e,!t&&e&&this.send({kind:"TrackTrackerEvent",token:o.token},{batch:!0})},description:`event tracker ${o.flowId}`}),this.emit("private:trackerStarted")}removeTracker(e){const t=this.trackers.get(e);t&&(t.untrack&&t.untrack(),this.trackers.delete(e),this.emit("private:trackerStopped"))}monitorTitle(){if(this.titleMonitored)return;this.titleMonitored=!0,this.fixTitle();const e=document.querySelector("title");if(e){const t=new MutationObserver((()=>{this.fixTitle()}));t.observe(e,{childList:!0}),this.titleObserver=t}}fixTitle(){const e=document.title,t="[Userflow Preview] "+e.replace(/\[Userflow Preview\] /,"");e!==t&&(document.title=t)}reportCspIssue(){const e=this.getSessionStorageState();!this.testUserIdentified&&!e.activeApp||this.cspIssueReported||(this.cspIssueReported=!0,nt("csp issue detected"),T({kind:"userflow:crxCspIssueDetected"}))}getAudio(){return this.audio||(this.audio=new Audio),this.audio}playAudio(e){if(document.hidden)return;const t=this.getAudio();e&&(t.src=e);const s=t.play();this.audioReady=!0,s&&s.catch((e=>{e.name}))}pauseAudio(){const e=this.audio;e&&!e.paused&&e.pause()}async getStepSpeech(e,t){return(await this.send({kind:"GetStepSpeechV2",syntheticVoice:e,text:t})).url}featureFlagEnabled(e){return this.featureFlags.has(e)}showNotification(e,t,s){const i={id:++this.notificationIdCounter,label:e,message:t,type:s};this.notifications=[...this.notifications,i],this.toggleUI()}dismissNotification(e){this.notifications=this.notifications.filter((t=>t.id!==e)),this.toggleUI()}warn(...e){console.warn(...e)}nextRef(){return this.refCounter++}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new Et;return{_stubbed:!1,init(t){e.init(t)},identify:(t,s={},i={})=>e.identify(t,s,i),identifyAnonymous:(t={},s={})=>e.identifyAnonymous(t,s),isIdentified:()=>e.isIdentified(),updateUser:(t,s={})=>e.updateUser(t,s),group:(t,s={},i={})=>e.group(t,s,i),updateGroup:(t,s={})=>e.updateGroup(t,s),track:(t,s={},i={})=>e.track(t,s,i),start:(t,{once:s}={})=>e.startFlow({flowId:t,startReason:L.USERFLOWJS,once:s}),startFlow:e=>(console.warn("Userflow.js: userflow.startFlow() has been deprecated. Use userflow.start() instead."),window.userflow.start(e)),startWalk:e=>(console.warn("Userflow.js: userflow.startWalk() has been deprecated. Use userflow.start() instead."),window.userflow.start(e)),endAll:()=>e.endAllFlows(),endChecklist:()=>e.endChecklist(),endAllFlows:()=>window.userflow.endAll(),async endFlow(){console.warn("Userflow.js: userflow.endFlow() has been deprecated and no longer has any effect.")},async endWalk(){console.warn("Userflow.js: userflow.endWalk() has been deprecated and no longer has any effect.")},openResourceCenter(){e.openResourceCenter()},closeResourceCenter(){e.closeResourceCenter()},toggleResourceCenter(){e.toggleResourceCenter()},setResourceCenterLauncherHidden(t){e.setResourceCenterLauncherHidden(t)},getResourceCenterState:()=>e.getResourceCenterState(),setWalkPosition(){console.warn("Userflow.js: userflow.setWalkPosition() has been deprecated and no longer has any effect.")},reset(){e.reset()},remount(){e.remount()},on(t,s){e.on(t,s)},off(t,s){e.off(t,s)},setCustomInputSelector(e){console.warn("Userflow.js: userflow.setCustomInputSelector() has been deprecated. Use userflow.registerCustomInput() instead. See docs: https://userflow.com/docs/userflow-js"),e&&Qe.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Qe.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Qe.customNavigate=e},setUrlFilter(e){Qe.urlFilter=e},setInferenceAttributeNames(e){Qe.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Qe.inferenceAttributeFilters[e]=qe(t)},setInferenceClassNameFilter(e){Qe.inferenceClassNameFilters=qe(e)},setScrollPadding(e){Qe.scrollPadding=e},setCustomScrollIntoView(e){Qe.customScrollIntoView=e},prepareAudio(){e.playAudio(null)},setShadowDomEnabled(e){console.warn("Userflow.js: userflow.setShadowDomEnabled() has been deprecated. Please remove this call from your Userflow.js snippet. Shadow DOM is supported by default now.")},setPageTrackingDisabled(t){e.pageTrackingDisabled=t},setBaseZIndex(e){Qe.baseZIndex=e},setServerEndpoint(e){Qe.serverEndpoint=e},disableEvalJs(){Qe.evalJsDisabled=!0},_setTargetEnv(t){e.setTargetEnv(t)}}}());window.userflow=e,window.studio1=e,function(){const e=window.userflow,t=window.USERFLOWJS_QUEUE;if(delete window.USERFLOWJS_QUEUE,!t||0===t.length)return;nt(`processing ${t.length} items in the queue`);for(const[s,i,n]of t){if("function"!=typeof e[s]){console.error(`Userflow.js: Invalid method '${s}' in queue`);continue}const t=e[s](...n);i&&t&&"function"==typeof t.then&&t.then(i.resolve,i.reject)}nt("queue processed")}()}export{N as $,Le as A,ht as B,me as C,Y as D,m as E,P as F,a as G,We as H,X as I,ne as J,ce as K,j as L,Q as M,de as N,Pe as O,Ne as P,_e as Q,at as R,L as S,dt as T,o as U,re as V,He as W,De as X,Fe as Y,je as Z,n as _,B as a,F as b,Qe as c,nt as d,D as e,H as f,tt as g,Ie as h,c as i,ct as j,se as k,ee as l,ue as m,Ae as n,p as o,_ as p,d as q,Te as r,l as s,et as t,g as u,fe as v,pe as w,lt as x,V as y,W as z};export default window.userflow;
|