userflow.js-self-hosted 0.1.1002497 → 0.1.1002513

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/BubbleToolbar.js CHANGED
@@ -1 +1 @@
1
- import{r as e}from"./vendor.react.js";import{c as t,a as n,i as r,b as l}from"./flow-condition-types.js";import{b as o}from"./stylesheets.js";import{o as a}from"./vendor.obj-str.js";import{l as i,n as s,S as u,E as c,c as d,s as m,U as b,p,d as f}from"./userflow.js";import{S as h,a as w,V as g,b as v,c as E,T as y}from"./Icons.js";import{F as k}from"./vendor.fortawesome.react-fontawesome.js";import{f as _}from"./vendor.fortawesome.pro-solid-svg-icons.js";import{u as x}from"./vendor.react-i18next.js";import{u as j}from"./client-context.js";const q=e.createContext(null);function N(){const t=e.useContext(q);if(!t)throw new Error("useSession: Session was not set");return t}function S(n){const r=N(),[l,a]=e.useState(!1),i=o(r.data),s=function(t){const n=e.useRef(t),r=e.useRef(t);return t!==r.current&&JSON.stringify(t)!==JSON.stringify(r.current)&&(n.current=t),r.current=t,n.current}(n);return e.useLayoutEffect((()=>{if(s){return t[s.type].track({sessionData:i,condition:s,callback:e=>{a(e)}})}}),[i,s]),null!=s&&l}const C=({appearance:t,hidden:n,disabled:r,onMouseDown:l,onClick:o,text:i,active:s,children:u})=>e.createElement("button",{className:a({[ce(t)]:!0,"userflowjs-bubble-button--hidden":!!n,"userflowjs-bubble-button--active":!!s}),onMouseDown:l,onClick:o,disabled:r},u||e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},i));async function T(e,t,l){const{steps:o}=t.version;switch(l.type){case i.CLOSE_FLOW:switch(t.kind){case"launcher":await e.dismissLauncher(t,{endReason:c.ACTION});break;case"flow":case"checklist":await e.endFlow(t,{endReason:c.ACTION})}return;case i.EVAL_JS:try{const e=r(l.code||"",t.data);new Function('"use strict";\n'+e)()}catch(a){console.error(`Userflow.js: Evaluate JavaScript action failed.\n\nError:\n${a.stack||a.message||a}\n\nCode:\n${l.code}`)}return;case i.GO_TO_STEP:{if("flow"!==t.kind)return;const n=o.find((({crossVersionId:e})=>e===l.stepCvid));if(!n)throw new b("Action points to unknown step: "+l.stepCvid);return void(await e.goToStep(t,n))}case i.NAVIGATE:{if(!l.url)return void console.warn("Userflow.js: NAVIGATE action is missing url property");const e=O(l.url,{lookupAttribute:n(t.data)});return void(l.navigateTarget===s.NEW_TAB?window.open(e):d.customNavigate?d.customNavigate(e):window.setTimeout((()=>{m(e)}),0))}case i.SNOOZE:return void("flow"===t.kind&&l.timeValue&&l.timeUnit&&(e.endFlow(t,{endReason:c.SNOOZED,batch:!0}),t.draftMode?window.alert(`In preview mode, flows can't be snoozed.\n\nBut if this flow was running in published mode, the flow would now be snoozed for ${l.timeValue} ${l.timeUnit.toLowerCase()+(1===l.timeValue?"":"s")}.`):e.send({kind:"Snooze",flowId:t.flow.id,timeValue:l.timeValue,timeUnit:l.timeUnit},{batch:!0})));case i.START_FLOW:return"launcher"===t.kind&&e.deactivateLauncher(t),void(l.otherFlow?await e.startFlow({flowId:l.otherFlow.id,stepCvid:l.otherFlowStepCvid,startReason:t.draftMode?u.DRAFT:u.ACTION,replaceCurrent:!0}):console.warn("Userflow.js: START_FLOW action is missing other flow"))}}async function I(e,t,n){const r=[],l=[],o=[];for(const a of n)a.type===i.NAVIGATE?a.navigateTarget===s.NEW_TAB?r.push(a):o.push(a):l.push(a);for(const a of r)T(e,t,a);await Promise.all(l.map((n=>T(e,t,n))));for(const a of o)T(e,t,a)}const P=({button:t})=>{const n=j(),l=N(),o=S(t.disabledCondition),a=S(t.hiddenCondition);return e.createElement(C,{appearance:t.appearance,hidden:a,disabled:o,onClick:()=>I(n,l,t.actions),text:r(t.text,l.data)})},A=({type:t,required:n,buttonText:r,options:l,otherOption:o,multipleSelection:i,shuffleOptions:s,labelLeft:u,labelCenter:c,labelRight:d,minValue:m,maxValue:b,onSubmit:f,inert:g})=>{const{t:v}=x(),E=e.useRef(null),[y,j]=e.useState(""),[q,N]=e.useState(new Set),[S,C]=e.useState(),[T,I]=e.useState(),[P,A]=e.useState(!1),[$,M]=e.useState(!1),[R,F]=e.useState(null),O=e.useMemo((()=>l&&(s?[...l].sort((()=>Math.random()-.5)):l)),[l,s]),U=e=>{if(!g&&f){if(n&&""===y&&[p.MULTILINE_TEXT,p.TEXT].includes(t))return F(v("question.requiredError")),void W();M(!0),F(null),f({...e,onCancel:()=>{M(!1)},onError:e=>{M(!1),F(e||"Sorry, something went wrong saving your answer. Please try again.")}})}},W=e.useCallback((()=>{!g&&E.current&&E.current.focus()}),[g]),[B,V]=e.useState(!1);e.useEffect((()=>{B&&(W(),V(!1))}),[W,B]);const D=e.createElement("div",{className:"userflowjs-bubble-question__button-row userflowjs-bubble-question__button-row--end"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:()=>U({answer:{kind:"text",value:y}}),tabIndex:g?-1:void 0,disabled:$},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||v("question.submit"))));let z=null,K=0;if(t===p.NPS)u=u||v("question.npsLabelLeft"),d=d||v("question.npsLabelRight"),z=[0,1,2,3,4,5,6,7,8,9,10],K=z.length;else if([p.SCALE,p.STARS].includes(t)){b=null!=b?b:5,z=[];for(let e=m=null!=m?m:1;e<=b;e++)z.push(e);K=z.length}else t===p.MULTIPLE_CHOICE&&(K=(O?O.length:0)+(o&&!P?1:0));const[J,H]=e.useState(-1),G=-1===J?-1:Math.min(J,K-1),X=e=>{if(!e.target.closest('[role="radio"], [role="checkbox"], [role="radiogroup"], [role="group"]'))return;let t=null;if("ArrowRight"===e.key||"ArrowDown"===e.key?t=1:"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(t=-1),null!=t){e.preventDefault();const n=e.currentTarget.querySelectorAll('[role="radio"], [role="checkbox"]');let r=G+t;r<0?r=n.length-1:r>n.length-1&&(r=0),H(r),n[r].focus()}};let Q,Z=null,Y=null;if(z&&(u||c||d)){const t=[];u&&t.push(z[0],u),d&&t.push(z[z.length-1],d),Z=e.createElement("div",{id:"a11y-scale-labels",className:"userflowjs-a11y-only"},t.join(", ")),Y=e.createElement("div",{id:"userflowjs-bubble-question-labels",className:"userflowjs-bubble-question__scale-labels","aria-hidden":"true"},e.createElement("div",{className:"userflowjs-bubble-question__scale-label"},u),c&&e.createElement("div",{className:"userflowjs-bubble-question__scale-label userflowjs-bubble-question__scale-label--center"},c),e.createElement("div",{className:"userflowjs-bubble-question__scale-label userflowjs-bubble-question__scale-label--right"},d))}switch(t){case p.MULTILINE_TEXT:Q=e.createElement(e.Fragment,null,e.createElement("textarea",{ref:E,className:"userflowjs-textarea userflowjs-bubble-question__textarea",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&"Enter"===e.key&&U({answer:{kind:"text",value:y}})},placeholder:v("question.placeholder"),readOnly:g||$,tabIndex:g?-1:void 0,rows:3,"aria-required":n?"true":void 0,"aria-invalid":null!=R?"true":void 0}),D);break;case p.MULTIPLE_CHOICE:{const t=()=>{y&&U({answer:{kind:"text",value:y},animationPromise:L()})},n=(O?.length||0)+(o?1:0),l=Math.max(0,Math.min(n,null==m?1:m)),s=Math.max(0,Math.min(n,null==b?n:b)),u=()=>{const e=(O||[]).filter(((e,t)=>q.has(t))).map((e=>e.value));o&&P&&""!==y&&e.push(y),l!==s||e.length===l?e.length<l?F(v("question.multiple_selection_too_few",{count:l})):e.length>s?F(v("question.multiple_selection_too_many",{count:s})):U({answer:{kind:"list",values:e}}):F(v("question.multiple_selection_wrong",{count:l}))};Q=e.createElement(e.Fragment,null,i&&e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice-hint":!0,"userflowjs-bubble-question__multiple-choice-hint--error":!!R})},v("question.multiple_selection_hint",{replace:{selected:q.size+(o&&P&&""!==y?1:0),range:l===s?l:`${l}-${s}`}}),R&&e.createElement(e.Fragment,null,". ",e.createElement("span",{role:"alert"},R))),e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice":!0,"userflowjs-bubble-question__multiple-choice--single-selection":!i,"userflowjs-bubble-question__multiple-choice--multiple-selection":!!i,"userflowjs-bubble-question__multiple-choice--other-option-active":!!o&&P}),role:i?"group":"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},O?.map((({value:t,label:n},r)=>e.createElement("button",{key:r,className:a({"userflowjs-bubble-question__multiple-choice-option":!0,"userflowjs-bubble-question__multiple-choice-option--selected":i?q.has(r):$&&!P&&y==t}),onClick:$?void 0:()=>{if(i){F(null);const e=new Set(q);q.has(r)?e.delete(r):e.add(r),N(e)}else A(!1),j(t),U({answer:{kind:"text",value:t},animationPromise:L()})},disabled:$,tabIndex:g||r!==G?-1:0,role:i?"checkbox":"radio","aria-label":n||t,"aria-checked":!P&&y==t},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-option-text","aria-hidden":"true"},n||t)))),o&&(P?e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice-option":!0,"userflowjs-bubble-question__multiple-choice-option--other":!0,"userflowjs-bubble-question__multiple-choice-option--selected":i?""!=y:$})},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox",onClick:()=>{j(""),A(!1)}},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("input",{ref:E,className:"userflowjs-bubble-question__multiple-choice-option-input",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key?"Escape"===e.key&&(e.stopPropagation(),j(""),A(!1)):i?u():t()},onBlur:()=>{""===y&&A(!1)},placeholder:v("question.placeholder"),readOnly:g||$,tabIndex:g?-1:void 0}),!i&&e.createElement("button",{"data-testid":"multiple-choice-other-submit",className:"userflowjs-bubble-question__multiple-choice-option-submit",onClick:()=>t(),disabled:$,"aria-label":v("question.submit")},e.createElement(w,null))):e.createElement("button",{className:"userflowjs-bubble-question__multiple-choice-option",onClick:$?void 0:()=>{F(null),A(!0),V(!0)},disabled:$,tabIndex:g||O?.length!==G?-1:0,role:"radio","aria-label":v("question.other"),"aria-checked":"false"},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-option-text","aria-hidden":"true"},v("question.other"))))),i&&e.createElement("div",{className:"userflowjs-bubble-question__button-row"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:u,tabIndex:g?-1:void 0,disabled:$},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||v("question.submit")))));break}case p.NPS:case p.SCALE:Q=e.createElement(e.Fragment,null,Z,e.createElement("div",{className:"userflowjs-bubble-question__scale-options",role:"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},z?.map(((t,n)=>e.createElement("button",{className:a({"userflowjs-bubble-question__scale-option":!0,"userflowjs-bubble-question__scale-option--selected":$&&S==t}),key:t,tabIndex:g||n!==G?-1:0,onClick:()=>{C(t),U({answer:{kind:"number",value:t},animationPromise:L()})},disabled:$,role:"radio","aria-checked":S==t},t)))),Y);break;case p.STARS:Q=e.createElement("div",{className:"userflowjs-bubble-question__stars-wrapper"},Z,e.createElement("div",{className:"userflowjs-bubble-question__stars",role:"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},z?.map(((t,n)=>e.createElement("button",{className:a({"userflowjs-bubble-question__star":!0,"userflowjs-bubble-question__star--hovered":!$&&null!=T&&T>=t,"userflowjs-bubble-question__star--selected":$&&null!=S&&S>=t,"userflowjs-bubble-question__star--not-selected":$&&null!=S&&S<t}),key:t,tabIndex:g||n!==G?-1:0,onClick:()=>{C(t),U({answer:{kind:"number",value:t},animationPromise:L()})},onMouseOver:()=>I(t),onMouseLeave:()=>I(null),disabled:$,role:"radio","aria-checked":S==t,"aria-label":String(t)},e.createElement("div",{className:"userflowjs-bubble-question__star-icon","aria-hidden":"true"},e.createElement(h,null)),e.createElement("div",{className:"userflowjs-bubble-question__star-value","aria-hidden":"true"},t))))),Y);break;case p.TEXT:Q=e.createElement(e.Fragment,null,e.createElement("input",{ref:E,className:"userflowjs-text-input userflowjs-bubble-question__text-input",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||U({answer:{kind:"text",value:y}})},placeholder:v("question.placeholder"),readOnly:g||$,tabIndex:g?-1:void 0,"aria-required":n?"true":void 0,"aria-invalid":null!=R?"true":void 0}),D)}return e.createElement("div",{className:"userflowjs-bubble-question",style:{pointerEvents:g?"none":void 0}},R&&!(t===p.MULTIPLE_CHOICE&&i)&&e.createElement("div",{className:"userflowjs-bubble-question__error",role:"alert"},R),Q)};function L(){return new Promise((e=>window.setTimeout(e,250)))}const $=({question:t})=>{const n=j(),r=function(){const e=N();if("flow"!==e.kind)throw new Error("useFlowSession: Wrong session kind");return e}();return e.createElement(A,{type:t.type,required:!!t.required,buttonText:t.buttonText||"",options:t.options,otherOption:t.otherOption,multipleSelection:t.multipleSelection,shuffleOptions:t.shuffleOptions,labelLeft:t.labelLeft||"",labelCenter:t.labelCenter||"",labelRight:t.labelRight||"",minValue:t.minValue,maxValue:t.maxValue,onSubmit:async e=>{f("answerQuestion",r.id,t.cvid,e);const{answer:l}=e;try{await Promise.all([await n.send({kind:"AnswerQuestion",sessionId:r.id,questionName:t.name,questionCvid:t.cvid,textAnswer:"text"==l.kind?l.value:null,numberAnswer:"number"==l.kind?String(l.value):null,listAnswer:"list"==l.kind?l.values:null}),e.animationPromise])}catch(a){return console.log("Userflow.js: Error when answering question:",a),void e.onError()}const{bindAttributeFqn:o}=t;if(o&&n.flowSession?.id===r.id){let e;switch(l.kind){case"text":e={name:o,value:l.value};break;case"number":e={name:o,value:String(l.value)};break;case"list":e={name:o,value:l.values}}n.optimisticClockUIUpdate((()=>{n.setFlowSession({...r,data:[...r.data.filter((e=>e.name!==o)),e]})}))}I(n,r,t.actions)}})},M=({text:t})=>{if(!t)return null;const n=t.split(/\n/);return 1===n.length?e.createElement(e.Fragment,null,n[0]):e.createElement(e.Fragment,null,n.map(((t,n)=>e.createElement(e.Fragment,{key:n},n>0&&e.createElement("br",null),t))))};function R(e=""){return{type:"paragraph",children:[{text:e}]}}function F(e){if(e){let n;try{n=JSON.parse(e)}catch(t){throw new Error("Could not JSON.parse rich content doc: "+e)}if("rich2"===n.type)return n;throw new Error("Could not recognize rich content doc: "+e)}return function(e=""){return{type:"rich2",children:[R(e)]}}()}function O(e,{lookupAttribute:t}){if(!e)return"";"string"==typeof e&&(e=function(e){if(e){let n;try{n=JSON.parse(e)}catch(t){throw new Error("Could not JSON.parse plaintext doc: "+e)}if("plaintext2"===n.type)return n;throw new Error("Could not recognize plaintext doc: "+e)}return function(e=""){return{type:"plaintext2",children:[{type:"plaintext",children:[{text:e}]}]}}()}(e));const n=[];function r(e){e&&e.forEach((e=>e&&function(e){if(ae(e))e.text&&n.push(e.text);else switch(e.type){case"attribute":{const r=re(e,t);r&&n.push(r);break}default:r(e.children)}}(e)))}return r(e.children),n.join("")}function U(e){let t=!0;if(!e)return!0;"string"==typeof e&&(e=F(e));const n=new Set(["attribute","button","image","question","video"]);return ie(e,(e=>{ae(e)?""!==e.text&&(t=!1):"type"in e&&n.has(e.type)&&(t=!1)})),t}const W=e.memo((({doc:t,...n})=>t?("string"==typeof t&&(t=F(t)),e.createElement(B,{parent:t,...n})):null)),B=({parent:t,...n})=>e.createElement(e.Fragment,null,t.children.map(((r,l)=>ae(r)?e.createElement(V,{key:l,node:r}):e.createElement(z,{key:l,node:r,parent:t,...n})))),V=({node:t})=>t.text?e.createElement(D,{node:t},e.createElement(M,{text:t.text})):null,D=({node:t,children:n})=>(t.color&&"string"==typeof t.color&&(n=e.createElement("span",{style:{color:t.color}},n)),t.bold&&(n=e.createElement("b",null,n)),t.italic&&(n=e.createElement("i",null,n)),t.underline&&(n=e.createElement("u",null,n)),t.strikeThrough&&(n=e.createElement("s",null,n)),t.code&&(n=e.createElement("code",null,n)),t.sup&&(n=e.createElement("sup",null,n)),n),z=({node:t,parent:n,...r})=>{const{lookupAttribute:l}=r,o=e.createElement(B,{parent:t,...r});switch(t.type){case"attribute":return e.createElement(K,{node:t,...r});case"button":return e.createElement(J,{node:t,...r});case"button-group":return e.createElement("div",{className:"userflowjs-bubble-buttons"},o);case"column":return e.createElement("div",{style:te(t,n)},o);case"column-group":return e.createElement("div",{className:"p-like",style:ee(t)},o);case"container":return e.createElement("div",{className:"p-like"+(t.className?` ${t.className}`:""),style:ne(t)},o);case"image":return e.createElement(G,{node:t,...r});case"link":return e.createElement("a",{href:O(t.href,{lookupAttribute:l}),target:"_blank",rel:"noopener noreferrer"},o);case"paragraph":return e.createElement("p",{className:Z(t)},o);case"heading1":return e.createElement("h1",{className:Z(t)},o);case"heading2":return e.createElement("h2",{className:Z(t)},o);case"question":return e.createElement(H,{node:t,...r});case"quote":return e.createElement("blockquote",null,o);case"code-block":return e.createElement("pre",null,e.createElement("code",null,o));case"ordered-list":return e.createElement("ol",null,o);case"unordered-list":return e.createElement("ul",null,o);case"list-item":return e.createElement("li",null,o);case"video":return e.createElement(X,{node:t,...r});default:return e.createElement("div",null,o)}},K=({node:t,lookupAttribute:n})=>{let r=re(t,n);return e.createElement(D,{node:t},r)},J=({node:t,buttons:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement(P,{key:r.id,button:r}):null},H=({node:t,questions:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement($,{key:r.id,question:r}):null},G=({node:t,lookupAttribute:n})=>{const{src:r,widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m,hasLink:b,href:p}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:f,blockStyle:h}=Y({widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m});let w=e.createElement("img",{src:r,style:{...h,objectFit:"contain"}});return b&&p&&(w=e.createElement("a",{href:O(p,{lookupAttribute:n}),target:"_blank",rel:"noopener noreferrer",style:h},w)),e.createElement("div",{className:"p-like"},e.createElement("div",{style:f},w))},X=({node:t,lookupAttribute:n})=>{const{url:r,widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:b,blockStyle:p}=Y({widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m});return e.createElement("div",{className:"p-like"},e.createElement("div",{style:b},e.createElement("div",{style:p},e.createElement(Q,{element:t,noFocus:!0,lookupAttribute:n}))))},Q=({element:{embedType:t,url:n,src:r,autoPlay:o,controls:a,loop:i,muted:s},noFocus:u,forceMuted:c,lookupAttribute:d})=>{if(!n)return null;const m={width:"100%",height:"100%",frameBorder:"0",allow:"accelerometer; autoplay; fullscreen; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,allowtransparency:"true",mozallowfullscreen:"true",webkitallowfullscreen:"true",oallowfullscreen:"true",msallowfullscreen:"true",style:{display:"block"},tabIndex:u?-1:void 0};if("video"===t)return e.createElement("video",{key:n+";"+String(o)+";"+String(a)+";"+String(i)+";"+String(s),src:n,style:{width:"100%",height:"100%",display:"block"},autoPlay:!!o,controls:!1!==a,loop:i,muted:c||s});if(r){let t;try{t=new URL(r)}catch(w){return null}return c&&(t.searchParams.has("autoplay")||t.searchParams.has("autoPlay"))&&(t.searchParams.set("mute","1"),t.searchParams.set("muted","1"),t.searchParams.set("volume","0")),e.createElement("iframe",{src:t.toString(),...m})}let b=function(e,{iframeFallback:t}={}){let n;try{n=new URL(e)}catch(w){return{kind:"invalid"}}const{hostname:r,pathname:l,searchParams:o}=n;if(r.match(/^(www\.)?(use)?loom\.com$/)){const e=l.match(/^\/share\/([a-z0-9]+)$/i);if(e){const[,t]=e;return{kind:"ok",videoProvider:"loom",videoId:t,searchParams:o}}}if(e.startsWith("raw:")){return{kind:"ok",videoProvider:"raw",videoId:e.replace(/^raw:/,""),searchParams:o}}if(e.startsWith("iframe:")){return{kind:"ok",videoProvider:"iframe",videoId:e.replace(/^iframe:/,""),searchParams:o}}if(["youtube.com","www.youtube.com"].includes(r)){const e=o.get("v");if(e)return o.delete("v"),{kind:"ok",videoProvider:"youtube",videoId:e,searchParams:o}}if("youtu.be"===r){const e=l.match(/^\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"youtube",videoId:t,searchParams:o}}}if("vimeo.com"===r){const e=l.match(/^\/(\d+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"vimeo",videoId:t,searchParams:o}}}if("player.vimeo.com"===r){const e=l.match(/^\/video\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"vimeo",videoId:t,searchParams:o}}}if(r.match(/^[^.]+\.wistia.com$/)){const e=l.match(/^\/medias\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"wistia",videoId:t,searchParams:o}}}return t?{kind:"ok",videoProvider:"iframe",videoId:e,searchParams:o}:{kind:"invalid"}}(n,{iframeFallback:!0});if("invalid"===b.kind)return null;const{videoProvider:p,videoId:f,searchParams:h}=b;switch(o=o||h.has("autoplay")||h.has("autoPlay"),p){case"iframe":return e.createElement("iframe",{src:l(f,(e=>encodeURIComponent(d(e)||""))),scrolling:h.get("scrolling")||void 0,...m});case"loom":return e.createElement("iframe",{src:`https://www.loom.com/embed/${f}?${h.toString()}`,...m});case"raw":return e.createElement("video",{src:f,controls:!0,style:{width:"100%",height:"100%",display:"block"},autoPlay:h.has("autoplay"),muted:c||h.has("muted")});case"youtube":return c&&o&&h.set("mute","1"),e.createElement("iframe",{src:`https://www.youtube.com/embed/${f}?${h.toString()}`,...m});case"vimeo":return c&&o&&h.set("muted","1"),e.createElement("iframe",{src:`https://player.vimeo.com/video/${f}?${h.toString()}`,...m});case"wistia":return h.set("videoFoam","true"),c&&o&&h.set("volume","0"),e.createElement(e.Fragment,null,e.createElement("iframe",{src:`https://fast.wistia.net/embed/iframe/${f}?${h.toString()}`,...m}))}};function Z(e){return"right"===e.align?"userflowjs-text-align-end":"center"===e.align?"userflowjs-text-align-center":""}function Y({widthMode:e,displayWidth:t,width:n,height:r,marginTop:l,marginRight:o,marginBottom:a,marginLeft:i,align:s}){const u={position:"relative"};"number"!=typeof t&&(t=100,e="percent"),"center"===s?(u.marginLeft="auto",u.marginRight="auto"):"right"===s&&(u.marginLeft="auto");let c=0;if(null!=l&&"number"==typeof l&&(u.marginTop=`${l}px`),null!=o&&"number"==typeof o&&(u.marginRight=`${o}px`,c+=o),null!=a&&"number"==typeof a&&(u.marginBottom=`${a}px`),null!=i&&"number"==typeof i&&(u.marginLeft=`${i}px`,c+=i),"number"!=typeof t||"number"!=typeof n||"number"!=typeof r)u.width="100px",u.height="100px";else if("px"===e){const e=10,l=Math.max(e,t);u.width=`${l}px`,u.height=l/(n/r)+"px"}else{const e=Math.max(0,Math.min(100,t));u.width=`calc(${e}% - ${c}px)`,u.height="0",u.paddingBottom=`calc((${e}% - ${c}px) / (${n} / ${r})`}return{wrapperStyle:u,blockStyle:{position:"absolute",top:"0",left:"0",display:"block",width:"100%",height:"100%"}}}function ee(e){return{display:"flex",alignItems:"stretch",marginRight:`-${null==e.spacing?16:e.spacing}px`}}function te(e,t){const n="fill"===e.widthMode||null==e.displayWidth;return{display:"flex",flexDirection:"column",justifyContent:e.justifyContent,width:n?void 0:"px"===e.widthMode?`${e.displayWidth||50}px`:"percent"===e.widthMode?`${e.displayWidth||50}%`:void 0,flex:n?"1 0 0":void 0,marginRight:`${null==t.spacing?16:t.spacing}px`,marginBottom:"0"}}function ne(e){return{display:"flex",flexDirection:"column",justifyContent:e.justifyContent,width:"px"===e.widthMode&&null!=e.displayWidth?`${e.displayWidth}px`:"percent"===e.widthMode&&null!=e.displayWidth?`${e.displayWidth}%`:void 0,minHeight:"px"===e.heightMode?`${e.displayHeight||50}px`:void 0,flex:"fill"===e.heightMode?"1 0 0":void 0,marginTop:null!=e.marginTop?`${e.marginTop}px`:void 0,marginRight:null!=e.marginRight?`${e.marginRight}px`:"fill"!==e.widthMode&&"center"===e.align?"auto":void 0,marginBottom:null!=e.marginBottom?`${e.marginBottom}px`:void 0,marginLeft:null!=e.marginLeft?`${e.marginLeft}px`:"fill"===e.widthMode||"center"!==e.align&&"right"!==e.align?void 0:"auto"}}function re(e,t){const n=e.attributeName;if("string"==typeof n){const r=t(n)||e.fallback;if("string"==typeof r)return r}return null}function le(e){return Array.isArray(e.children)&&void 0===e.addMark}function oe(e,t,n="type"){return le(e)&&e[n]===t}function ae(e){return"string"==typeof e.text}function ie(e,t){function n(e){e&&e.forEach(((e,r)=>e&&function(e,r){t(e,r),le(e)&&n(e.children)}(e,r)))}n(Array.isArray(e)?e:e.children)}const se=e.memo((({doc:t,lookupAttribute:n})=>t?e.createElement(e.Fragment,null,O(t,{lookupAttribute:n})):null));function ue(e,{buttons:t,questions:n}){const r=new Set,l=new Set;if(ie(e,(e=>{oe(e,"button")&&r.add(e.cvid),oe(e,"question")&&l.add(e.cvid)})),n){const t=n.filter((e=>!l.has(e.cvid)));t.length>0&&(e={...e,children:[...e.children,...t.map((e=>({type:"question",cvid:e.cvid,children:[{text:""}]})))]})}if(t){const n=t.filter((e=>!r.has(e.cvid)));n.length>0&&(e={...e,children:[...e.children,{type:"button-group",children:n.map((e=>({type:"button",cvid:e.cvid,children:[{text:""}]})))}]})}return e}function ce(e){return"userflowjs-bubble-button "+("primary"===(e=e||"default")||"PRIMARY"===e?"userflowjs-bubble-button--primary":"default"===e||"DEFAULT"===e?"userflowjs-bubble-button--default":e)}var de=new URL("flow-host.css",import.meta.url).href,me=new URL("bubble-frame.css",import.meta.url).href;const be=({draftMode:t,muted:n,toggleMuted:r,close:l,minimize:o})=>{const{t:a}=x();return e.createElement("div",{className:"userflowjs-bubble-toolbar"},t&&e.createElement("div",{className:"userflowjs-bubble-draft"},"string"==typeof t?t:"Preview"),r&&e.createElement("button",{className:"userflowjs-bubble-toolbar-button",onClick:r,"aria-label":n?"Unmute":"Mute"},n?e.createElement(g,null):e.createElement(v,null)),o&&e.createElement("button",{"data-testid":"minimize-button",className:"userflowjs-bubble-toolbar-button",onClick:o,"aria-label":"Minimize checklist"},e.createElement(E,null)),l&&e.createElement("button",{"data-testid":"close-button",className:"userflowjs-bubble-toolbar-button",onClick:l,"aria-label":a("menu.close")},e.createElement(y,null)))};export{be as B,W as R,q as S,se as a,me as b,C as c,F as d,N as e,de as f,re as g,I as h,ae as i,ue as m,U as r,O as s,S as u};
1
+ import{r as e}from"./vendor.react.js";import{c as t,a as n,i as r,b as l}from"./flow-condition-types.js";import{b as o}from"./stylesheets.js";import{o as a}from"./vendor.obj-str.js";import{c as i,s,l as u,n as c,S as d,E as m,U as b,p,d as f}from"./userflow.js";import{S as h,a as w,V as g,b as v,c as E,T as y}from"./Icons.js";import{F as k}from"./vendor.fortawesome.react-fontawesome.js";import{f as _}from"./vendor.fortawesome.pro-solid-svg-icons.js";import{u as x}from"./vendor.react-i18next.js";import{u as j}from"./client-context.js";const q=e.createContext(null);function N(){const t=e.useContext(q);if(!t)throw new Error("useSession: Session was not set");return t}function S(n){const r=N(),[l,a]=e.useState(!1),i=o(r.data),s=function(t){const n=e.useRef(t),r=e.useRef(t);return t!==r.current&&JSON.stringify(t)!==JSON.stringify(r.current)&&(n.current=t),r.current=t,n.current}(n);return e.useLayoutEffect((()=>{if(s){return t[s.type].track({sessionData:i,condition:s,callback:e=>{a(e)}})}}),[i,s]),null!=s&&l}const C=({appearance:t,hidden:n,disabled:r,onMouseDown:l,onClick:o,text:i,active:s,children:u})=>e.createElement("button",{className:a({[de(t)]:!0,"userflowjs-bubble-button--hidden":!!n,"userflowjs-bubble-button--active":!!s}),onMouseDown:l,onClick:o,disabled:r},u||e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},i));function T(e){i.customNavigate?i.customNavigate(e):window.setTimeout((()=>{s(e)}),0)}async function I(e,t,l){const{steps:o}=t.version;switch(l.type){case u.CLOSE_FLOW:switch(t.kind){case"launcher":await e.dismissLauncher(t,{endReason:m.ACTION});break;case"flow":case"checklist":await e.endFlow(t,{endReason:m.ACTION})}return;case u.EVAL_JS:try{const e=r(l.code||"",t.data);new Function('"use strict";\n'+e)()}catch(a){console.error(`Userflow.js: Evaluate JavaScript action failed.\n\nError:\n${a.stack||a.message||a}\n\nCode:\n${l.code}`)}return;case u.GO_TO_STEP:{if("flow"!==t.kind)return;const n=o.find((({crossVersionId:e})=>e===l.stepCvid));if(!n)throw new b("Action points to unknown step: "+l.stepCvid);return void(await e.goToStep(t,n))}case u.NAVIGATE:{if(!l.url)return void console.warn("Userflow.js: NAVIGATE action is missing url property");const e=U(l.url,{lookupAttribute:n(t.data)});return void(l.navigateTarget===c.NEW_TAB?window.open(e):T(e))}case u.SNOOZE:return void("flow"===t.kind&&l.timeValue&&l.timeUnit&&(e.endFlow(t,{endReason:m.SNOOZED,batch:!0}),t.draftMode?window.alert(`In preview mode, flows can't be snoozed.\n\nBut if this flow was running in published mode, the flow would now be snoozed for ${l.timeValue} ${l.timeUnit.toLowerCase()+(1===l.timeValue?"":"s")}.`):e.send({kind:"Snooze",flowId:t.flow.id,timeValue:l.timeValue,timeUnit:l.timeUnit},{batch:!0})));case u.START_FLOW:return"launcher"===t.kind&&e.deactivateLauncher(t),void(l.otherFlow?await e.startFlow({flowId:l.otherFlow.id,stepCvid:l.otherFlowStepCvid,startReason:t.draftMode?d.DRAFT:d.ACTION,replaceCurrent:!0}):console.warn("Userflow.js: START_FLOW action is missing other flow"))}}async function P(e,t,n){const r=[],l=[],o=[];for(const a of n)a.type===u.NAVIGATE?a.navigateTarget===c.NEW_TAB?r.push(a):o.push(a):l.push(a);for(const a of r)I(e,t,a);await Promise.all(l.map((n=>I(e,t,n))));for(const a of o)I(e,t,a)}const A=({button:t})=>{const n=j(),l=N(),o=S(t.disabledCondition),a=S(t.hiddenCondition);return e.createElement(C,{appearance:t.appearance,hidden:a,disabled:o,onClick:()=>P(n,l,t.actions),text:r(t.text,l.data)})},L=({type:t,required:n,buttonText:r,options:l,otherOption:o,multipleSelection:i,shuffleOptions:s,labelLeft:u,labelCenter:c,labelRight:d,minValue:m,maxValue:b,onSubmit:f,inert:g})=>{const{t:v}=x(),E=e.useRef(null),[y,j]=e.useState(""),[q,N]=e.useState(new Set),[S,C]=e.useState(),[T,I]=e.useState(),[P,A]=e.useState(!1),[L,M]=e.useState(!1),[R,F]=e.useState(null),O=e.useMemo((()=>l&&(s?[...l].sort((()=>Math.random()-.5)):l)),[l,s]),U=e=>{if(!g&&f){if(n&&""===y&&[p.MULTILINE_TEXT,p.TEXT].includes(t))return F(v("question.requiredError")),void W();M(!0),F(null),f({...e,onCancel:()=>{M(!1)},onError:e=>{M(!1),F(e||"Sorry, something went wrong saving your answer. Please try again.")}})}},W=e.useCallback((()=>{!g&&E.current&&E.current.focus()}),[g]),[B,V]=e.useState(!1);e.useEffect((()=>{B&&(W(),V(!1))}),[W,B]);const D=e.createElement("div",{className:"userflowjs-bubble-question__button-row userflowjs-bubble-question__button-row--end"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:()=>U({answer:{kind:"text",value:y}}),tabIndex:g?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||v("question.submit"))));let z=null,K=0;if(t===p.NPS)u=u||v("question.npsLabelLeft"),d=d||v("question.npsLabelRight"),z=[0,1,2,3,4,5,6,7,8,9,10],K=z.length;else if([p.SCALE,p.STARS].includes(t)){b=null!=b?b:5,z=[];for(let e=m=null!=m?m:1;e<=b;e++)z.push(e);K=z.length}else t===p.MULTIPLE_CHOICE&&(K=(O?O.length:0)+(o&&!P?1:0));const[J,H]=e.useState(-1),G=-1===J?-1:Math.min(J,K-1),X=e=>{if(!e.target.closest('[role="radio"], [role="checkbox"], [role="radiogroup"], [role="group"]'))return;let t=null;if("ArrowRight"===e.key||"ArrowDown"===e.key?t=1:"ArrowLeft"!==e.key&&"ArrowUp"!==e.key||(t=-1),null!=t){e.preventDefault();const n=e.currentTarget.querySelectorAll('[role="radio"], [role="checkbox"]');let r=G+t;r<0?r=n.length-1:r>n.length-1&&(r=0),H(r),n[r].focus()}};let Q,Z=null,Y=null;if(z&&(u||c||d)){const t=[];u&&t.push(z[0],u),d&&t.push(z[z.length-1],d),Z=e.createElement("div",{id:"a11y-scale-labels",className:"userflowjs-a11y-only"},t.join(", ")),Y=e.createElement("div",{id:"userflowjs-bubble-question-labels",className:"userflowjs-bubble-question__scale-labels","aria-hidden":"true"},e.createElement("div",{className:"userflowjs-bubble-question__scale-label"},u),c&&e.createElement("div",{className:"userflowjs-bubble-question__scale-label userflowjs-bubble-question__scale-label--center"},c),e.createElement("div",{className:"userflowjs-bubble-question__scale-label userflowjs-bubble-question__scale-label--right"},d))}switch(t){case p.MULTILINE_TEXT:Q=e.createElement(e.Fragment,null,e.createElement("textarea",{ref:E,className:"userflowjs-textarea userflowjs-bubble-question__textarea",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&"Enter"===e.key&&U({answer:{kind:"text",value:y}})},placeholder:v("question.placeholder"),readOnly:g||L,tabIndex:g?-1:void 0,rows:3,"aria-required":n?"true":void 0,"aria-invalid":null!=R?"true":void 0}),D);break;case p.MULTIPLE_CHOICE:{const t=()=>{y&&U({answer:{kind:"text",value:y},animationPromise:$()})},n=(O?.length||0)+(o?1:0),l=Math.max(0,Math.min(n,null==m?1:m)),s=Math.max(0,Math.min(n,null==b?n:b)),u=()=>{const e=(O||[]).filter(((e,t)=>q.has(t))).map((e=>e.value));o&&P&&""!==y&&e.push(y),l!==s||e.length===l?e.length<l?F(v("question.multiple_selection_too_few",{count:l})):e.length>s?F(v("question.multiple_selection_too_many",{count:s})):U({answer:{kind:"list",values:e}}):F(v("question.multiple_selection_wrong",{count:l}))};Q=e.createElement(e.Fragment,null,i&&e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice-hint":!0,"userflowjs-bubble-question__multiple-choice-hint--error":!!R})},v("question.multiple_selection_hint",{replace:{selected:q.size+(o&&P&&""!==y?1:0),range:l===s?l:`${l}-${s}`}}),R&&e.createElement(e.Fragment,null,". ",e.createElement("span",{role:"alert"},R))),e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice":!0,"userflowjs-bubble-question__multiple-choice--single-selection":!i,"userflowjs-bubble-question__multiple-choice--multiple-selection":!!i,"userflowjs-bubble-question__multiple-choice--other-option-active":!!o&&P}),role:i?"group":"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},O?.map((({value:t,label:n},r)=>e.createElement("button",{key:r,className:a({"userflowjs-bubble-question__multiple-choice-option":!0,"userflowjs-bubble-question__multiple-choice-option--selected":i?q.has(r):L&&!P&&y==t}),onClick:L?void 0:()=>{if(i){F(null);const e=new Set(q);q.has(r)?e.delete(r):e.add(r),N(e)}else A(!1),j(t),U({answer:{kind:"text",value:t},animationPromise:$()})},disabled:L,tabIndex:g||r!==G?-1:0,role:i?"checkbox":"radio","aria-label":n||t,"aria-checked":!P&&y==t},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-option-text","aria-hidden":"true"},n||t)))),o&&(P?e.createElement("div",{className:a({"userflowjs-bubble-question__multiple-choice-option":!0,"userflowjs-bubble-question__multiple-choice-option--other":!0,"userflowjs-bubble-question__multiple-choice-option--selected":i?""!=y:L})},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox",onClick:()=>{j(""),A(!1)}},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("input",{ref:E,className:"userflowjs-bubble-question__multiple-choice-option-input",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key?"Escape"===e.key&&(e.stopPropagation(),j(""),A(!1)):i?u():t()},onBlur:()=>{""===y&&A(!1)},placeholder:v("question.placeholder"),readOnly:g||L,tabIndex:g?-1:void 0}),!i&&e.createElement("button",{"data-testid":"multiple-choice-other-submit",className:"userflowjs-bubble-question__multiple-choice-option-submit",onClick:()=>t(),disabled:L,"aria-label":v("question.submit")},e.createElement(w,null))):e.createElement("button",{className:"userflowjs-bubble-question__multiple-choice-option",onClick:L?void 0:()=>{F(null),A(!0),V(!0)},disabled:L,tabIndex:g||O?.length!==G?-1:0,role:"radio","aria-label":v("question.other"),"aria-checked":"false"},i?e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(k,{icon:_}))):e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio"},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-radio-inner"})),e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-option-text","aria-hidden":"true"},v("question.other"))))),i&&e.createElement("div",{className:"userflowjs-bubble-question__button-row"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:u,tabIndex:g?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||v("question.submit")))));break}case p.NPS:case p.SCALE:Q=e.createElement(e.Fragment,null,Z,e.createElement("div",{className:"userflowjs-bubble-question__scale-options",role:"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},z?.map(((t,n)=>e.createElement("button",{className:a({"userflowjs-bubble-question__scale-option":!0,"userflowjs-bubble-question__scale-option--selected":L&&S==t}),key:t,tabIndex:g||n!==G?-1:0,onClick:()=>{C(t),U({answer:{kind:"number",value:t},animationPromise:$()})},disabled:L,role:"radio","aria-checked":S==t},t)))),Y);break;case p.STARS:Q=e.createElement("div",{className:"userflowjs-bubble-question__stars-wrapper"},Z,e.createElement("div",{className:"userflowjs-bubble-question__stars",role:"radiogroup",tabIndex:g||-1!==G?-1:0,onKeyDown:X},z?.map(((t,n)=>e.createElement("button",{className:a({"userflowjs-bubble-question__star":!0,"userflowjs-bubble-question__star--hovered":!L&&null!=T&&T>=t,"userflowjs-bubble-question__star--selected":L&&null!=S&&S>=t,"userflowjs-bubble-question__star--not-selected":L&&null!=S&&S<t}),key:t,tabIndex:g||n!==G?-1:0,onClick:()=>{C(t),U({answer:{kind:"number",value:t},animationPromise:$()})},onMouseOver:()=>I(t),onMouseLeave:()=>I(null),disabled:L,role:"radio","aria-checked":S==t,"aria-label":String(t)},e.createElement("div",{className:"userflowjs-bubble-question__star-icon","aria-hidden":"true"},e.createElement(h,null)),e.createElement("div",{className:"userflowjs-bubble-question__star-value","aria-hidden":"true"},t))))),Y);break;case p.TEXT:Q=e.createElement(e.Fragment,null,e.createElement("input",{ref:E,className:"userflowjs-text-input userflowjs-bubble-question__text-input",value:y,onChange:e=>j(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||U({answer:{kind:"text",value:y}})},placeholder:v("question.placeholder"),readOnly:g||L,tabIndex:g?-1:void 0,"aria-required":n?"true":void 0,"aria-invalid":null!=R?"true":void 0}),D)}return e.createElement("div",{className:"userflowjs-bubble-question",style:{pointerEvents:g?"none":void 0}},R&&!(t===p.MULTIPLE_CHOICE&&i)&&e.createElement("div",{className:"userflowjs-bubble-question__error",role:"alert"},R),Q)};function $(){return new Promise((e=>window.setTimeout(e,250)))}const M=({question:t})=>{const n=j(),r=function(){const e=N();if("flow"!==e.kind)throw new Error("useFlowSession: Wrong session kind");return e}();return e.createElement(L,{type:t.type,required:!!t.required,buttonText:t.buttonText||"",options:t.options,otherOption:t.otherOption,multipleSelection:t.multipleSelection,shuffleOptions:t.shuffleOptions,labelLeft:t.labelLeft||"",labelCenter:t.labelCenter||"",labelRight:t.labelRight||"",minValue:t.minValue,maxValue:t.maxValue,onSubmit:async e=>{f("answerQuestion",r.id,t.cvid,e);const{answer:l}=e;try{await Promise.all([await n.send({kind:"AnswerQuestion",sessionId:r.id,questionName:t.name,questionCvid:t.cvid,textAnswer:"text"==l.kind?l.value:null,numberAnswer:"number"==l.kind?String(l.value):null,listAnswer:"list"==l.kind?l.values:null}),e.animationPromise])}catch(a){return console.log("Userflow.js: Error when answering question:",a),void e.onError()}const{bindAttributeFqn:o}=t;if(o&&n.flowSession?.id===r.id){let e;switch(l.kind){case"text":e={name:o,value:l.value};break;case"number":e={name:o,value:String(l.value)};break;case"list":e={name:o,value:l.values}}n.optimisticClockUIUpdate((()=>{n.setFlowSession({...r,data:[...r.data.filter((e=>e.name!==o)),e]})}))}P(n,r,t.actions)}})},R=({text:t})=>{if(!t)return null;const n=t.split(/\n/);return 1===n.length?e.createElement(e.Fragment,null,n[0]):e.createElement(e.Fragment,null,n.map(((t,n)=>e.createElement(e.Fragment,{key:n},n>0&&e.createElement("br",null),t))))};function F(e=""){return{type:"paragraph",children:[{text:e}]}}function O(e){if(e){let n;try{n=JSON.parse(e)}catch(t){throw new Error("Could not JSON.parse rich content doc: "+e)}if("rich2"===n.type)return n;throw new Error("Could not recognize rich content doc: "+e)}return function(e=""){return{type:"rich2",children:[F(e)]}}()}function U(e,{lookupAttribute:t}){if(!e)return"";"string"==typeof e&&(e=function(e){if(e){let n;try{n=JSON.parse(e)}catch(t){throw new Error("Could not JSON.parse plaintext doc: "+e)}if("plaintext2"===n.type)return n;throw new Error("Could not recognize plaintext doc: "+e)}return function(e=""){return{type:"plaintext2",children:[{type:"plaintext",children:[{text:e}]}]}}()}(e));const n=[];function r(e){e&&e.forEach((e=>e&&function(e){if(ie(e))e.text&&n.push(e.text);else switch(e.type){case"attribute":{const r=le(e,t);r&&n.push(r);break}default:r(e.children)}}(e)))}return r(e.children),n.join("")}function W(e){let t=!0;if(!e)return!0;"string"==typeof e&&(e=O(e));const n=new Set(["attribute","button","image","question","video"]);return se(e,(e=>{ie(e)?""!==e.text&&(t=!1):"type"in e&&n.has(e.type)&&(t=!1)})),t}const B=e.memo((({doc:t,...n})=>t?("string"==typeof t&&(t=O(t)),e.createElement(V,{parent:t,...n})):null)),V=({parent:t,...n})=>e.createElement(e.Fragment,null,t.children.map(((r,l)=>ie(r)?e.createElement(D,{key:l,node:r}):e.createElement(K,{key:l,node:r,parent:t,...n})))),D=({node:t})=>t.text?e.createElement(z,{node:t},e.createElement(R,{text:t.text})):null,z=({node:t,children:n})=>(t.color&&"string"==typeof t.color&&(n=e.createElement("span",{style:{color:t.color}},n)),t.bold&&(n=e.createElement("b",null,n)),t.italic&&(n=e.createElement("i",null,n)),t.underline&&(n=e.createElement("u",null,n)),t.strikeThrough&&(n=e.createElement("s",null,n)),t.code&&(n=e.createElement("code",null,n)),t.sup&&(n=e.createElement("sup",null,n)),n),K=({node:t,parent:n,...r})=>{const{lookupAttribute:l}=r,o=e.createElement(V,{parent:t,...r});switch(t.type){case"attribute":return e.createElement(J,{node:t,...r});case"button":return e.createElement(H,{node:t,...r});case"button-group":return e.createElement("div",{className:"userflowjs-bubble-buttons"},o);case"column":return e.createElement("div",{style:ne(t,n)},o);case"column-group":return e.createElement("div",{className:"p-like",style:te(t)},o);case"container":return e.createElement("div",{className:"p-like"+(t.className?` ${t.className}`:""),style:re(t)},o);case"image":return e.createElement(X,{node:t,...r});case"link":return e.createElement("a",{href:U(t.href,{lookupAttribute:l}),target:"_blank",rel:"noopener noreferrer"},o);case"paragraph":return e.createElement("p",{className:Y(t)},o);case"heading1":return e.createElement("h1",{className:Y(t)},o);case"heading2":return e.createElement("h2",{className:Y(t)},o);case"question":return e.createElement(G,{node:t,...r});case"quote":return e.createElement("blockquote",null,o);case"code-block":return e.createElement("pre",null,e.createElement("code",null,o));case"ordered-list":return e.createElement("ol",null,o);case"unordered-list":return e.createElement("ul",null,o);case"list-item":return e.createElement("li",null,o);case"video":return e.createElement(Q,{node:t,...r});default:return e.createElement("div",null,o)}},J=({node:t,lookupAttribute:n})=>{let r=le(t,n);return e.createElement(z,{node:t},r)},H=({node:t,buttons:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement(A,{key:r.id,button:r}):null},G=({node:t,questions:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement(M,{key:r.id,question:r}):null},X=({node:t,lookupAttribute:n})=>{const{src:r,widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m,hasLink:b,href:p}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:f,blockStyle:h}=ee({widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m});let w=e.createElement("img",{src:r,style:{...h,objectFit:"contain"}});return b&&p&&(w=e.createElement("a",{href:U(p,{lookupAttribute:n}),target:"_blank",rel:"noopener noreferrer",style:h},w)),e.createElement("div",{className:"p-like"},e.createElement("div",{style:f},w))},Q=({node:t,lookupAttribute:n})=>{const{url:r,widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:b,blockStyle:p}=ee({widthMode:l,displayWidth:o,width:a,height:i,marginTop:s,marginRight:u,marginBottom:c,marginLeft:d,align:m});return e.createElement("div",{className:"p-like"},e.createElement("div",{style:b},e.createElement("div",{style:p},e.createElement(Z,{element:t,noFocus:!0,lookupAttribute:n}))))},Z=({element:{embedType:t,url:n,src:r,autoPlay:o,controls:a,loop:i,muted:s},noFocus:u,forceMuted:c,lookupAttribute:d})=>{if(!n)return null;const m={width:"100%",height:"100%",frameBorder:"0",allow:"accelerometer; autoplay; fullscreen; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,allowtransparency:"true",mozallowfullscreen:"true",webkitallowfullscreen:"true",oallowfullscreen:"true",msallowfullscreen:"true",style:{display:"block"},tabIndex:u?-1:void 0};if("video"===t)return e.createElement("video",{key:n+";"+String(o)+";"+String(a)+";"+String(i)+";"+String(s),src:n,style:{width:"100%",height:"100%",display:"block"},autoPlay:!!o,controls:!1!==a,loop:i,muted:c||s});if(r){let t;try{t=new URL(r)}catch(w){return null}return c&&(t.searchParams.has("autoplay")||t.searchParams.has("autoPlay"))&&(t.searchParams.set("mute","1"),t.searchParams.set("muted","1"),t.searchParams.set("volume","0")),e.createElement("iframe",{src:t.toString(),...m})}let b=function(e,{iframeFallback:t}={}){let n;try{n=new URL(e)}catch(w){return{kind:"invalid"}}const{hostname:r,pathname:l,searchParams:o}=n;if(r.match(/^(www\.)?(use)?loom\.com$/)){const e=l.match(/^\/share\/([a-z0-9]+)$/i);if(e){const[,t]=e;return{kind:"ok",videoProvider:"loom",videoId:t,searchParams:o}}}if(e.startsWith("raw:")){return{kind:"ok",videoProvider:"raw",videoId:e.replace(/^raw:/,""),searchParams:o}}if(e.startsWith("iframe:")){return{kind:"ok",videoProvider:"iframe",videoId:e.replace(/^iframe:/,""),searchParams:o}}if(["youtube.com","www.youtube.com"].includes(r)){const e=o.get("v");if(e)return o.delete("v"),{kind:"ok",videoProvider:"youtube",videoId:e,searchParams:o}}if("youtu.be"===r){const e=l.match(/^\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"youtube",videoId:t,searchParams:o}}}if("vimeo.com"===r){const e=l.match(/^\/(\d+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"vimeo",videoId:t,searchParams:o}}}if("player.vimeo.com"===r){const e=l.match(/^\/video\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"vimeo",videoId:t,searchParams:o}}}if(r.match(/^[^.]+\.wistia.com$/)){const e=l.match(/^\/medias\/([^/]+)$/);if(e){const[,t]=e;return{kind:"ok",videoProvider:"wistia",videoId:t,searchParams:o}}}return t?{kind:"ok",videoProvider:"iframe",videoId:e,searchParams:o}:{kind:"invalid"}}(n,{iframeFallback:!0});if("invalid"===b.kind)return null;const{videoProvider:p,videoId:f,searchParams:h}=b;switch(o=o||h.has("autoplay")||h.has("autoPlay"),p){case"iframe":return e.createElement("iframe",{src:l(f,(e=>encodeURIComponent(d(e)||""))),scrolling:h.get("scrolling")||void 0,...m});case"loom":return e.createElement("iframe",{src:`https://www.loom.com/embed/${f}?${h.toString()}`,...m});case"raw":return e.createElement("video",{src:f,controls:!0,style:{width:"100%",height:"100%",display:"block"},autoPlay:h.has("autoplay"),muted:c||h.has("muted")});case"youtube":return c&&o&&h.set("mute","1"),e.createElement("iframe",{src:`https://www.youtube.com/embed/${f}?${h.toString()}`,...m});case"vimeo":return c&&o&&h.set("muted","1"),e.createElement("iframe",{src:`https://player.vimeo.com/video/${f}?${h.toString()}`,...m});case"wistia":return h.set("videoFoam","true"),c&&o&&h.set("volume","0"),e.createElement(e.Fragment,null,e.createElement("iframe",{src:`https://fast.wistia.net/embed/iframe/${f}?${h.toString()}`,...m}))}};function Y(e){return"right"===e.align?"userflowjs-text-align-end":"center"===e.align?"userflowjs-text-align-center":""}function ee({widthMode:e,displayWidth:t,width:n,height:r,marginTop:l,marginRight:o,marginBottom:a,marginLeft:i,align:s}){const u={position:"relative"};"number"!=typeof t&&(t=100,e="percent"),"center"===s?(u.marginLeft="auto",u.marginRight="auto"):"right"===s&&(u.marginLeft="auto");let c=0;if(null!=l&&"number"==typeof l&&(u.marginTop=`${l}px`),null!=o&&"number"==typeof o&&(u.marginRight=`${o}px`,c+=o),null!=a&&"number"==typeof a&&(u.marginBottom=`${a}px`),null!=i&&"number"==typeof i&&(u.marginLeft=`${i}px`,c+=i),"number"!=typeof t||"number"!=typeof n||"number"!=typeof r)u.width="100px",u.height="100px";else if("px"===e){const e=10,l=Math.max(e,t);u.width=`${l}px`,u.height=l/(n/r)+"px"}else{const e=Math.max(0,Math.min(100,t));u.width=`calc(${e}% - ${c}px)`,u.height="0",u.paddingBottom=`calc((${e}% - ${c}px) / (${n} / ${r})`}return{wrapperStyle:u,blockStyle:{position:"absolute",top:"0",left:"0",display:"block",width:"100%",height:"100%"}}}function te(e){return{display:"flex",alignItems:"stretch",marginRight:`-${null==e.spacing?16:e.spacing}px`}}function ne(e,t){const n="fill"===e.widthMode||null==e.displayWidth;return{display:"flex",flexDirection:"column",justifyContent:e.justifyContent,width:n?void 0:"px"===e.widthMode?`${e.displayWidth||50}px`:"percent"===e.widthMode?`${e.displayWidth||50}%`:void 0,flex:n?"1 0 0":void 0,marginRight:`${null==t.spacing?16:t.spacing}px`,marginBottom:"0"}}function re(e){return{display:"flex",flexDirection:"column",justifyContent:e.justifyContent,width:"px"===e.widthMode&&null!=e.displayWidth?`${e.displayWidth}px`:"percent"===e.widthMode&&null!=e.displayWidth?`${e.displayWidth}%`:void 0,minHeight:"px"===e.heightMode?`${e.displayHeight||50}px`:void 0,flex:"fill"===e.heightMode?"1 0 0":void 0,marginTop:null!=e.marginTop?`${e.marginTop}px`:void 0,marginRight:null!=e.marginRight?`${e.marginRight}px`:"fill"!==e.widthMode&&"center"===e.align?"auto":void 0,marginBottom:null!=e.marginBottom?`${e.marginBottom}px`:void 0,marginLeft:null!=e.marginLeft?`${e.marginLeft}px`:"fill"===e.widthMode||"center"!==e.align&&"right"!==e.align?void 0:"auto"}}function le(e,t){const n=e.attributeName;if("string"==typeof n){const r=t(n)||e.fallback;if("string"==typeof r)return r}return null}function oe(e){return Array.isArray(e.children)&&void 0===e.addMark}function ae(e,t,n="type"){return oe(e)&&e[n]===t}function ie(e){return"string"==typeof e.text}function se(e,t){function n(e){e&&e.forEach(((e,r)=>e&&function(e,r){t(e,r),oe(e)&&n(e.children)}(e,r)))}n(Array.isArray(e)?e:e.children)}const ue=e.memo((({doc:t,lookupAttribute:n})=>t?e.createElement(e.Fragment,null,U(t,{lookupAttribute:n})):null));function ce(e,{buttons:t,questions:n}){const r=new Set,l=new Set;if(se(e,(e=>{ae(e,"button")&&r.add(e.cvid),ae(e,"question")&&l.add(e.cvid)})),n){const t=n.filter((e=>!l.has(e.cvid)));t.length>0&&(e={...e,children:[...e.children,...t.map((e=>({type:"question",cvid:e.cvid,children:[{text:""}]})))]})}if(t){const n=t.filter((e=>!r.has(e.cvid)));n.length>0&&(e={...e,children:[...e.children,{type:"button-group",children:n.map((e=>({type:"button",cvid:e.cvid,children:[{text:""}]})))}]})}return e}function de(e){return"userflowjs-bubble-button "+("primary"===(e=e||"default")||"PRIMARY"===e?"userflowjs-bubble-button--primary":"default"===e||"DEFAULT"===e?"userflowjs-bubble-button--default":e)}var me=new URL("flow-host.css",import.meta.url).href,be=new URL("bubble-frame.css",import.meta.url).href;const pe=({draftMode:t,muted:n,toggleMuted:r,close:l,minimize:o})=>{const{t:a}=x();return e.createElement("div",{className:"userflowjs-bubble-toolbar"},t&&e.createElement("div",{className:"userflowjs-bubble-draft"},"string"==typeof t?t:"Preview"),r&&e.createElement("button",{className:"userflowjs-bubble-toolbar-button",onClick:r,"aria-label":n?"Unmute":"Mute"},n?e.createElement(g,null):e.createElement(v,null)),o&&e.createElement("button",{"data-testid":"minimize-button",className:"userflowjs-bubble-toolbar-button",onClick:o,"aria-label":"Minimize checklist"},e.createElement(E,null)),l&&e.createElement("button",{"data-testid":"close-button",className:"userflowjs-bubble-toolbar-button",onClick:l,"aria-label":a("menu.close")},e.createElement(y,null)))};export{pe as B,B as R,q as S,ue as a,be as b,C as c,O as d,N as e,me as f,le as g,P as h,ie as i,ce as m,T as n,W as r,U as s,S as u};
@@ -1 +1 @@
1
- import{r as e}from"./vendor.react.js";import{h as t,C as r,i as s,c as o,j as n,k as c,E as l,l as a,m as i,S as u}from"./userflow.js";import{u as d,i as m}from"./client-context.js";import{u as f,w,C as h}from"./Icons.js";import{b as E,h as b,B as p,R as k,a as v,s as g,f as j}from"./BubbleToolbar.js";import{M as C,g as S,a as y}from"./flow-condition-types.js";import{u as N,a as _,g as x}from"./stylesheets.js";import{u as I,F as T,S as R}from"./logomark.js";import{o as L}from"./vendor.obj-str.js";import{D as B}from"./DynamicIcon.js";import{f as H,C as M}from"./ChecklistUI.js";import{f as W,a as F,b as P,c as $,d as A,e as O,g as z,h as U,i as q}from"./vendor.fortawesome.pro-regular-svg-icons.js";import{u as D}from"./vendor.react-i18next.js";import"./vendor.object-assign.js";import"./vendor.phoenix.js";import"./vendor.uuid.js";import"./vendor.i18next.js";import"./vendor.fortawesome.react-fontawesome.js";import"./vendor.fortawesome.fontawesome-svg-core.js";import"./vendor.prop-types.js";import"./vendor.fortawesome.pro-solid-svg-icons.js";import"./vendor.date-fns.js";import"./vendor.react-dom.js";import"./vendor.scheduler.js";import"./vendor.babel.runtime.js";function K(e){return e!==t.ACTION&&e!==t.CONTACT&&e!==t.FLOWS&&e!==t.KNOWLEDGE_BASE&&e!==t.SUBPAGE}const Q=window,V={[r.CRISP]:{configure:({onShow:e,onHide:t})=>{Q.$crisp||(Q.$crisp=[]),Q.$crisp.push(["do","chat:hide"]);let r=!1,s=!1;const o=()=>{r||s?(Q.$crisp.push(["do","chat:show"]),e()):(Q.$crisp.push(["do","chat:hide"]),t())},n=()=>{r=!0,o()};Q.$crisp.push(["on","chat:opened",n]);const c=()=>{r=!1,o()};Q.$crisp.push(["on","chat:closed",c]);const l=()=>{s=!0,o()};Q.$crisp.push(["on","message:received",l]);const a=window.setInterval((()=>{const e=(()=>{const e=document.getElementById("crisp-chatbox");if(!e||"block"!==window.getComputedStyle(e).display)return!1;const t=e.querySelector('[data-id="new_messages"]');return!(!t||"block"!==window.getComputedStyle(t).display)})();e!==s&&(s=e,o())}),200);return()=>{Q.$crisp.push(["off","chat:opened",n]),Q.$crisp.push(["off","chat:closed",c]),Q.$crisp.push(["off","message:received",l]),window.clearInterval(a)}},show:()=>{Q.$crisp.push(["do","chat:show"]),Q.$crisp.push(["do","chat:open"])},hide:()=>{Q.$crisp.push(["do","chat:hide"]),Q.$crisp.push(["do","chat:close"])}},[r.CUSTOM]:{configure:()=>()=>{},show:({block:e})=>{try{new Function('"use strict";\n'+e.chatCode)()}catch(t){console.error(`Userflow.js: Showing custom chat provider failed. Code: ${e.chatCode}`,t)}},hide:()=>{}},[r.FRESHCHAT]:{configure:({onShow:e,onHide:t})=>{if(!Q.fcWidget)throw new Error("Freshchat is not installed");let r=!1,s=!1;const o=()=>{r||s?e():t()},n=()=>{r=!0,o()};Q.fcWidget.on("widget:opened",n);const c=()=>{r=!1,o()};Q.fcWidget.on("widget:closed",c);const l=()=>{const e=!!document.querySelector("#fc_frame.h-open-notify");e!==s&&(s=e,o())},a=window.setInterval(l,200);return Q.fcWidget.on("unreadCount:notify",l),()=>{Q.fcWidget.off("widget:opened",n),Q.fcWidget.off("widget:closed",c),Q.fcWidget.off("unreadCount:notify",l),window.clearInterval(a)}},show:()=>{Q.fcWidget.open()},hide:()=>{Q.fcWidget.close()}},[r.HELPSCOUT]:{configure:({onShow:e,onHide:t})=>{if(!Q.Beacon)throw new Error("Help Scout is not installed");G();let r=!1,s=!1;const o=()=>{r||s?(Z(),e()):(G(),t())},n=()=>{r=!0,o()};Q.Beacon("on","open",n),Q.Beacon("info")?.status.isOpened&&n();const c=()=>{r=!1,o()};Q.Beacon("on","close",c);const l=window.setInterval((()=>{const e=!!document.querySelector(".BeaconNotificationsFrame");e!==s&&(s=e,o())}),200);return()=>{Q.Beacon("off","open",n),Q.Beacon("off","close",c),window.clearInterval(l)}},show:()=>{Z(),Q.Beacon("open")},hide:()=>{G(),Q.Beacon("close")}},[r.HUBSPOT]:{configure:({onShow:e,onHide:t})=>{const r=()=>{const r=document.getElementById("hubspot-messages-iframe-container");if(!Q.HubSpotConversations||!r)return;window.clearInterval(o),Y?J():X();let n=!1,c=!1;const l=()=>{n||c?(J(),e()):(X(),t())},a=()=>{const e=!!document.querySelector("#hubspot-messages-iframe-container .shadow-container.active");e!==n&&(n=e,l())},i=new C(a);i.observe(r,{attributes:!0,subtree:!0,attributeFilter:["class"]}),a();const u=({unreadCount:e})=>{const t=e>0;t!==c&&(c=t,l())};Q.HubSpotConversations.on("unreadConversationCountChanged",u),s=()=>{i.disconnect(),Q.HubSpotConversations.off("unreadConversationCountChanged",u)}};let s=()=>{window.clearInterval(o)};const o=window.setInterval(r,100);return r(),()=>{s()}},show:()=>{J(),Q.HubSpotConversations.widget.open()},hide:()=>{X(),Q.HubSpotConversations.widget.close()}},[r.INTERCOM]:{configure:({onShow:e,onHide:t})=>{if(!Q.Intercom)throw new Error("Intercom is not installed");return oe(),function(){if(ee)return;ee=!0;let e=!1,t=!1;const r=()=>{se();for(const e of te)e()},s=()=>{oe();for(const e of re)e()},o=()=>{e||t?r():s()};Q.Intercom("onShow",(()=>{e=!0,o()})),Q.Intercom("onHide",(()=>{e=!1,o()}));const n=()=>{const e=!!document.querySelector('iframe[name="intercom-borderless-frame"], iframe[name="intercom-notifications-frame"]');t!==e&&(t=e,o())};Q.Intercom("onUnreadCountChange",(()=>{n()})),window.setInterval(n,200)}(),te.add(e),re.add(t),()=>{te.delete(e),re.delete(t)}},show:()=>{se(),Q.Intercom("show")},hide:()=>{oe(),Q.Intercom("hide")}},[r.ZENDESK]:{configure:({onShow:e,onHide:t})=>{if(!Q.zE)throw new Error("Zendesk is not installed");!function(){if(ne)return;ne=!0,Q.zE("webWidget:on","open",(()=>{for(const e of ce)e()})),Q.zE("webWidget:on","close",(()=>{for(const e of le)e()})),Q.zE("webWidget:on","chat:unreadMessages",(e=>{for(const t of ae)t(e)}))}(),Q.zE("webWidget","hide"),Q.zE("webWidget","close");let r=!1,s=!1;const o=()=>{r||s?(Q.zE("webWidget","show"),e()):(Q.zE("webWidget","hide"),t())},n=()=>{r=!0,s=!1,o()};ce.add(n);const c=()=>{r=!1,s=!1,o()};le.add(c);const l=e=>{const t=e>0;t!==s&&(s=t,o())};return ae.add(l),()=>{ce.delete(n),le.delete(c),ae.delete(l)}},show:()=>{Q.zE("webWidget","show"),Q.zE("webWidget","open")},hide:()=>{Q.zE("webWidget","hide"),Q.zE("webWidget","close")}},[r.ZENDESK_MESSENGER]:{configure:({onShow:e,onHide:t})=>{if(!Q.zE)throw new Error("Zendesk is not installed");let r=!1;const s=window.setInterval((()=>{const s=(()=>{const e=document.querySelector('iframe[title="Messaging window"]');return!!e?.parentElement&&"0px"!==window.getComputedStyle(e.parentElement).height})();s!==r&&(r=s,r?e():t())}),200);return()=>{window.clearInterval(s)}},show:()=>{Q.zE("messenger","open")},hide:()=>{Q.zE("messenger","close")}}};function Z(){Q.Beacon("config",{display:{style:"icon"}})}function G(){Q.Beacon("config",{display:{style:"manual"}})}let Y=!1;function J(){Y=!0;document.getElementById("hubspot-messages-iframe-container")?.style.setProperty("visibility","visible","important")}function X(){Y=!1;document.getElementById("hubspot-messages-iframe-container")?.style.setProperty("visibility","hidden","important")}let ee=!1,te=new Set,re=new Set;function se(){Q.Intercom("update",{hide_default_launcher:!1,vertical_padding:20})}function oe(){Q.Intercom("update",{hide_default_launcher:!0,vertical_padding:100})}let ne=!1,ce=new Set,le=new Set,ae=new Set;const ie=t=>e.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 100 100"},t),e.createElement("path",{fill:"currentColor",d:"M24.049 79.74h36.003c8.185 0 15.985-6.621 17.43-14.814l6.091-34.556h3.997c8.149 0 13.645 6.63 12.2 14.815l-7.051 40C91.274 93.363 83.474 100 75.288 100h-40c-8.185 0-13.645-6.667-12.2-14.815l.96-5.444Z"}),e.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M12.437 69.63h40c8.148 0 15.978-6.637 17.422-14.815l7.052-40C78.355 6.63 72.896 0 64.711 0h-40C16.533 0 8.726 6.63 7.281 14.815l-7.052 40C-1.215 62.963 4.252 69.63 12.437 69.63Zm33.628-33.798c3.756-2.064 8.725-4.795 9.907-11.844C57.385 15.458 50.065 8.983 42.168 9c-7.452 0-12.771 3.195-17.508 8.892-.858 1.034-.884 2.45-.053 3.212l3.472 3.196c.847.767 2.25.589 3.176-.406 2.842-3.068 4.869-4.83 8.51-4.83 2.864 0 6.077 1.934 5.59 4.847-.37 2.223-2.292 3.334-5.4 5.001l-.28.151c-3.582 1.92-8.134 4.362-9.124 10.247l-.16.956c-.055.28-.05.571.014.85.065.278.188.538.362.76.173.222.391.4.639.522.247.121.518.183.79.18h6.744a2.709 2.709 0 0 0 1.712-.688c.481-.426.81-1.01.934-1.657l.095-.556c.266-1.582 2.101-2.59 4.384-3.845ZM32.837 59c3.552 0 6.955-3.034 7.58-6.769.63-3.729-1.742-6.763-5.293-6.763-3.552 0-6.934 3.028-7.58 6.763C26.9 55.966 29.286 59 32.837 59Z"})),ue=()=>{const t=12;return e.createElement("div",{className:"userflowjs-spinner"},e.createElement("svg",{viewBox:"0 0 24 24",version:"1.1",xmlns:"http://www.w3.org/2000/svg"},e.createElement("circle",{className:"userflowjs-spinner__bg",fill:"none",cx:t,cy:t,r:10,style:{strokeWidth:"4px"}}),e.createElement("circle",{className:"userflowjs-spinner__fill",fill:"none",cx:t,cy:t,r:10,transform:"translate(12, 12) rotate(-90) translate(-12, -12)",style:{strokeWidth:"4px",strokeDasharray:20*Math.PI*.25+"px, 1000"}})))};function de(t){const r=d(),[s,o]=e.useState(!0),[n,c]=e.useState(!1),[l,a]=e.useState(null),[i,u]=e.useState(null),[m,f]=e.useState(null),w=e.useRef(0),h=e.useRef(null),E=e.useRef((()=>{}));return e.useEffect((()=>{const e=JSON.stringify(t);if(e===h.current)return;h.current=e;const s=++w.current;let n,l;let i=!1;E.current=async(e,t)=>{if(!i){i=!0,c(!0);try{const o=e(n,l);l=o;const u=await r.send(o,{handlesRejection:!0});if(s!==w.current)return;n=t(n,u),a(n),f(null)}catch(o){if(s!==w.current)return;f(o)}finally{i=!1,c(!1)}}},(async()=>{o(!0);try{l=t;const e=await r.send(t,{handlesRejection:!0});if(s!==w.current)return;n=e,a(n),u(t),f(null)}catch(e){if(s!==w.current)return;f(e)}finally{o(!1)}})()}),[r,t]),{loading:s,loadingMore:n,data:l,messageForData:i,error:m,loadMore:E.current}}function me(t,r){const[s,o]=e.useState(t),n=e.useRef(void 0),c=e.useCallback((e=>{window.clearTimeout(n.current),o(e),r(e)}),[r]),l=e.useCallback((e=>{window.clearTimeout(n.current),o(e),n.current=window.setTimeout((()=>{r(e)}),200)}),[r]);return e.useEffect((()=>()=>{window.clearTimeout(n.current)}),[]),[s,l,c]}const fe=({session:a,isOpen:i,flowSession:u,checklistSession:b})=>{const p=d(),{t:k}=D(),{company:v}=a.flow,{version:g}=a,y=g.resourceCenter,M=N(g.theme),A=a.locale?a.locale.standardLocaleId:a.version.theme.languageId;e.useEffect((()=>{m.changeLanguage(A)}),[A]);const{loaded:O}=_(window,j,M),[z,U]=e.useState(!1),q=O&&z,[Q,Z]=e.useState(S()),G=e.useCallback((()=>{Z(S())}),[]);I(G);const{zIndex:Y,bringToFront:J}=f(),X=e.useRef(null),[ee,te]=e.useState(null),[re,se]=e.useState(null),[oe,ne]=e.useState(null),ce=e.useRef(null),[le,ae]=e.useState(null),[ue,de]=e.useState(null),[me,fe]=e.useState(null),[Ee,be]=e.useState(0),[je,Ce]=e.useState(0),ye=e.useCallback((()=>{re&&be(re.offsetWidth),Ce((oe?.offsetHeight||0)+(le?.offsetHeight||0)+(ue?.offsetHeight||0)+(me?.offsetHeight||0))}),[re,oe,le,ue,me]);e.useLayoutEffect((()=>{if(!ee||"function"!=typeof C)return;const e=new C((()=>{ye()}));return e.observe(ee,{childList:!0,attributes:!0,subtree:!0}),()=>{e.disconnect()}}),[ee,ye]),e.useLayoutEffect((()=>{ye()}));const[xe,Ie]=e.useState(!1),Te=e.useRef(),Re=e.useCallback((()=>{Ie(!0),window.clearTimeout(Te.current),Te.current=window.setTimeout((()=>{Ie(!1)}),M.resourceCenterTransitionDuration)}),[M.resourceCenterTransitionDuration]);e.useEffect((()=>()=>{window.clearTimeout(Te.current)}),[]);const Le=e.useCallback((()=>{J(),Re(),p.openResourceCenter()}),[J,p,Re]),Be=e.useCallback((()=>{Re(),p.closeResourceCenter()}),[p,Re]),[He,Me]=e.useState(!1);e.useEffect((()=>{if(He){if(i){const e='button:not([tabindex="-1"]), [tabindex]:not([tabindex="-1"]), input, textarea';let t=le?.querySelector(e)||oe?.querySelector(e);if(t){const e=t.closest&&t.closest(".userflowjs-resource-center-checklist")||null;e?H(e):t.focus({preventScroll:!0})}}else re?.focus({preventScroll:!0});Me(!1)}}),[He,i,le,oe,re]),e.useEffect((()=>{const e=ee?.ownerDocument.defaultView;if(!i||!e)return;const t=e=>{"Escape"===e.key&&(Be(),Me(!0))};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)}),[i,ee,Me,Be]);const[We,Fe]=e.useState(null),Pe=e.useCallback(((e,t)=>{Fe(e),0===t?.detail&&Me(!0)}),[]);e.useEffect((()=>{i||Pe(null)}),[i,Pe]);const $e=e.useMemo((()=>y.blocks.filter((e=>!(e.type===t.CHECKLIST&&!b)&&(!e.hiddenWhenFlowsActive||!e.hiddenWhenFlowsActive.some((e=>e===u?.flow.id||e===b?.flow.id)))))),[y,u,b]),Ae=e.useMemo((()=>we($e)),[$e]),Oe=e.useMemo((()=>b&&y.blocks.some((e=>e.type===t.CHECKLIST))?s(b):0),[y,b]),ze=e.useMemo((()=>y.blocks.find((e=>e.type===t.CONTACT&&e.chatEnabled&&e.chatProvider))),[y]),[Ue,qe]=e.useState(!1),De=e.useCallback((()=>{p.closeResourceCenter(),ze&&ze.chatProvider!==r.CUSTOM&&qe(!0)}),[p,ze]),Ke=e.useCallback((()=>{qe(!1)}),[]),Qe=e.useCallback((()=>{if(ze)try{V[ze.chatProvider].hide({block:ze}),Ke()}catch(e){console.error(`Userflow.js: Error when hiding ${ze.chatProvider}:`,e)}}),[ze,Ke]);e.useEffect((()=>{if(!ze)return;o.autoHide3pDisabled=!0;const e=V[ze.chatProvider];try{const t=e.configure({block:ze,onShow:De,onHide:Ke});return()=>{t()}}catch(t){return void console.error(`Userflow.js: Error when configuring ${ze.chatProvider}:`,t)}}),[ze,De,Ke]),e.useEffect((()=>{i&&Qe()}),[Qe,i]);const Ve=!!We&&("search"===We.kind||"flows"===We.kind||"knowledgeBase"===We.kind),Ze={zIndex:null!=M.resourceCenterZIndex?M.resourceCenterZIndex:i?Y:w(h),width:i?void 0:Ee+"px",height:i?Math.min(Ve?540:je,Q-2*M.resourceCenterPaddingY)+"px":void 0,position:q?void 0:"absolute",visibility:q&&!Ue?void 0:"hidden"},Ge=M.resourceCenterDisplayChecklistProgress&&b&&Oe>0?e.createElement("div",{"data-testid":"resource-center-launcher-badge",className:"userflowjs-resource-center-launcher-badge"},Oe,e.createElement("div",{className:"userflowjs-a11y-only"},"uncompleted tasks")):null;let Ye="",Je="";return M.resourceCenterLauncherTextMode===n.CHECKLIST_OVERRIDE&&b&&Oe>0?Ye=b.version.checklist?.launcherText||"Get Started":M.resourceCenterLauncherTextMode!==n.NONE&&(Je=y.buttonText),e.createElement("div",{"data-testid":"resource-center-app",className:"userflowjs-resource-center userflowjs-theme-root",style:x(M),dir:m.dir()},e.createElement(T,{elRef:X,className:L({"userflowjs-resource-center-frame":!0,"userflowjs-resource-center-frame--fixed":!0,[`userflowjs-resource-center-frame--placement-${M.resourceCenterPlacement.toLowerCase().replace(/_/g,"-")}`]:!0,"userflowjs-resource-center-frame--animating":xe,"userflowjs-resource-center-frame--open":i,"userflowjs-resource-center-frame--closed":!i}),style:{...Ze},stylesheetUrl:E,theme:M,onStylesheetsLoad:U},q&&e.createElement(e.Fragment,null,e.createElement("div",{ref:te,className:L({"userflowjs-resource-center-frame-root":!0,[`userflowjs-resource-center-frame-root--placement-${M.resourceCenterPlacement.toLowerCase().replace(/_/g,"-")}`]:!0,"userflowjs-resource-center-frame-root--animating":xe,"userflowjs-resource-center-frame-root--open":i,"userflowjs-resource-center-frame-root--closed":!i}),dir:m.dir(),role:i?"dialog":void 0,"aria-label":i?y.headerText:void 0},e.createElement("div",{className:"userflowjs-resource-center-launcher-container"},e.createElement("button",{ref:se,className:"userflowjs-resource-center-launcher-button",onClick:e=>{Le(),0===e.detail&&Me(!0)},"aria-label":`Open ${y.headerText}`},Ge,Ye&&e.createElement("div",{"data-testid":"resource-center-launcher-text",className:"userflowjs-resource-center-launcher-text"},Ye),(Ge||Ye)&&e.createElement("div",{className:"userflowjs-resource-center-launcher-divider"}),Je&&e.createElement("div",{"data-testid":"resource-center-launcher-text",className:"userflowjs-resource-center-launcher-text"},Je),e.createElement("div",{className:"userflowjs-resource-center-launcher-icon"},M.resourceCenterLauncherIconType===c.PLAINTEXT?"?":e.createElement(ie,null)))),e.createElement("div",{ref:ce,className:"userflowjs-resource-center-body"},e.createElement("div",{ref:ae,className:L({"userflowjs-resource-center-body-content":!0,"userflowjs-resource-center-body-content--same-background":M.sameBackground,"userflowjs-resource-center-body-content--with-made-with-userflow":v.resourceCenterBranding})},i&&e.createElement(e.Fragment,null,We?"search"===We.kind?e.createElement(pe,{session:a,navigate:Pe}):"email"===We.kind?e.createElement(ke,{block:We.block,session:a}):"phone"===We.kind?e.createElement(ve,{block:We.block,session:a}):"flows"===We.kind?e.createElement(ge,{block:We.block,initialQ:We.initialQ,session:a,navigate:Pe}):"knowledgeBase"===We.kind?e.createElement(Se,{block:We.block,initialQ:We.initialQ,session:a,bodyRef:ce}):"subpage"===We.kind?e.createElement(Ne,{block:We.block,session:a}):null:e.createElement(e.Fragment,null,$e.map(((t,r)=>{const s=he[t.type],o=$e[r+1];return s?e.createElement(e.Fragment,{key:t.id},e.createElement(s.View,{session:a,flowSession:u,checklistSession:b,block:t,navigate:Pe,onChatShow:De}),o&&(n=t.type,c=o.type,K(n)||K(c))&&e.createElement("div",{className:"userflowjs-resource-center-divider"})):null;var n,c})))))),v.resourceCenterBranding&&e.createElement("div",{className:"userflowjs-resource-center-made-with-userflow"},e.createElement("div",{className:"userflowjs-resource-center-made-with-userflow-content",ref:de},e.createElement("a",{href:"https://userflow.com/?utm_source=made-with-userflow&utm_medium=link&utm_campaign=made-with-userflow-"+v.slug+"&utm_content=resource-center",target:"_blank",rel:"noopener noreferrer"},e.createElement(R,null),e.createElement("div",null,"Made with Userflow")))),a.draftMode&&e.createElement("div",{className:"userflowjs-resource-center-preview"},e.createElement("div",{ref:fe,className:"userflowjs-resource-center-preview-content"},e.createElement("div",{className:"userflowjs-resource-center-preview-text"},"Preview"),e.createElement("button",{className:"userflowjs-resource-center-preview-button",onClick:()=>{p.endFlow(a,{endReason:l.USER_CLOSED})}},e.createElement(B,{icon:W})))),e.createElement("div",{className:"userflowjs-resource-center-header"},e.createElement("div",{ref:ne,className:"userflowjs-resource-center-header-content"},null==We?e.createElement("div",{className:"userflowjs-resource-center-header-text"},y.headerText):e.createElement("button",{className:"userflowjs-resource-center-icon-button",onClick:e=>Pe(null,e)},e.createElement("div",{className:"userflowjs-rtl-mirrored"},e.createElement(B,{icon:F})),e.createElement("div",{className:"userflowjs-resource-center-icon-button__text"},k("resource_center.back"))),e.createElement("div",{className:"flex-1"}),Ae.length>0&&e.createElement("button",{className:"userflowjs-resource-center-icon-button",onClick:()=>{let e={kind:"search"};if(1===Ae.length){const t=Ae[0],r=he[t.type];r.routeTo&&(e=r.routeTo({block:t}))}"search"===We?.kind?Pe(null):(_e(p,a,null,"Search icon"),Pe(e))},"aria-label":"Search"},e.createElement(B,{icon:P})),e.createElement("button",{className:"userflowjs-resource-center-icon-button userflowjs-resource-center-close-button",onClick:e=>{Be(),0===e.detail&&Me(!0)},"aria-label":`Close ${y.headerText}`},e.createElement(B,{icon:$}))))))))};function we(e){return e.filter((e=>{const t=he[e.type];return t.isSearchable?t.isSearchable(e):!!t.search}))}const he={[t.ACTION]:{View:t=>{const{block:r,session:s,flowSession:o,checklistSession:n}=t,c=d(),[l,i]=e.useState(!1),u=o?.id,m=n?.id;return e.useEffect((()=>{i(!1)}),[u,m]),e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:l?void 0:()=>{_e(c,s,r);const e=r.actions.find((e=>e.type===a.START_FLOW));if(e){e.otherFlow?.id!==n?.flow.id&&i(!0)}else c.closeResourceCenter();b(c,s,r.actions)},disabled:l},e.createElement(Ee,{...t}),e.createElement(be,{...t}),l&&e.createElement(ue,null))}},[t.CHECKLIST]:{View:({checklistSession:t})=>e.createElement("div",{"data-testid":"resource-center-checklist",className:"userflowjs-resource-center-checklist"},e.createElement(M,{session:t}),e.createElement(p,{draftMode:!!t.draftMode&&"CHECKLIST PREVIEW"}))},[t.CONTACT]:{View:t=>{const{block:r,session:s,navigate:o,onChatShow:n}=t,c=d(),l=[];return r.emailEnabled&&l.push({icon:z,label:"Email",isRoute:!0,onClick:e=>{_e(c,s,r,"Email"),o({kind:"email",block:r},e)}}),r.phoneEnabled&&l.push({icon:U,label:"Phone",isRoute:!0,onClick:e=>{_e(c,s,r,"Phone"),o({kind:"phone",block:r},e)}}),r.chatEnabled&&l.push({icon:q,label:"Live-chat",isRoute:!1,onClick:()=>{if(_e(c,s,r,"Chat"),r.chatProvider){const t=V[r.chatProvider];try{t.show({block:r})}catch(e){console.error(`Userflow.js: Error when showing ${r.chatProvider}:`,e)}n()}else s.draftMode&&window.alert("You have not selected a chat provider. Go to the resource center builder in Userflow. Click the Contact block. Pick a chat provider in the side panel.")}}),e.createElement("div",{className:L({"userflowjs-resource-center-block":!0,"userflowjs-resource-center-block--clickable":1===l.length}),onClick:1===l.length?l[0].onClick:void 0},1===l.length&&e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(B,{icon:l[0].icon})),e.createElement(be,{...t}),l.length>1&&l.map((({icon:t,label:r,onClick:s},o)=>e.createElement("button",{key:o,className:"userflowjs-resource-center-icon-button",onClick:s,"aria-label":r},e.createElement(B,{icon:t})))),1===l.length&&l[0].isRoute&&e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(B,{icon:A})))}},[t.FLOWS]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{_e(n,s,r),o({kind:"flows",block:r},e)}},e.createElement(Ee,{...t}),e.createElement(be,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(B,{icon:A})))},routeTo:({block:e,initialQ:t})=>({kind:"flows",block:e,initialQ:t}),isSearchable:e=>!!e.searchEnabled,search:async({client:e,session:t,block:r,q:s})=>{const{flows:o}=await e.send({kind:"ListResourceCenterBlockFlows",sessionId:t.id,blockCvid:r.cvid},{handlesRejection:!0}),n=je(o,s),c=n.slice(0,5);return{block:r,truncated:c.length===n.length,results:c.map((e=>({kind:"flow",flow:e})))}}},[t.KNOWLEDGE_BASE]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{_e(n,s,r),o({kind:"knowledgeBase",block:r},e)}},e.createElement(Ee,{...t}),e.createElement(be,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(B,{icon:A})))},routeTo:({block:e,initialQ:t})=>({kind:"knowledgeBase",block:e,initialQ:t}),search:async({client:e,session:t,block:r,q:s})=>{const{truncated:o,articles:n}=await e.send({kind:"SearchKnowledgeBase",sessionId:t.id,blockCvid:r.cvid,q:s,offset:0,limit:5},{handlesRejection:!0});return{block:r,truncated:o,results:n.map((e=>({kind:"article",article:e})))}}},[t.MESSAGE]:{View:({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-block"},e.createElement("div",{className:"userflowjs-resource-center-block-text userflowjs-bubble-content"},e.createElement(k,{doc:t.content,lookupAttribute:y(r.data)})))},[t.SUBPAGE]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{_e(n,s,r),o({kind:"subpage",block:r},e)}},e.createElement(Ee,{...t}),e.createElement(be,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(B,{icon:A})))}}},Ee=({block:t})=>t.icon?e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(B,{icon:t.icon,size:16})):null,be=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-block-text"},e.createElement(v,{doc:t.name,lookupAttribute:y(r.data)})),pe=({session:t,navigate:r})=>{const s=d(),o=t.version.resourceCenter.blocks,n=we(o),{t:c}=D(),l=e.useRef(null),[a,i]=e.useState(""),[u,m]=me(a,i),[f,w]=e.useState(null);return e.useEffect((()=>{if(""===a.trim())return void w(null);let e=!1;return(async()=>{w(null);const r=await Promise.all(o.map((async e=>{const{search:r}=he[e.type];if(!r)return null;try{return await r({client:s,session:t,block:e,q:a})}catch(o){return console.error(`Userflow.js: Global search failed for ${e.type} block=`,e,"error=",o),null}})));e||w(r.filter((e=>null!=e&&e.results.length>0)))})(),()=>{e=!0}}),[s,t,o,a]),e.useEffect((()=>{l.current?.focus({preventScroll:!0})}),[]),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:l,className:"userflowjs-text-input",type:"text",value:u,onChange:e=>m(e.target.value),placeholder:c("resource_center.search_placeholder")})),""===a.trim()?e.createElement("div",{"data-testid":"resource-center-empty-query",className:"userflowjs-resource-center-list-route-error"},c("resource_center.search_in")," ",n.map(((r,s)=>e.createElement(e.Fragment,{key:r.cvid},s>0&&(s===n.length-1?` ${c("and")} `:", "),e.createElement("b",null,e.createElement(v,{doc:r.name,lookupAttribute:y(t.data)}))))),"."):f?0===f.length?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},c("resource_center.no_results_found")):f.map((({block:o,truncated:n,results:l},i)=>{const u=he[o.type],d=u.routeTo&&u.routeTo({block:o,initialQ:a});return e.createElement(e.Fragment,{key:o.cvid},i>0&&e.createElement("div",{className:"userflowjs-resource-center-divider"}),e.createElement("div",{className:"userflowjs-resource-center-label"},e.createElement(v,{doc:o.name,lookupAttribute:y(t.data)})),l.map(((s,n)=>"flow"===s.kind?e.createElement(Ce,{key:s.flow.id,block:o,session:t,flow:s.flow,navigate:r}):"article"===s.kind?e.createElement(ye,{key:n,block:o,session:t,article:s.article}):null)),!n&&d&&e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{_e(s,t,o),r(d,e)}},e.createElement("div",{className:"userflowjs-resource-center-block-text"},c("more"),":"," ",e.createElement(v,{doc:o.name,lookupAttribute:y(t.data)})),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(B,{icon:A}))))})):e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(ue,null)))},ke=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.emailContent,lookupAttribute:y(r.data)})),ve=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.phoneContent,lookupAttribute:y(r.data)})),ge=({block:t,initialQ:r,session:s,navigate:o})=>{const{t:n}=D(),c=e.useRef(null),[l,a]=e.useState(r||""),[i,u]=me(l,a),{data:d,error:m}=de({kind:"ListResourceCenterBlockFlows",sessionId:s.id,blockCvid:t.cvid}),f=d?.flows,w=e.useMemo((()=>f?je(f,l):null),[f,l]);return e.useEffect((()=>{c.current?.focus({preventScroll:!0})}),[]),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-header"},e.createElement("div",{className:"userflowjs-resource-center-list-route-title"},e.createElement(v,{doc:t.name,lookupAttribute:y(s.data)}))),t.searchEnabled&&e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:c,className:"userflowjs-text-input",type:"text",value:i,onChange:e=>u(e.target.value),placeholder:n("resource_center.search_placeholder")})),m?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.generic_error")):w?0===w.length?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.no_results_found")):w.map((r=>e.createElement(Ce,{key:r.id,block:t,session:s,flow:r,navigate:o}))):e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(ue,null)))};function je(e,t){const r=t.toLowerCase().trim();return""===r?e:e.filter((e=>e.name.toLowerCase().includes(r)))}const Ce=({block:t,session:r,flow:s,navigate:o})=>{const n=d(),[c,l]=e.useState(!1);return e.useEffect((()=>{if(!c||s.type!==i.CHECKLIST)return;const e=()=>{n.checklistSession?.flow.id===s.id&&(t(),o(null))},t=()=>{n.off("checklistChanged",e)};return n.on("checklistChanged",e),t}),[n,c,s.type,s.id,o]),e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:()=>{_e(n,r,t,s.name),n.startFlow({flowId:s.id,startReason:u.RESOURCE_CENTER,replaceCurrent:!0}),l(!0)},disabled:c},e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(B,{icon:s.type===i.CHECKLIST?"regular/tasks":"regular/shoe-prints",size:16})),e.createElement("div",{className:"userflowjs-resource-center-block-text"},s.name),c&&e.createElement(ue,null))},Se=({block:t,initialQ:r,session:s,bodyRef:o})=>{const{t:n}=D(),c=e.useRef(null),[l,a]=e.useState(r||""),[i,u]=me(l,a),{loading:d,loadingMore:m,data:f,messageForData:w,error:h,loadMore:E}=de({kind:"SearchKnowledgeBase",sessionId:s.id,blockCvid:t.cvid,q:l,offset:0}),b=f?.truncated,p=e.useCallback((()=>{E(((e,t)=>({...t,offset:e.articles.length})),((e,t)=>({...t,articles:[...e.articles,...t.articles]})))}),[E]);e.useEffect((()=>{const e=o.current;if(!e||d||m||b)return;const t=()=>{e.scrollHeight-e.clientHeight-e.scrollTop>400||p()};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}}),[o,d,m,b,p]),e.useEffect((()=>{c.current?.focus({preventScroll:!0})}),[]);let k=t.knowledgeBaseUrl||"";return k.match(/^https?:\/\//)||(k=`http://${k}`),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-header"},e.createElement("div",{className:"userflowjs-resource-center-list-route-title"},e.createElement(v,{doc:t.name,lookupAttribute:y(s.data)})),e.createElement("a",{className:"userflowjs-resource-center-icon-button",href:k,target:"_blank",rel:"noopener noreferrer"},e.createElement(B,{icon:O}))),e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:c,className:"userflowjs-text-input",type:"text",value:i,onChange:e=>u(e.target.value),placeholder:n("resource_center.search_placeholder")})),h?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},"quota_exceeded"===h.code?"Sorry, this company has reached its max number of searches. Consider asking Userflow to be moved to a dedicated search engine for a higher quota.":n("resource_center.generic_error")):d||!f?e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(ue,null)):0===f.articles.length?""===w?.q?null:e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.no_results_found")):e.createElement(e.Fragment,null,""===w?.q&&e.createElement("div",{className:"userflowjs-resource-center-label"},n("resource_center.suggested_articles")),f.articles.map(((r,o)=>e.createElement(ye,{key:o,block:t,session:s,article:r}))),m&&e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(ue,null))))},ye=({block:t,article:r,session:s})=>{const o=d();return e.createElement("a",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:()=>{_e(o,s,t,r.title)},href:r.url,target:"_blank",rel:"noopener noreferrer"},e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(B,{icon:"regular/file-alt",size:16})),e.createElement("div",{className:"userflowjs-resource-center-block-text"},e.createElement("span",{dangerouslySetInnerHTML:{__html:r.htmlTitle}}),e.createElement("div",{className:"userflowjs-resource-center-block-subtext",dangerouslySetInnerHTML:{__html:r.htmlSnippet}})))},Ne=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.content,lookupAttribute:y(r.data)}));function _e(e,t,r,s){e.send({kind:"ClickResourceCenter",sessionId:t.id,description:r?g(r.name,{lookupAttribute:y(t.data)})+(s?` - ${s}`:""):s},{batch:!0})}export default fe;export{fe as ResourceCenterApp};
1
+ import{r as e}from"./vendor.react.js";import{h as t,C as r,i as s,c as o,j as n,k as c,E as l,l as a,m as i,S as u}from"./userflow.js";import{u as d,i as m}from"./client-context.js";import{u as f,w,C as h}from"./Icons.js";import{b as E,h as b,B as p,R as k,a as v,s as g,n as j,f as C}from"./BubbleToolbar.js";import{M as S,g as y,a as N}from"./flow-condition-types.js";import{u as _,a as x,g as I}from"./stylesheets.js";import{u as T,F as R,S as L}from"./logomark.js";import{o as B}from"./vendor.obj-str.js";import{D as H}from"./DynamicIcon.js";import{f as M,C as W}from"./ChecklistUI.js";import{f as F,a as P,b as A,c as $,d as O,e as z,g as U,h as q,i as D}from"./vendor.fortawesome.pro-regular-svg-icons.js";import{u as K}from"./vendor.react-i18next.js";import"./vendor.object-assign.js";import"./vendor.phoenix.js";import"./vendor.uuid.js";import"./vendor.i18next.js";import"./vendor.fortawesome.react-fontawesome.js";import"./vendor.fortawesome.fontawesome-svg-core.js";import"./vendor.prop-types.js";import"./vendor.fortawesome.pro-solid-svg-icons.js";import"./vendor.date-fns.js";import"./vendor.react-dom.js";import"./vendor.scheduler.js";import"./vendor.babel.runtime.js";function Q(e){return e!==t.ACTION&&e!==t.CONTACT&&e!==t.FLOWS&&e!==t.KNOWLEDGE_BASE&&e!==t.SUBPAGE}const V=window,Z={[r.CRISP]:{configure:({onShow:e,onHide:t})=>{V.$crisp||(V.$crisp=[]),V.$crisp.push(["do","chat:hide"]);let r=!1,s=!1;const o=()=>{r||s?(V.$crisp.push(["do","chat:show"]),e()):(V.$crisp.push(["do","chat:hide"]),t())},n=()=>{r=!0,o()};V.$crisp.push(["on","chat:opened",n]);const c=()=>{r=!1,o()};V.$crisp.push(["on","chat:closed",c]);const l=()=>{s=!0,o()};V.$crisp.push(["on","message:received",l]);const a=window.setInterval((()=>{const e=(()=>{const e=document.getElementById("crisp-chatbox");if(!e||"block"!==window.getComputedStyle(e).display)return!1;const t=e.querySelector('[data-id="new_messages"]');return!(!t||"block"!==window.getComputedStyle(t).display)})();e!==s&&(s=e,o())}),200);return()=>{V.$crisp.push(["off","chat:opened",n]),V.$crisp.push(["off","chat:closed",c]),V.$crisp.push(["off","message:received",l]),window.clearInterval(a)}},show:()=>{V.$crisp.push(["do","chat:show"]),V.$crisp.push(["do","chat:open"])},hide:()=>{V.$crisp.push(["do","chat:hide"]),V.$crisp.push(["do","chat:close"])}},[r.CUSTOM]:{configure:()=>()=>{},show:({block:e})=>{try{new Function('"use strict";\n'+e.chatCode)()}catch(t){console.error(`Userflow.js: Showing custom chat provider failed. Code: ${e.chatCode}`,t)}},hide:()=>{}},[r.FRESHCHAT]:{configure:({onShow:e,onHide:t})=>{if(!V.fcWidget)throw new Error("Freshchat is not installed");let r=!1,s=!1;const o=()=>{r||s?e():t()},n=()=>{r=!0,o()};V.fcWidget.on("widget:opened",n);const c=()=>{r=!1,o()};V.fcWidget.on("widget:closed",c);const l=()=>{const e=!!document.querySelector("#fc_frame.h-open-notify");e!==s&&(s=e,o())},a=window.setInterval(l,200);return V.fcWidget.on("unreadCount:notify",l),()=>{V.fcWidget.off("widget:opened",n),V.fcWidget.off("widget:closed",c),V.fcWidget.off("unreadCount:notify",l),window.clearInterval(a)}},show:()=>{V.fcWidget.open()},hide:()=>{V.fcWidget.close()}},[r.HELPSCOUT]:{configure:({onShow:e,onHide:t})=>{if(!V.Beacon)throw new Error("Help Scout is not installed");Y();let r=!1,s=!1;const o=()=>{r||s?(G(),e()):(Y(),t())},n=()=>{r=!0,o()};V.Beacon("on","open",n),V.Beacon("info")?.status.isOpened&&n();const c=()=>{r=!1,o()};V.Beacon("on","close",c);const l=window.setInterval((()=>{const e=!!document.querySelector(".BeaconNotificationsFrame");e!==s&&(s=e,o())}),200);return()=>{V.Beacon("off","open",n),V.Beacon("off","close",c),window.clearInterval(l)}},show:()=>{G(),V.Beacon("open")},hide:()=>{Y(),V.Beacon("close")}},[r.HUBSPOT]:{configure:({onShow:e,onHide:t})=>{const r=()=>{const r=document.getElementById("hubspot-messages-iframe-container");if(!V.HubSpotConversations||!r)return;window.clearInterval(o),J?X():ee();let n=!1,c=!1;const l=()=>{n||c?(X(),e()):(ee(),t())},a=()=>{const e=!!document.querySelector("#hubspot-messages-iframe-container .shadow-container.active");e!==n&&(n=e,l())},i=new S(a);i.observe(r,{attributes:!0,subtree:!0,attributeFilter:["class"]}),a();const u=({unreadCount:e})=>{const t=e>0;t!==c&&(c=t,l())};V.HubSpotConversations.on("unreadConversationCountChanged",u),s=()=>{i.disconnect(),V.HubSpotConversations.off("unreadConversationCountChanged",u)}};let s=()=>{window.clearInterval(o)};const o=window.setInterval(r,100);return r(),()=>{s()}},show:()=>{X(),V.HubSpotConversations.widget.open()},hide:()=>{ee(),V.HubSpotConversations.widget.close()}},[r.INTERCOM]:{configure:({onShow:e,onHide:t})=>{if(!V.Intercom)throw new Error("Intercom is not installed");return ne(),function(){if(te)return;te=!0;let e=!1,t=!1;const r=()=>{oe();for(const e of re)e()},s=()=>{ne();for(const e of se)e()},o=()=>{e||t?r():s()};V.Intercom("onShow",(()=>{e=!0,o()})),V.Intercom("onHide",(()=>{e=!1,o()}));const n=()=>{const e=!!document.querySelector('iframe[name="intercom-borderless-frame"], iframe[name="intercom-notifications-frame"]');t!==e&&(t=e,o())};V.Intercom("onUnreadCountChange",(()=>{n()})),window.setInterval(n,200)}(),re.add(e),se.add(t),()=>{re.delete(e),se.delete(t)}},show:()=>{oe(),V.Intercom("show")},hide:()=>{ne(),V.Intercom("hide")}},[r.ZENDESK]:{configure:({onShow:e,onHide:t})=>{if(!V.zE)throw new Error("Zendesk is not installed");!function(){if(ce)return;ce=!0,V.zE("webWidget:on","open",(()=>{for(const e of le)e()})),V.zE("webWidget:on","close",(()=>{for(const e of ae)e()})),V.zE("webWidget:on","chat:unreadMessages",(e=>{for(const t of ie)t(e)}))}(),V.zE("webWidget","hide"),V.zE("webWidget","close");let r=!1,s=!1;const o=()=>{r||s?(V.zE("webWidget","show"),e()):(V.zE("webWidget","hide"),t())},n=()=>{r=!0,s=!1,o()};le.add(n);const c=()=>{r=!1,s=!1,o()};ae.add(c);const l=e=>{const t=e>0;t!==s&&(s=t,o())};return ie.add(l),()=>{le.delete(n),ae.delete(c),ie.delete(l)}},show:()=>{V.zE("webWidget","show"),V.zE("webWidget","open")},hide:()=>{V.zE("webWidget","hide"),V.zE("webWidget","close")}},[r.ZENDESK_MESSENGER]:{configure:({onShow:e,onHide:t})=>{if(!V.zE)throw new Error("Zendesk is not installed");let r=!1;const s=window.setInterval((()=>{const s=(()=>{const e=document.querySelector('iframe[title="Messaging window"]');return!!e?.parentElement&&"0px"!==window.getComputedStyle(e.parentElement).height})();s!==r&&(r=s,r?e():t())}),200);return()=>{window.clearInterval(s)}},show:()=>{V.zE("messenger","open")},hide:()=>{V.zE("messenger","close")}}};function G(){V.Beacon("config",{display:{style:"icon"}})}function Y(){V.Beacon("config",{display:{style:"manual"}})}let J=!1;function X(){J=!0;document.getElementById("hubspot-messages-iframe-container")?.style.setProperty("visibility","visible","important")}function ee(){J=!1;document.getElementById("hubspot-messages-iframe-container")?.style.setProperty("visibility","hidden","important")}let te=!1,re=new Set,se=new Set;function oe(){V.Intercom("update",{hide_default_launcher:!1,vertical_padding:20})}function ne(){V.Intercom("update",{hide_default_launcher:!0,vertical_padding:100})}let ce=!1,le=new Set,ae=new Set,ie=new Set;const ue=t=>e.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 100 100"},t),e.createElement("path",{fill:"currentColor",d:"M24.049 79.74h36.003c8.185 0 15.985-6.621 17.43-14.814l6.091-34.556h3.997c8.149 0 13.645 6.63 12.2 14.815l-7.051 40C91.274 93.363 83.474 100 75.288 100h-40c-8.185 0-13.645-6.667-12.2-14.815l.96-5.444Z"}),e.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M12.437 69.63h40c8.148 0 15.978-6.637 17.422-14.815l7.052-40C78.355 6.63 72.896 0 64.711 0h-40C16.533 0 8.726 6.63 7.281 14.815l-7.052 40C-1.215 62.963 4.252 69.63 12.437 69.63Zm33.628-33.798c3.756-2.064 8.725-4.795 9.907-11.844C57.385 15.458 50.065 8.983 42.168 9c-7.452 0-12.771 3.195-17.508 8.892-.858 1.034-.884 2.45-.053 3.212l3.472 3.196c.847.767 2.25.589 3.176-.406 2.842-3.068 4.869-4.83 8.51-4.83 2.864 0 6.077 1.934 5.59 4.847-.37 2.223-2.292 3.334-5.4 5.001l-.28.151c-3.582 1.92-8.134 4.362-9.124 10.247l-.16.956c-.055.28-.05.571.014.85.065.278.188.538.362.76.173.222.391.4.639.522.247.121.518.183.79.18h6.744a2.709 2.709 0 0 0 1.712-.688c.481-.426.81-1.01.934-1.657l.095-.556c.266-1.582 2.101-2.59 4.384-3.845ZM32.837 59c3.552 0 6.955-3.034 7.58-6.769.63-3.729-1.742-6.763-5.293-6.763-3.552 0-6.934 3.028-7.58 6.763C26.9 55.966 29.286 59 32.837 59Z"})),de=()=>{const t=12;return e.createElement("div",{className:"userflowjs-spinner"},e.createElement("svg",{viewBox:"0 0 24 24",version:"1.1",xmlns:"http://www.w3.org/2000/svg"},e.createElement("circle",{className:"userflowjs-spinner__bg",fill:"none",cx:t,cy:t,r:10,style:{strokeWidth:"4px"}}),e.createElement("circle",{className:"userflowjs-spinner__fill",fill:"none",cx:t,cy:t,r:10,transform:"translate(12, 12) rotate(-90) translate(-12, -12)",style:{strokeWidth:"4px",strokeDasharray:20*Math.PI*.25+"px, 1000"}})))};function me(t){const r=d(),[s,o]=e.useState(!0),[n,c]=e.useState(!1),[l,a]=e.useState(null),[i,u]=e.useState(null),[m,f]=e.useState(null),w=e.useRef(0),h=e.useRef(null),E=e.useRef((()=>{}));return e.useEffect((()=>{const e=JSON.stringify(t);if(e===h.current)return;h.current=e;const s=++w.current;let n,l;let i=!1;E.current=async(e,t)=>{if(!i){i=!0,c(!0);try{const o=e(n,l);l=o;const u=await r.send(o,{handlesRejection:!0});if(s!==w.current)return;n=t(n,u),a(n),f(null)}catch(o){if(s!==w.current)return;f(o)}finally{i=!1,c(!1)}}},(async()=>{o(!0);try{l=t;const e=await r.send(t,{handlesRejection:!0});if(s!==w.current)return;n=e,a(n),u(t),f(null)}catch(e){if(s!==w.current)return;f(e)}finally{o(!1)}})()}),[r,t]),{loading:s,loadingMore:n,data:l,messageForData:i,error:m,loadMore:E.current}}function fe(t,r){const[s,o]=e.useState(t),n=e.useRef(void 0),c=e.useCallback((e=>{window.clearTimeout(n.current),o(e),r(e)}),[r]),l=e.useCallback((e=>{window.clearTimeout(n.current),o(e),n.current=window.setTimeout((()=>{r(e)}),200)}),[r]);return e.useEffect((()=>()=>{window.clearTimeout(n.current)}),[]),[s,l,c]}const we=({session:a,isOpen:i,flowSession:u,checklistSession:b})=>{const p=d(),{t:k}=K(),{company:v}=a.flow,{version:g}=a,j=g.resourceCenter,N=_(g.theme),W=a.locale?a.locale.standardLocaleId:a.version.theme.languageId;e.useEffect((()=>{m.changeLanguage(W)}),[W]);const{loaded:O}=x(window,C,N),[z,U]=e.useState(!1),q=O&&z,[D,V]=e.useState(y()),G=e.useCallback((()=>{V(y())}),[]);T(G);const{zIndex:Y,bringToFront:J}=f(),X=e.useRef(null),[ee,te]=e.useState(null),[re,se]=e.useState(null),[oe,ne]=e.useState(null),ce=e.useRef(null),[le,ae]=e.useState(null),[ie,de]=e.useState(null),[me,fe]=e.useState(null),[we,be]=e.useState(0),[pe,Ce]=e.useState(0),Se=e.useCallback((()=>{re&&be(re.offsetWidth),Ce((oe?.offsetHeight||0)+(le?.offsetHeight||0)+(ie?.offsetHeight||0)+(me?.offsetHeight||0))}),[re,oe,le,ie,me]);e.useLayoutEffect((()=>{if(!ee||"function"!=typeof S)return;const e=new S((()=>{Se()}));return e.observe(ee,{childList:!0,attributes:!0,subtree:!0}),()=>{e.disconnect()}}),[ee,Se]),e.useLayoutEffect((()=>{Se()}));const[Ne,Ie]=e.useState(!1),Te=e.useRef(),Re=e.useCallback((()=>{Ie(!0),window.clearTimeout(Te.current),Te.current=window.setTimeout((()=>{Ie(!1)}),N.resourceCenterTransitionDuration)}),[N.resourceCenterTransitionDuration]);e.useEffect((()=>()=>{window.clearTimeout(Te.current)}),[]);const Le=e.useCallback((()=>{J(),Re(),p.openResourceCenter()}),[J,p,Re]),Be=e.useCallback((()=>{Re(),p.closeResourceCenter()}),[p,Re]),[He,Me]=e.useState(!1);e.useEffect((()=>{if(He){if(i){const e='button:not([tabindex="-1"]), [tabindex]:not([tabindex="-1"]), input, textarea';let t=le?.querySelector(e)||oe?.querySelector(e);if(t){const e=t.closest&&t.closest(".userflowjs-resource-center-checklist")||null;e?M(e):t.focus({preventScroll:!0})}}else re?.focus({preventScroll:!0});Me(!1)}}),[He,i,le,oe,re]),e.useEffect((()=>{const e=ee?.ownerDocument.defaultView;if(!i||!e)return;const t=e=>{"Escape"===e.key&&(Be(),Me(!0))};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)}),[i,ee,Me,Be]);const[We,Fe]=e.useState(null),Pe=e.useCallback(((e,t)=>{Fe(e),0===t?.detail&&Me(!0)}),[]);e.useEffect((()=>{i||Pe(null)}),[i,Pe]);const Ae=e.useMemo((()=>j.blocks.filter((e=>!(e.type===t.CHECKLIST&&!b)&&(!e.hiddenWhenFlowsActive||!e.hiddenWhenFlowsActive.some((e=>e===u?.flow.id||e===b?.flow.id)))))),[j,u,b]),$e=e.useMemo((()=>he(Ae)),[Ae]),Oe=e.useMemo((()=>b&&j.blocks.some((e=>e.type===t.CHECKLIST))?s(b):0),[j,b]),ze=e.useMemo((()=>j.blocks.find((e=>e.type===t.CONTACT&&e.chatEnabled&&e.chatProvider))),[j]),[Ue,qe]=e.useState(!1),De=e.useCallback((()=>{p.closeResourceCenter(),ze&&ze.chatProvider!==r.CUSTOM&&qe(!0)}),[p,ze]),Ke=e.useCallback((()=>{qe(!1)}),[]),Qe=e.useCallback((()=>{if(ze)try{Z[ze.chatProvider].hide({block:ze}),Ke()}catch(e){console.error(`Userflow.js: Error when hiding ${ze.chatProvider}:`,e)}}),[ze,Ke]);e.useEffect((()=>{if(!ze)return;o.autoHide3pDisabled=!0;const e=Z[ze.chatProvider];try{const t=e.configure({block:ze,onShow:De,onHide:Ke});return()=>{t()}}catch(t){return void console.error(`Userflow.js: Error when configuring ${ze.chatProvider}:`,t)}}),[ze,De,Ke]),e.useEffect((()=>{i&&Qe()}),[Qe,i]);const Ve=!!We&&("search"===We.kind||"flows"===We.kind||"knowledgeBase"===We.kind),Ze={zIndex:null!=N.resourceCenterZIndex?N.resourceCenterZIndex:i?Y:w(h),width:i?void 0:we+"px",height:i?Math.min(Ve?540:pe,D-2*N.resourceCenterPaddingY)+"px":void 0,position:q?void 0:"absolute",visibility:q&&!Ue?void 0:"hidden"},Ge=N.resourceCenterDisplayChecklistProgress&&b&&Oe>0?e.createElement("div",{"data-testid":"resource-center-launcher-badge",className:"userflowjs-resource-center-launcher-badge"},Oe,e.createElement("div",{className:"userflowjs-a11y-only"},"uncompleted tasks")):null;let Ye="",Je="";return N.resourceCenterLauncherTextMode===n.CHECKLIST_OVERRIDE&&b&&Oe>0?Ye=b.version.checklist?.launcherText||"Get Started":N.resourceCenterLauncherTextMode!==n.NONE&&(Je=j.buttonText),e.createElement("div",{"data-testid":"resource-center-app",className:"userflowjs-resource-center userflowjs-theme-root",style:I(N),dir:m.dir()},e.createElement(R,{elRef:X,className:B({"userflowjs-resource-center-frame":!0,"userflowjs-resource-center-frame--fixed":!0,[`userflowjs-resource-center-frame--placement-${N.resourceCenterPlacement.toLowerCase().replace(/_/g,"-")}`]:!0,"userflowjs-resource-center-frame--animating":Ne,"userflowjs-resource-center-frame--open":i,"userflowjs-resource-center-frame--closed":!i}),style:{...Ze},stylesheetUrl:E,theme:N,onStylesheetsLoad:U},q&&e.createElement(e.Fragment,null,e.createElement("div",{ref:te,className:B({"userflowjs-resource-center-frame-root":!0,[`userflowjs-resource-center-frame-root--placement-${N.resourceCenterPlacement.toLowerCase().replace(/_/g,"-")}`]:!0,"userflowjs-resource-center-frame-root--animating":Ne,"userflowjs-resource-center-frame-root--open":i,"userflowjs-resource-center-frame-root--closed":!i}),dir:m.dir(),role:i?"dialog":void 0,"aria-label":i?j.headerText:void 0},e.createElement("div",{className:"userflowjs-resource-center-launcher-container"},e.createElement("button",{ref:se,className:"userflowjs-resource-center-launcher-button",onClick:e=>{Le(),0===e.detail&&Me(!0)},"aria-label":`Open ${j.headerText}`},Ge,Ye&&e.createElement("div",{"data-testid":"resource-center-launcher-text",className:"userflowjs-resource-center-launcher-text"},Ye),(Ge||Ye)&&e.createElement("div",{className:"userflowjs-resource-center-launcher-divider"}),Je&&e.createElement("div",{"data-testid":"resource-center-launcher-text",className:"userflowjs-resource-center-launcher-text"},Je),e.createElement("div",{className:"userflowjs-resource-center-launcher-icon"},N.resourceCenterLauncherIconType===c.PLAINTEXT?"?":e.createElement(ue,null)))),e.createElement("div",{ref:ce,className:"userflowjs-resource-center-body"},e.createElement("div",{ref:ae,className:B({"userflowjs-resource-center-body-content":!0,"userflowjs-resource-center-body-content--same-background":N.sameBackground,"userflowjs-resource-center-body-content--with-made-with-userflow":v.resourceCenterBranding})},i&&e.createElement(e.Fragment,null,We?"search"===We.kind?e.createElement(ke,{session:a,navigate:Pe}):"email"===We.kind?e.createElement(ve,{block:We.block,session:a}):"phone"===We.kind?e.createElement(ge,{block:We.block,session:a}):"flows"===We.kind?e.createElement(je,{block:We.block,initialQ:We.initialQ,session:a,navigate:Pe}):"knowledgeBase"===We.kind?e.createElement(ye,{block:We.block,initialQ:We.initialQ,session:a,bodyRef:ce}):"subpage"===We.kind?e.createElement(_e,{block:We.block,session:a}):null:e.createElement(e.Fragment,null,Ae.map(((t,r)=>{const s=Ee[t.type],o=Ae[r+1];return s?e.createElement(e.Fragment,{key:t.id},e.createElement(s.View,{session:a,flowSession:u,checklistSession:b,block:t,navigate:Pe,onChatShow:De}),o&&(n=t.type,c=o.type,Q(n)||Q(c))&&e.createElement("div",{className:"userflowjs-resource-center-divider"})):null;var n,c})))))),v.resourceCenterBranding&&e.createElement("div",{className:"userflowjs-resource-center-made-with-userflow"},e.createElement("div",{className:"userflowjs-resource-center-made-with-userflow-content",ref:de},e.createElement("a",{href:"https://userflow.com/?utm_source=made-with-userflow&utm_medium=link&utm_campaign=made-with-userflow-"+v.slug+"&utm_content=resource-center",target:"_blank",rel:"noopener noreferrer"},e.createElement(L,null),e.createElement("div",null,"Made with Userflow")))),a.draftMode&&e.createElement("div",{className:"userflowjs-resource-center-preview"},e.createElement("div",{ref:fe,className:"userflowjs-resource-center-preview-content"},e.createElement("div",{className:"userflowjs-resource-center-preview-text"},"Preview"),e.createElement("button",{className:"userflowjs-resource-center-preview-button",onClick:()=>{p.endFlow(a,{endReason:l.USER_CLOSED})}},e.createElement(H,{icon:F})))),e.createElement("div",{className:"userflowjs-resource-center-header"},e.createElement("div",{ref:ne,className:"userflowjs-resource-center-header-content"},null==We?e.createElement("div",{className:"userflowjs-resource-center-header-text"},j.headerText):e.createElement("button",{className:"userflowjs-resource-center-icon-button",onClick:e=>Pe(null,e)},e.createElement("div",{className:"userflowjs-rtl-mirrored"},e.createElement(H,{icon:P})),e.createElement("div",{className:"userflowjs-resource-center-icon-button__text"},k("resource_center.back"))),e.createElement("div",{className:"flex-1"}),$e.length>0&&e.createElement("button",{className:"userflowjs-resource-center-icon-button",onClick:()=>{let e={kind:"search"};if(1===$e.length){const t=$e[0],r=Ee[t.type];r.routeTo&&(e=r.routeTo({block:t}))}"search"===We?.kind?Pe(null):(xe(p,a,null,"Search icon"),Pe(e))},"aria-label":"Search"},e.createElement(H,{icon:A})),e.createElement("button",{className:"userflowjs-resource-center-icon-button userflowjs-resource-center-close-button",onClick:e=>{Be(),0===e.detail&&Me(!0)},"aria-label":`Close ${j.headerText}`},e.createElement(H,{icon:$}))))))))};function he(e){return e.filter((e=>{const t=Ee[e.type];return t.isSearchable?t.isSearchable(e):!!t.search}))}const Ee={[t.ACTION]:{View:t=>{const{block:r,session:s,flowSession:o,checklistSession:n}=t,c=d(),[l,i]=e.useState(!1),u=o?.id,m=n?.id;return e.useEffect((()=>{i(!1)}),[u,m]),e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:l?void 0:()=>{xe(c,s,r);const e=r.actions.find((e=>e.type===a.START_FLOW));if(e){e.otherFlow?.id!==n?.flow.id&&i(!0)}else c.closeResourceCenter();b(c,s,r.actions)},disabled:l},e.createElement(be,{...t}),e.createElement(pe,{...t}),l&&e.createElement(de,null))}},[t.CHECKLIST]:{View:({checklistSession:t})=>e.createElement("div",{"data-testid":"resource-center-checklist",className:"userflowjs-resource-center-checklist"},e.createElement(W,{session:t}),e.createElement(p,{draftMode:!!t.draftMode&&"CHECKLIST PREVIEW"}))},[t.CONTACT]:{View:t=>{const{block:r,session:s,navigate:o,onChatShow:n}=t,c=d(),l=[];return r.emailEnabled&&l.push({icon:U,label:"Email",isRoute:!0,onClick:e=>{xe(c,s,r,"Email"),o({kind:"email",block:r},e)}}),r.phoneEnabled&&l.push({icon:q,label:"Phone",isRoute:!0,onClick:e=>{xe(c,s,r,"Phone"),o({kind:"phone",block:r},e)}}),r.chatEnabled&&l.push({icon:D,label:"Live-chat",isRoute:!1,onClick:()=>{if(xe(c,s,r,"Chat"),r.chatProvider){const t=Z[r.chatProvider];try{t.show({block:r})}catch(e){console.error(`Userflow.js: Error when showing ${r.chatProvider}:`,e)}n()}else s.draftMode&&window.alert("You have not selected a chat provider. Go to the resource center builder in Userflow. Click the Contact block. Pick a chat provider in the side panel.")}}),e.createElement("div",{className:B({"userflowjs-resource-center-block":!0,"userflowjs-resource-center-block--clickable":1===l.length}),onClick:1===l.length?l[0].onClick:void 0},1===l.length&&e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(H,{icon:l[0].icon})),e.createElement(pe,{...t}),l.length>1&&l.map((({icon:t,label:r,onClick:s},o)=>e.createElement("button",{key:o,className:"userflowjs-resource-center-icon-button",onClick:s,"aria-label":r},e.createElement(H,{icon:t})))),1===l.length&&l[0].isRoute&&e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(H,{icon:O})))}},[t.FLOWS]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{xe(n,s,r),o({kind:"flows",block:r},e)}},e.createElement(be,{...t}),e.createElement(pe,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(H,{icon:O})))},routeTo:({block:e,initialQ:t})=>({kind:"flows",block:e,initialQ:t}),isSearchable:e=>!!e.searchEnabled,search:async({client:e,session:t,block:r,q:s})=>{const{flows:o}=await e.send({kind:"ListResourceCenterBlockFlows",sessionId:t.id,blockCvid:r.cvid},{handlesRejection:!0}),n=Ce(o,s),c=n.slice(0,5);return{block:r,truncated:c.length===n.length,results:c.map((e=>({kind:"flow",flow:e})))}}},[t.KNOWLEDGE_BASE]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{xe(n,s,r),o({kind:"knowledgeBase",block:r},e)}},e.createElement(be,{...t}),e.createElement(pe,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(H,{icon:O})))},routeTo:({block:e,initialQ:t})=>({kind:"knowledgeBase",block:e,initialQ:t}),search:async({client:e,session:t,block:r,q:s})=>{const{truncated:o,articles:n}=await e.send({kind:"SearchKnowledgeBase",sessionId:t.id,blockCvid:r.cvid,q:s,offset:0,limit:5},{handlesRejection:!0});return{block:r,truncated:o,results:n.map((e=>({kind:"article",article:e})))}}},[t.MESSAGE]:{View:({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-block"},e.createElement("div",{className:"userflowjs-resource-center-block-text userflowjs-bubble-content"},e.createElement(k,{doc:t.content,lookupAttribute:N(r.data)})))},[t.SUBPAGE]:{View:t=>{const{block:r,session:s,navigate:o}=t,n=d();return e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{xe(n,s,r),o({kind:"subpage",block:r},e)}},e.createElement(be,{...t}),e.createElement(pe,{...t}),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(H,{icon:O})))}}},be=({block:t})=>t.icon?e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(H,{icon:t.icon,size:16})):null,pe=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-block-text"},e.createElement(v,{doc:t.name,lookupAttribute:N(r.data)})),ke=({session:t,navigate:r})=>{const s=d(),o=t.version.resourceCenter.blocks,n=he(o),{t:c}=K(),l=e.useRef(null),[a,i]=e.useState(""),[u,m]=fe(a,i),[f,w]=e.useState(null);return e.useEffect((()=>{if(""===a.trim())return void w(null);let e=!1;return(async()=>{w(null);const r=await Promise.all(o.map((async e=>{const{search:r}=Ee[e.type];if(!r)return null;try{return await r({client:s,session:t,block:e,q:a})}catch(o){return console.error(`Userflow.js: Global search failed for ${e.type} block=`,e,"error=",o),null}})));e||w(r.filter((e=>null!=e&&e.results.length>0)))})(),()=>{e=!0}}),[s,t,o,a]),e.useEffect((()=>{l.current?.focus({preventScroll:!0})}),[]),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:l,className:"userflowjs-text-input",type:"text",value:u,onChange:e=>m(e.target.value),placeholder:c("resource_center.search_placeholder")})),""===a.trim()?e.createElement("div",{"data-testid":"resource-center-empty-query",className:"userflowjs-resource-center-list-route-error"},c("resource_center.search_in")," ",n.map(((r,s)=>e.createElement(e.Fragment,{key:r.cvid},s>0&&(s===n.length-1?` ${c("and")} `:", "),e.createElement("b",null,e.createElement(v,{doc:r.name,lookupAttribute:N(t.data)}))))),"."):f?0===f.length?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},c("resource_center.no_results_found")):f.map((({block:o,truncated:n,results:l},i)=>{const u=Ee[o.type],d=u.routeTo&&u.routeTo({block:o,initialQ:a});return e.createElement(e.Fragment,{key:o.cvid},i>0&&e.createElement("div",{className:"userflowjs-resource-center-divider"}),e.createElement("div",{className:"userflowjs-resource-center-label"},e.createElement(v,{doc:o.name,lookupAttribute:N(t.data)})),l.map(((s,n)=>"flow"===s.kind?e.createElement(Se,{key:s.flow.id,block:o,session:t,flow:s.flow,navigate:r}):"article"===s.kind?e.createElement(Ne,{key:n,block:o,session:t,article:s.article}):null)),!n&&d&&e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:e=>{xe(s,t,o),r(d,e)}},e.createElement("div",{className:"userflowjs-resource-center-block-text"},c("more"),":"," ",e.createElement(v,{doc:o.name,lookupAttribute:N(t.data)})),e.createElement("div",{className:"userflowjs-resource-center-block-nav-icon"},e.createElement(H,{icon:O}))))})):e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(de,null)))},ve=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.emailContent,lookupAttribute:N(r.data)})),ge=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.phoneContent,lookupAttribute:N(r.data)})),je=({block:t,initialQ:r,session:s,navigate:o})=>{const{t:n}=K(),c=e.useRef(null),[l,a]=e.useState(r||""),[i,u]=fe(l,a),{data:d,error:m}=me({kind:"ListResourceCenterBlockFlows",sessionId:s.id,blockCvid:t.cvid}),f=d?.flows,w=e.useMemo((()=>f?Ce(f,l):null),[f,l]);return e.useEffect((()=>{c.current?.focus({preventScroll:!0})}),[]),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-header"},e.createElement("div",{className:"userflowjs-resource-center-list-route-title"},e.createElement(v,{doc:t.name,lookupAttribute:N(s.data)}))),t.searchEnabled&&e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:c,className:"userflowjs-text-input",type:"text",value:i,onChange:e=>u(e.target.value),placeholder:n("resource_center.search_placeholder")})),m?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.generic_error")):w?0===w.length?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.no_results_found")):w.map((r=>e.createElement(Se,{key:r.id,block:t,session:s,flow:r,navigate:o}))):e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(de,null)))};function Ce(e,t){const r=t.toLowerCase().trim();return""===r?e:e.filter((e=>e.name.toLowerCase().includes(r)))}const Se=({block:t,session:r,flow:s,navigate:o})=>{const n=d(),[c,l]=e.useState(!1);return e.useEffect((()=>{if(!c||s.type!==i.CHECKLIST)return;const e=()=>{n.checklistSession?.flow.id===s.id&&(t(),o(null))},t=()=>{n.off("checklistChanged",e)};return n.on("checklistChanged",e),t}),[n,c,s.type,s.id,o]),e.createElement("button",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:()=>{xe(n,r,t,s.name),n.startFlow({flowId:s.id,startReason:u.RESOURCE_CENTER,replaceCurrent:!0}),l(!0);const e=g(s.url,{lookupAttribute:N(r.data)});e&&j(e)},disabled:c},e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(H,{icon:s.type===i.CHECKLIST?"regular/tasks":"regular/shoe-prints",size:16})),e.createElement("div",{className:"userflowjs-resource-center-block-text"},s.name),c&&e.createElement(de,null))},ye=({block:t,initialQ:r,session:s,bodyRef:o})=>{const{t:n}=K(),c=e.useRef(null),[l,a]=e.useState(r||""),[i,u]=fe(l,a),{loading:d,loadingMore:m,data:f,messageForData:w,error:h,loadMore:E}=me({kind:"SearchKnowledgeBase",sessionId:s.id,blockCvid:t.cvid,q:l,offset:0}),b=f?.truncated,p=e.useCallback((()=>{E(((e,t)=>({...t,offset:e.articles.length})),((e,t)=>({...t,articles:[...e.articles,...t.articles]})))}),[E]);e.useEffect((()=>{const e=o.current;if(!e||d||m||b)return;const t=()=>{e.scrollHeight-e.clientHeight-e.scrollTop>400||p()};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}}),[o,d,m,b,p]),e.useEffect((()=>{c.current?.focus({preventScroll:!0})}),[]);let k=t.knowledgeBaseUrl||"";return k.match(/^https?:\/\//)||(k=`http://${k}`),e.createElement(e.Fragment,null,e.createElement("div",{className:"userflowjs-resource-center-list-route-header"},e.createElement("div",{className:"userflowjs-resource-center-list-route-title"},e.createElement(v,{doc:t.name,lookupAttribute:N(s.data)})),e.createElement("a",{className:"userflowjs-resource-center-icon-button",href:k,target:"_blank",rel:"noopener noreferrer"},e.createElement(H,{icon:z}))),e.createElement("div",{className:"userflowjs-resource-center-list-route-search"},e.createElement("input",{ref:c,className:"userflowjs-text-input",type:"text",value:i,onChange:e=>u(e.target.value),placeholder:n("resource_center.search_placeholder")})),h?e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},"quota_exceeded"===h.code?"Sorry, this company has reached its max number of searches. Consider asking Userflow to be moved to a dedicated search engine for a higher quota.":n("resource_center.generic_error")):d||!f?e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(de,null)):0===f.articles.length?""===w?.q?null:e.createElement("div",{className:"userflowjs-resource-center-list-route-error"},n("resource_center.no_results_found")):e.createElement(e.Fragment,null,""===w?.q&&e.createElement("div",{className:"userflowjs-resource-center-label"},n("resource_center.suggested_articles")),f.articles.map(((r,o)=>e.createElement(Ne,{key:o,block:t,session:s,article:r}))),m&&e.createElement("div",{className:"userflowjs-resource-center-list-route-spinner"},e.createElement(de,null))))},Ne=({block:t,article:r,session:s})=>{const o=d();return e.createElement("a",{className:"userflowjs-resource-center-block userflowjs-resource-center-block--clickable",onClick:()=>{xe(o,s,t,r.title)},href:r.url,target:"_blank",rel:"noopener noreferrer"},e.createElement("div",{className:"userflowjs-resource-center-block-icon"},e.createElement(H,{icon:"regular/file-alt",size:16})),e.createElement("div",{className:"userflowjs-resource-center-block-text"},e.createElement("span",{dangerouslySetInnerHTML:{__html:r.htmlTitle}}),e.createElement("div",{className:"userflowjs-resource-center-block-subtext",dangerouslySetInnerHTML:{__html:r.htmlSnippet}})))},_e=({block:t,session:r})=>e.createElement("div",{className:"userflowjs-resource-center-content-route userflowjs-bubble-content"},e.createElement(k,{doc:t.content,lookupAttribute:N(r.data)}));function xe(e,t,r,s){e.send({kind:"ClickResourceCenter",sessionId:t.id,description:r?g(r.name,{lookupAttribute:N(t.data)})+(s?` - ${s}`:""):s},{batch:!0})}export default we;export{we as ResourceCenterApp};
package/bubble-frame.css CHANGED
@@ -1,11 +1,3 @@
1
- b,
2
- strong {
3
- font-weight: var(--userflow-font-weight-bold, 600);
4
- }
5
- i,
6
- em {
7
- font-style: italic;
8
- }
9
1
  [dir="rtl"] .userflowjs-rtl-mirrored,
10
2
  [dir="rtl"] .userflowjs-resource-center-block-nav-icon {
11
3
  transform: scaleX(-1);
@@ -51,6 +43,14 @@ em {
51
43
  font-family: var(--userflow-font-family);
52
44
  font-size: var(--userflow-font-size, 16px);
53
45
  }
46
+ .userflowjs-theme-root b,
47
+ .userflowjs-theme-root strong {
48
+ font-weight: var(--userflow-font-weight-bold, 600);
49
+ }
50
+ .userflowjs-theme-root i,
51
+ .userflowjs-theme-root em {
52
+ font-style: italic;
53
+ }
54
54
  .userflowjs-theme-root a {
55
55
  color: var(--userflow-link-color);
56
56
  text-decoration: underline;
package/hash.txt CHANGED
@@ -1 +1 @@
1
- 80241ffbf593379fee93565682f73ab084495edf
1
+ 03ec8fba5c203c8a784b0bcde7618156ca23558b
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "userflow.js-self-hosted",
3
- "version": "0.1.1002497",
3
+ "version": "0.1.1002513",
4
4
  "description": "Self-hosted version of Userflow.js",
5
5
  "main": "userflow.js"
6
6
  }
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){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}getItem(e){return e=this.formatKey(e),"undefined"==typeof window?null:window[this.type].getItem(e)}setItem(e,t){e=this.formatKey(e),"undefined"!=typeof window&&window[this.type].setItem(e,t)}removeItem(e){if(e=this.formatKey(e),"undefined"!=typeof window)return window[this.type].removeItem(e)}clear(){if("undefined"!=typeof window)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,f;function E(e,t,{toOrigin:s}={}){e.postMessage(t,s||"*")}function w(e,{fromWindow:t,fromOrigin:s}={}){const i=i=>{if(!i.isTrusted)return;if(t&&t!==i.source)return;if(s&&i.origin!==s)return;const o=i.data;o&&"object"==typeof o&&"string"==typeof o.kind&&o.kind.startsWith("userflow:")&&!0===e(o)&&n()};window.addEventListener("message",i);const n=()=>window.removeEventListener("message",i);return n}(h||(h={})).INPUT="INPUT",(f=u||(u={})).AUTO="AUTO",f.MANUAL="MANUAL";const T=new Set;let p=!1;function S(e){return function(){if(p)return;p=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),C()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{C()}))}(),T.add(e),()=>{g(e)}}function g(e){T.delete(e)}function C(){T.forEach((e=>e()))}class I{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){E(window.opener,e,{toOrigin:"https://userflow.com"})}onBuilderMessage(e){return this.unregisterOnMessage=w(e,{fromOrigin:"https://userflow.com"}),!1}async captureScreenshot(e,t,s,i){E(window,{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=>{w((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,U,A,L,y,R,O,v,N,_,b,D,F,M,P,B,x,H,G,W,$,V,j,K,z,Y,J,X,Q,Z,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,fe,Ee,we,Te,pe,Se,ge,Ce,Ie,me,ke,Ue,Ae,Le,ye,Re,Oe,ve,Ne,_e,be,De,Fe,Me,Pe;(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",(A=U||(U={})).SECOND="SECOND",A.MINUTE="MINUTE",A.HOUR="HOUR",A.DAY="DAY",(y=L||(L={})).ACTION="ACTION",y.DRAFT="DRAFT",y.LINK="LINK",y.LAUNCHER_SEEN="LAUNCHER_SEEN",y.RESOURCE_CENTER="RESOURCE_CENTER",y.USERFLOWJS="USERFLOWJS",(O=R||(R={})).STRING="STRING",O.BOOLEAN="BOOLEAN",O.NUMBER="NUMBER",O.DATETIME="DATETIME",O.LIST="LIST",(N=v||(v={})).FLOW="FLOW",N.CHECKLIST="CHECKLIST",N.LAUNCHER="LAUNCHER",N.RESOURCE_CENTER="RESOURCE_CENTER",(b=_||(_={})).ALWAYS_TRUE="ALWAYS_TRUE",b.ATTRIBUTE="ATTRIBUTE",b.CLAUSE="CLAUSE",b.ELEMENT="ELEMENT",b.FILLED_IN_INPUT="FILLED_IN_INPUT",b.FLOW="FLOW",b.INPUT_VALUE="INPUT_VALUE",b.PAGE="PAGE",b.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(D||(D={})),(F||(F={})).INPUT="INPUT",(P=M||(M={})).ABSOLUTE_EQ="ABSOLUTE_EQ",P.ABSOLUTE_GT="ABSOLUTE_GT",P.ABSOLUTE_LT="ABSOLUTE_LT",P.AND="AND",P.CONTAINS="CONTAINS",P.EMPTY="EMPTY",P.ENDS_WITH="ENDS_WITH",P.EQ="EQ",P.EXCLUDES_ALL="EXCLUDES_ALL",P.EXCLUDES_ANY="EXCLUDES_ANY",P.FALSE="FALSE",P.GT="GT",P.INCLUDES_ALL="INCLUDES_ALL",P.INCLUDES_ANY="INCLUDES_ANY",P.LT="LT",P.NE="NE",P.NOT_CONTAINS="NOT_CONTAINS",P.NOT_EMPTY="NOT_EMPTY",P.NOT_REGEX="NOT_REGEX",P.OR="OR",P.REGEX="REGEX",P.RELATIVE_EQ="RELATIVE_EQ",P.RELATIVE_GT="RELATIVE_GT",P.RELATIVE_LT="RELATIVE_LT",P.STARTS_WITH="STARTS_WITH",P.TRUE="TRUE",P.URL="URL",(x=B||(B={})).CLICK="CLICK",x.DISABLED="DISABLED",x.MOUSEDOWN="MOUSEDOWN",x.NOT_CLICK="NOT_CLICK",x.NOT_DISABLED="NOT_DISABLED",x.NOT_PRESENT="NOT_PRESENT",x.PRESENT="PRESENT",(G=H||(H={})).ASSET="ASSET",G.CARTOON="CARTOON",G.NONE="NONE",G.URL="URL",($=W||(W={})).INSIDE="INSIDE",$.OUTSIDE="OUTSIDE",(j=V||(V={})).TOP_LEFT="TOP_LEFT",j.TOP_CENTER="TOP_CENTER",j.TOP_RIGHT="TOP_RIGHT",j.BOTTOM_RIGHT="BOTTOM_RIGHT",j.BOTTOM_CENTER="BOTTOM_CENTER",j.BOTTOM_LEFT="BOTTOM_LEFT",j.CENTER="CENTER",(z=K||(K={})).GOOGLE="GOOGLE",z.STANDARD="STANDARD",(J=Y||(Y={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",J.DISMISS="DISMISS",(Q=X||(X={})).DISMISS="DISMISS",Q.NONE="NONE",(q=Z||(Z={})).DEFAULT="DEFAULT",q.PLAINTEXT="PLAINTEXT",(te=ee||(ee={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",te.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",te.NONE="NONE",(ie=se||(se={})).BUBBLE="BUBBLE",ie.END="END",ie.ERROR="ERROR",ie.FLAG="FLAG",(oe=ne||(ne={})).MANUAL="MANUAL",oe.NONE="NONE",oe.SYNTHETIC="SYNTHETIC",(ae=re||(re={})).BUBBLE="BUBBLE",ae.HIDDEN="HIDDEN",ae.MODAL="MODAL",ae.TOOLTIP="TOOLTIP",(le=ce||(ce={})).ABOVE="ABOVE",le.BELOW="BELOW",le.LEFT="LEFT",le.RIGHT="RIGHT",(he=de||(de={})).CLOSE_FLOW="CLOSE_FLOW",he.EVAL_JS="EVAL_JS",he.GO_TO_STEP="GO_TO_STEP",he.NAVIGATE="NAVIGATE",he.SNOOZE="SNOOZE",he.START_FLOW="START_FLOW",(fe=ue||(ue={})).NEW_TAB="NEW_TAB",fe.SAME_TAB="SAME_TAB",(we=Ee||(Ee={})).MULTILINE_TEXT="MULTILINE_TEXT",we.MULTIPLE_CHOICE="MULTIPLE_CHOICE",we.NPS="NPS",we.SCALE="SCALE",we.STARS="STARS",we.TEXT="TEXT",(pe=Te||(Te={})).ACTION="ACTION",pe.CHECKLIST="CHECKLIST",pe.CONTACT="CONTACT",pe.FLOWS="FLOWS",pe.KNOWLEDGE_BASE="KNOWLEDGE_BASE",pe.MESSAGE="MESSAGE",pe.SUBPAGE="SUBPAGE",(ge=Se||(Se={})).CRISP="CRISP",ge.CUSTOM="CUSTOM",ge.FRESHCHAT="FRESHCHAT",ge.HELPSCOUT="HELPSCOUT",ge.HUBSPOT="HUBSPOT",ge.INTERCOM="INTERCOM",ge.ZENDESK="ZENDESK",ge.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ie=Ce||(Ce={})).LAUNCHER_CLICK="LAUNCHER_CLICK",Ie.LAUNCHER_HOVER="LAUNCHER_HOVER",Ie.TARGET_CLICK="TARGET_CLICK",Ie.TARGET_HOVER="TARGET_HOVER",Ie.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",Ie.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(ke=me||(me={})).ACTIVATE="ACTIVATE",ke.DEACTIVATE="DEACTIVATE",ke.NEVER="NEVER",(Ae=Ue||(Ue={})).AUTO="AUTO",Ae.TOP="TOP",Ae.RIGHT="RIGHT",Ae.BOTTOM="BOTTOM",Ae.LEFT="LEFT",(ye=Le||(Le={})).START="START",ye.CENTER="CENTER",ye.END="END",(Oe=Re||(Re={})).PERCENT="PERCENT",Oe.PX="PX",(Ne=ve||(ve={})).BEACON="BEACON",Ne.BUTTON="BUTTON",Ne.HIDDEN="HIDDEN",Ne.ICON="ICON",(be=_e||(_e={})).LAUNCHER="LAUNCHER",be.TARGET="TARGET",(Fe=De||(De={})).ACTIVE="ACTIVE",Fe.COMPLETED="COMPLETED",Fe.ENDED="ENDED",Fe.NOT_SEEN="NOT_SEEN",(Pe=Me||(Me={})).HIGHLIGHT="HIGHLIGHT",Pe.MODAL="MODAL",Pe.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Be={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-")]};function xe(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function He(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function Ge(){let e=d();if(Be.urlFilter){if(e=Be.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}const We=(localStorage.getItem("debug")||"").split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),$e=je("log");let Ve;function je(e){return function(t,...s){if(We){const i=performance.now(),n=Ve?Math.round(i-Ve):0;Ve=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#4579E4;","","color:#4579E4;",...s)}}}$e.group=je("group"),$e.groupCollapsed=je("groupCollapsed"),$e.groupEnd=function(){We&&console.groupEnd()};const Ke=()=>n((()=>import("./ResourceCenterApp.js")),[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("Icons.js",import.meta.url).toString(),new URL("BubbleToolbar.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.obj-str.js",import.meta.url).toString(),new URL("vendor.fortawesome.react-fontawesome.js",import.meta.url).toString(),new URL("vendor.fortawesome.fontawesome-svg-core.js",import.meta.url).toString(),new URL("vendor.prop-types.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("logomark.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("DynamicIcon.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("ChecklistUI.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]);function ze(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class Ye{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 Je=import.meta.url;class Xe{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.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.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{$e(`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,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}),c.setItem("previewFlowId",e.flowId),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void 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}),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(),$e("constructor, build=1002497"),S(this.onUrlChange),this.setTargetEnv(new I),this.checkTestUserAtBoot(),this.toggleUI()}get socketStatus(){return this._socketStatus}destroy(){$e("destroy"),this.reset(),g(this.onUrlChange),this.destroyTargetEnv()}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 s=c.getItem("userflowClientState");if(s)try{e=JSON.parse(s)}catch(t){console.error("Userflow.js: Parse ElementSelectionState error:",t)}e||(e={testUser:null,activeApp:null,elementSelection:null,trackerTesting:null})}return e}checkTestUserAtBoot(){const e=this.getSessionStorageState().testUser;e&&($e("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($e("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?$e("init() ignoring new token since a test user has been identified"):(this.clientToken&&($e("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",$e("connecting to socket");let t="e.userflow.com";"js.getuserflow.com"===new URL(Je).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((()=>{$e("socket opened")})),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),$e("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:"1002497",signature:this.signature,groupExternalId:this.groupId,groupSignature:this.groupSignature,flowSessionId:this.flowSession?.id||null,checklistSessionId:this.checklistSession?.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 $e("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.debounceInactiveDisconnect():($e("disconnecting from socket due to inactivity"),this.disconnect())}),3e5)}hasDraftSession(){return!!this.flowSession?.draftMode||!!this.checklistSession?.draftMode||!!this.resourceCenterSession?.draftMode||this.launcherSessions.some((e=>e.draftMode))}async send(e,{batch:t,handlesRejection:s}={}){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),this.endBatchTimeout=window.setTimeout((()=>{this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}),50)),this.sendRaw(e,{handlesRejection:s})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel)throw Error("Userflow.js: send() should not be called if channel is not set");$e(`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 got phx_error";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",(t=>{r();const s=`Userflow.js error reply (${t.code}): ${t.message}`;console.log(s,"\nClient message:",e,"\nError:",t),i(new o(s,t.code))}))}))}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){$e(`received ${e.kind} message`,e);const{serverClock:t,flowSession:s,flowSessionClock:i,checklistSession:n,checklistSessionClock:o,resourceCenterSession:r}=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"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 $e(`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"SetChecklistSession":return void(o<=t||n?.id===e.session.id?(this.setChecklistSession(e.session,t),this.toggleUI()):$e(`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()):$e(`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"TrackClientCondition":return void this.trackClientCondition(e.condition);case"UnsetChecklistSession":return o>t?void $e(`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 $e(`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(r?.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($e("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)$e("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&&($e("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={}){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={}){$e("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if($e("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)$e("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={}){$e("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 R.STRING;case"number":return R.NUMBER;case"boolean":return R.BOOLEAN;case"datetime":return R.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=R.STRING;break;case"boolean":n=R.BOOLEAN;break;case"integer":case"decimal":n=R.NUMBER;break;case"datetime":n=R.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}={}){$e(`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&&($e(`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:Ge(),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(){$e("reset"),this.externalId=null,this.groupId=null,this.sessionStorageState=null,this.setFlowSession(null,0),this.setChecklistSession(null,0),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}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}),$e(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return $e("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(),$e("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;return{isOpen:this.resourceCenterOpen,hasChecklist:e,uncompletedChecklistTaskCount:e&&t?ze(t):0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Te.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.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===v.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===v.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){$e("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(){$e("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){$e("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===v.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")}setResourceCenterSession(e){const t=this.resourceCenterSession;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===me.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(){this.flowSession||!this.checklistExpandPending&&!this.checklistSession?.version.checklist?.tasks.some((e=>this.taskIsUnacked(e.cvid)))||this.showChecklist(),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.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&&($e("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&($e("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.resourceCenterSession&&Ke();const{RealUI:t}=await e;return new t(this)}catch(e){throw this.reportCspIssue(),e}}async trackClientCondition(e){if(this.clientConditions.has(e.id))return;$e("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.u}))),[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 Ye([]),condition:e,callback:t=>{i.isTrue!==t&&($e("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&&($e("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.u}))),[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 Ye(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})}}),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"))}reportCspIssue(){const e=this.getSessionStorageState();!this.testUserIdentified&&!e.activeApp||this.cspIssueReported||(this.cspIssueReported=!0,$e("csp issue detected"),E(window,{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)}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new Xe;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&&Be.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Be.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Be.customNavigate=e},setUrlFilter(e){Be.urlFilter=e},setInferenceAttributeNames(e){Be.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Be.inferenceAttributeFilters[e]=xe(t)},setInferenceClassNameFilter(e){Be.inferenceClassNameFilters=xe(e)},setScrollPadding(e){Be.scrollPadding=e},setCustomScrollIntoView(e){Be.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},_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;$e(`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)}$e("queue processed")}()}export{H as A,W as B,Se as C,Ce as D,m as E,M as F,Ue as G,_e as H,Le as I,Re as J,ve as L,X as M,Ke as R,L as S,se as T,o as U,ne as V,n as _,F as a,D as b,Be as c,$e as d,_ as e,B as f,Ge as g,Te as h,ze as i,ee as j,Z as k,de as l,v as m,ue as n,S as o,Ee as p,Ye as q,K as r,l as s,He as t,g as u,a as v,Y as w,re as x,V as y,ce 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){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}getItem(e){return e=this.formatKey(e),"undefined"==typeof window?null:window[this.type].getItem(e)}setItem(e,t){e=this.formatKey(e),"undefined"!=typeof window&&window[this.type].setItem(e,t)}removeItem(e){if(e=this.formatKey(e),"undefined"!=typeof window)return window[this.type].removeItem(e)}clear(){if("undefined"!=typeof window)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,f;function E(e,t,{toOrigin:s}={}){e.postMessage(t,s||"*")}function w(e,{fromWindow:t,fromOrigin:s}={}){const i=i=>{if(!i.isTrusted)return;if(t&&t!==i.source)return;if(s&&i.origin!==s)return;const o=i.data;o&&"object"==typeof o&&"string"==typeof o.kind&&o.kind.startsWith("userflow:")&&!0===e(o)&&n()};window.addEventListener("message",i);const n=()=>window.removeEventListener("message",i);return n}(h||(h={})).INPUT="INPUT",(f=u||(u={})).AUTO="AUTO",f.MANUAL="MANUAL";const T=new Set;let p=!1;function S(e){return function(){if(p)return;p=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),C()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{C()}))}(),T.add(e),()=>{g(e)}}function g(e){T.delete(e)}function C(){T.forEach((e=>e()))}class I{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){E(window.opener,e,{toOrigin:"https://userflow.com"})}onBuilderMessage(e){return this.unregisterOnMessage=w(e,{fromOrigin:"https://userflow.com"}),!1}async captureScreenshot(e,t,s,i){E(window,{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=>{w((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,U,A,L,y,R,O,v,N,_,b,D,F,M,P,B,x,H,G,W,$,V,j,K,z,Y,J,X,Q,Z,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,fe,Ee,we,Te,pe,Se,ge,Ce,Ie,me,ke,Ue,Ae,Le,ye,Re,Oe,ve,Ne,_e,be,De,Fe,Me,Pe;(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",(A=U||(U={})).SECOND="SECOND",A.MINUTE="MINUTE",A.HOUR="HOUR",A.DAY="DAY",(y=L||(L={})).ACTION="ACTION",y.DRAFT="DRAFT",y.LINK="LINK",y.LAUNCHER_SEEN="LAUNCHER_SEEN",y.RESOURCE_CENTER="RESOURCE_CENTER",y.USERFLOWJS="USERFLOWJS",(O=R||(R={})).STRING="STRING",O.BOOLEAN="BOOLEAN",O.NUMBER="NUMBER",O.DATETIME="DATETIME",O.LIST="LIST",(N=v||(v={})).FLOW="FLOW",N.CHECKLIST="CHECKLIST",N.LAUNCHER="LAUNCHER",N.RESOURCE_CENTER="RESOURCE_CENTER",(b=_||(_={})).ALWAYS_TRUE="ALWAYS_TRUE",b.ATTRIBUTE="ATTRIBUTE",b.CLAUSE="CLAUSE",b.ELEMENT="ELEMENT",b.FILLED_IN_INPUT="FILLED_IN_INPUT",b.FLOW="FLOW",b.INPUT_VALUE="INPUT_VALUE",b.PAGE="PAGE",b.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(D||(D={})),(F||(F={})).INPUT="INPUT",(P=M||(M={})).ABSOLUTE_EQ="ABSOLUTE_EQ",P.ABSOLUTE_GT="ABSOLUTE_GT",P.ABSOLUTE_LT="ABSOLUTE_LT",P.AND="AND",P.CONTAINS="CONTAINS",P.EMPTY="EMPTY",P.ENDS_WITH="ENDS_WITH",P.EQ="EQ",P.EXCLUDES_ALL="EXCLUDES_ALL",P.EXCLUDES_ANY="EXCLUDES_ANY",P.FALSE="FALSE",P.GT="GT",P.INCLUDES_ALL="INCLUDES_ALL",P.INCLUDES_ANY="INCLUDES_ANY",P.LT="LT",P.NE="NE",P.NOT_CONTAINS="NOT_CONTAINS",P.NOT_EMPTY="NOT_EMPTY",P.NOT_REGEX="NOT_REGEX",P.OR="OR",P.REGEX="REGEX",P.RELATIVE_EQ="RELATIVE_EQ",P.RELATIVE_GT="RELATIVE_GT",P.RELATIVE_LT="RELATIVE_LT",P.STARTS_WITH="STARTS_WITH",P.TRUE="TRUE",P.URL="URL",(x=B||(B={})).CLICK="CLICK",x.DISABLED="DISABLED",x.MOUSEDOWN="MOUSEDOWN",x.NOT_CLICK="NOT_CLICK",x.NOT_DISABLED="NOT_DISABLED",x.NOT_PRESENT="NOT_PRESENT",x.PRESENT="PRESENT",(G=H||(H={})).ASSET="ASSET",G.CARTOON="CARTOON",G.NONE="NONE",G.URL="URL",($=W||(W={})).INSIDE="INSIDE",$.OUTSIDE="OUTSIDE",(j=V||(V={})).TOP_LEFT="TOP_LEFT",j.TOP_CENTER="TOP_CENTER",j.TOP_RIGHT="TOP_RIGHT",j.BOTTOM_RIGHT="BOTTOM_RIGHT",j.BOTTOM_CENTER="BOTTOM_CENTER",j.BOTTOM_LEFT="BOTTOM_LEFT",j.CENTER="CENTER",(z=K||(K={})).GOOGLE="GOOGLE",z.STANDARD="STANDARD",(J=Y||(Y={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",J.DISMISS="DISMISS",(Q=X||(X={})).DISMISS="DISMISS",Q.NONE="NONE",(q=Z||(Z={})).DEFAULT="DEFAULT",q.PLAINTEXT="PLAINTEXT",(te=ee||(ee={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",te.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",te.NONE="NONE",(ie=se||(se={})).BUBBLE="BUBBLE",ie.END="END",ie.ERROR="ERROR",ie.FLAG="FLAG",(oe=ne||(ne={})).MANUAL="MANUAL",oe.NONE="NONE",oe.SYNTHETIC="SYNTHETIC",(ae=re||(re={})).BUBBLE="BUBBLE",ae.HIDDEN="HIDDEN",ae.MODAL="MODAL",ae.TOOLTIP="TOOLTIP",(le=ce||(ce={})).ABOVE="ABOVE",le.BELOW="BELOW",le.LEFT="LEFT",le.RIGHT="RIGHT",(he=de||(de={})).CLOSE_FLOW="CLOSE_FLOW",he.EVAL_JS="EVAL_JS",he.GO_TO_STEP="GO_TO_STEP",he.NAVIGATE="NAVIGATE",he.SNOOZE="SNOOZE",he.START_FLOW="START_FLOW",(fe=ue||(ue={})).NEW_TAB="NEW_TAB",fe.SAME_TAB="SAME_TAB",(we=Ee||(Ee={})).MULTILINE_TEXT="MULTILINE_TEXT",we.MULTIPLE_CHOICE="MULTIPLE_CHOICE",we.NPS="NPS",we.SCALE="SCALE",we.STARS="STARS",we.TEXT="TEXT",(pe=Te||(Te={})).ACTION="ACTION",pe.CHECKLIST="CHECKLIST",pe.CONTACT="CONTACT",pe.FLOWS="FLOWS",pe.KNOWLEDGE_BASE="KNOWLEDGE_BASE",pe.MESSAGE="MESSAGE",pe.SUBPAGE="SUBPAGE",(ge=Se||(Se={})).CRISP="CRISP",ge.CUSTOM="CUSTOM",ge.FRESHCHAT="FRESHCHAT",ge.HELPSCOUT="HELPSCOUT",ge.HUBSPOT="HUBSPOT",ge.INTERCOM="INTERCOM",ge.ZENDESK="ZENDESK",ge.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ie=Ce||(Ce={})).LAUNCHER_CLICK="LAUNCHER_CLICK",Ie.LAUNCHER_HOVER="LAUNCHER_HOVER",Ie.TARGET_CLICK="TARGET_CLICK",Ie.TARGET_HOVER="TARGET_HOVER",Ie.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",Ie.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(ke=me||(me={})).ACTIVATE="ACTIVATE",ke.DEACTIVATE="DEACTIVATE",ke.NEVER="NEVER",(Ae=Ue||(Ue={})).AUTO="AUTO",Ae.TOP="TOP",Ae.RIGHT="RIGHT",Ae.BOTTOM="BOTTOM",Ae.LEFT="LEFT",(ye=Le||(Le={})).START="START",ye.CENTER="CENTER",ye.END="END",(Oe=Re||(Re={})).PERCENT="PERCENT",Oe.PX="PX",(Ne=ve||(ve={})).BEACON="BEACON",Ne.BUTTON="BUTTON",Ne.HIDDEN="HIDDEN",Ne.ICON="ICON",(be=_e||(_e={})).LAUNCHER="LAUNCHER",be.TARGET="TARGET",(Fe=De||(De={})).ACTIVE="ACTIVE",Fe.COMPLETED="COMPLETED",Fe.ENDED="ENDED",Fe.NOT_SEEN="NOT_SEEN",(Pe=Me||(Me={})).HIGHLIGHT="HIGHLIGHT",Pe.MODAL="MODAL",Pe.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Be={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-")]};function xe(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function He(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function Ge(){let e=d();if(Be.urlFilter){if(e=Be.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}const We=(localStorage.getItem("debug")||"").split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),$e=je("log");let Ve;function je(e){return function(t,...s){if(We){const i=performance.now(),n=Ve?Math.round(i-Ve):0;Ve=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#4579E4;","","color:#4579E4;",...s)}}}$e.group=je("group"),$e.groupCollapsed=je("groupCollapsed"),$e.groupEnd=function(){We&&console.groupEnd()};const Ke=()=>n((()=>import("./ResourceCenterApp.js")),[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("Icons.js",import.meta.url).toString(),new URL("BubbleToolbar.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.obj-str.js",import.meta.url).toString(),new URL("vendor.fortawesome.react-fontawesome.js",import.meta.url).toString(),new URL("vendor.fortawesome.fontawesome-svg-core.js",import.meta.url).toString(),new URL("vendor.prop-types.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-solid-svg-icons.js",import.meta.url).toString(),new URL("logomark.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("DynamicIcon.js",import.meta.url).toString(),new URL("vendor.fortawesome.pro-regular-svg-icons.js",import.meta.url).toString(),new URL("ChecklistUI.js",import.meta.url).toString(),new URL("vendor.phoenix.js",import.meta.url).toString(),new URL("vendor.uuid.js",import.meta.url).toString()]);function ze(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class Ye{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 Je=import.meta.url;class Xe{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.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.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{$e(`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,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}),c.setItem("previewFlowId",e.flowId),e.testUser?this.identifyTestUser(e.testUser):this.resetTestUser(),void 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}),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(),$e("constructor, build=1002513"),S(this.onUrlChange),this.setTargetEnv(new I),this.checkTestUserAtBoot(),this.toggleUI()}get socketStatus(){return this._socketStatus}destroy(){$e("destroy"),this.reset(),g(this.onUrlChange),this.destroyTargetEnv()}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 s=c.getItem("userflowClientState");if(s)try{e=JSON.parse(s)}catch(t){console.error("Userflow.js: Parse ElementSelectionState error:",t)}e||(e={testUser:null,activeApp:null,elementSelection:null,trackerTesting:null})}return e}checkTestUserAtBoot(){const e=this.getSessionStorageState().testUser;e&&($e("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($e("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?$e("init() ignoring new token since a test user has been identified"):(this.clientToken&&($e("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",$e("connecting to socket");let t="e.userflow.com";"js.getuserflow.com"===new URL(Je).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((()=>{$e("socket opened")})),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),$e("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:"1002513",signature:this.signature,groupExternalId:this.groupId,groupSignature:this.groupSignature,flowSessionId:this.flowSession?.id||null,checklistSessionId:this.checklistSession?.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 $e("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.debounceInactiveDisconnect():($e("disconnecting from socket due to inactivity"),this.disconnect())}),3e5)}hasDraftSession(){return!!this.flowSession?.draftMode||!!this.checklistSession?.draftMode||!!this.resourceCenterSession?.draftMode||this.launcherSessions.some((e=>e.draftMode))}async send(e,{batch:t,handlesRejection:s}={}){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),this.endBatchTimeout=window.setTimeout((()=>{this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}),50)),this.sendRaw(e,{handlesRejection:s})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel)throw Error("Userflow.js: send() should not be called if channel is not set");$e(`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 got phx_error";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",(t=>{r();const s=`Userflow.js error reply (${t.code}): ${t.message}`;console.log(s,"\nClient message:",e,"\nError:",t),i(new o(s,t.code))}))}))}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){$e(`received ${e.kind} message`,e);const{serverClock:t,flowSession:s,flowSessionClock:i,checklistSession:n,checklistSessionClock:o,resourceCenterSession:r}=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"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 $e(`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"SetChecklistSession":return void(o<=t||n?.id===e.session.id?(this.setChecklistSession(e.session,t),this.toggleUI()):$e(`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()):$e(`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"TrackClientCondition":return void this.trackClientCondition(e.condition);case"UnsetChecklistSession":return o>t?void $e(`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 $e(`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(r?.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($e("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)$e("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&&($e("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={}){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={}){$e("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if($e("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)$e("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={}){$e("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 R.STRING;case"number":return R.NUMBER;case"boolean":return R.BOOLEAN;case"datetime":return R.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=R.STRING;break;case"boolean":n=R.BOOLEAN;break;case"integer":case"decimal":n=R.NUMBER;break;case"datetime":n=R.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}={}){$e(`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&&($e(`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:Ge(),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(){$e("reset"),this.externalId=null,this.groupId=null,this.sessionStorageState=null,this.setFlowSession(null,0),this.setChecklistSession(null,0),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}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}),$e(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return $e("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(),$e("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;return{isOpen:this.resourceCenterOpen,hasChecklist:e,uncompletedChecklistTaskCount:e&&t?ze(t):0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Te.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.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===v.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===v.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){$e("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(){$e("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){$e("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===v.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")}setResourceCenterSession(e){const t=this.resourceCenterSession;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===me.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(){this.flowSession||!this.checklistExpandPending&&!this.checklistSession?.version.checklist?.tasks.some((e=>this.taskIsUnacked(e.cvid)))||this.showChecklist(),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.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&&($e("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&($e("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.resourceCenterSession&&Ke();const{RealUI:t}=await e;return new t(this)}catch(e){throw this.reportCspIssue(),e}}async trackClientCondition(e){if(this.clientConditions.has(e.id))return;$e("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.u}))),[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 Ye([]),condition:e,callback:t=>{i.isTrue!==t&&($e("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&&($e("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.u}))),[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 Ye(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})}}),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"))}reportCspIssue(){const e=this.getSessionStorageState();!this.testUserIdentified&&!e.activeApp||this.cspIssueReported||(this.cspIssueReported=!0,$e("csp issue detected"),E(window,{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)}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new Xe;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&&Be.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Be.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Be.customNavigate=e},setUrlFilter(e){Be.urlFilter=e},setInferenceAttributeNames(e){Be.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Be.inferenceAttributeFilters[e]=xe(t)},setInferenceClassNameFilter(e){Be.inferenceClassNameFilters=xe(e)},setScrollPadding(e){Be.scrollPadding=e},setCustomScrollIntoView(e){Be.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},_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;$e(`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)}$e("queue processed")}()}export{H as A,W as B,Se as C,Ce as D,m as E,M as F,Ue as G,_e as H,Le as I,Re as J,ve as L,X as M,Ke as R,L as S,se as T,o as U,ne as V,n as _,F as a,D as b,Be as c,$e as d,_ as e,B as f,Ge as g,Te as h,ze as i,ee as j,Z as k,de as l,v as m,ue as n,S as o,Ee as p,Ye as q,K as r,l as s,He as t,g as u,a as v,Y as w,re as x,V as y,ce as z};export default window.userflow;