userflow.js-self-hosted 0.1.1003270 → 0.1.1003308

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,b as n,i as r,d 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,q as u,m as c,r as d,S as m,E as b,v as p,U as f,w as h,d as w}from"./userflow.js";import{S as g,a as v,V as E,b as y,c as k,T as _}from"./Icons.js";import{F as x}from"./vendor.fortawesome.react-fontawesome.js";import{f as j}from"./vendor.fortawesome.pro-solid-svg-icons.js";import{u as q}from"./vendor.react-i18next.js";import{u as N}from"./client-context.js";const S=e.createContext(null);function T(){const t=e.useContext(S);if(!t)throw new Error("useSession: Session was not set");return t}function C(n){const r=T(),[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 A=({appearance:t,hidden:n,disabled:r,onMouseDown:l,onClick:o,text:i,active:s,children:u})=>e.createElement("button",{className:a({[be(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 I(e){const t=u();t!==new URL(e,t).toString()&&(i.customNavigate?i.customNavigate(e):window.setTimeout((()=>{s(e)}),0))}async function P(e,t,l){const{steps:o}=t.version;switch(l.type){case c.CLOSE_FLOW:switch(t.kind){case"launcher":await e.dismissLauncher(t,{endReason:b.ACTION});break;case"flow":case"checklist":await e.endFlow(t,{endReason:b.ACTION})}return;case c.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 c.GO_TO_STEP:{if("flow"!==t.kind)return;const n=o.find((({crossVersionId:e})=>e===l.stepCvid));if(!n)throw new f("Action points to unknown step: "+l.stepCvid);return void(await e.goToStep(t,n))}case c.NAVIGATE:{if(!l.url)return void console.warn("Userflow.js: NAVIGATE action is missing url property");const e=B(l.url,{lookupAttribute:n(t.data)});return void(l.navigateTarget===d.NEW_TAB?window.open(e):I(e))}case c.SET_ATTRIBUTE:{let t;const n=l.attributeValue||"";switch(l.attributeOperation){case p.SET:t={set:n};break;case p.SET_ONCE:t={set_once:n};break;case p.ADD:t={add:n};break;case p.SUBTRACT:t={subtract:n};break;case p.UNSET:t={set:null};break;default:return}const r=l.attributeFqn||"",o=r.split("/");return void(1===o.length?e.updateUser({[r]:t}):"group"===o[0]?e.updateGroup({[o[1]]:t}):"group_membership"===o[0]&&e.updateGroup({},{membership:{[o[1]]:t}}))}case c.SNOOZE:return void("flow"===t.kind&&l.timeValue&&l.timeUnit&&(e.endFlow(t,{endReason:b.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 c.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?m.DRAFT:m.ACTION,replaceCurrent:!0}):console.warn("Userflow.js: START_FLOW action is missing other flow"))}}async function L(e,t,n){const r=[],l=[],o=[];for(const a of n)a.type===c.NAVIGATE?a.navigateTarget===d.NEW_TAB?r.push(a):o.push(a):l.push(a);for(const a of r)P(e,t,a);await Promise.all(l.map((n=>P(e,t,n))));for(const a of o)P(e,t,a)}const $=({button:t})=>{const n=N(),l=T(),o=C(t.disabledCondition),a=C(t.hiddenCondition);return e.createElement(A,{appearance:t.appearance,hidden:a,disabled:o,onClick:()=>L(n,l,t.actions),text:r(t.text,l.data)})},M=({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:p,inert:f})=>{const{t:w}=q(),E=e.useRef(null),[y,k]=e.useState(""),[_,N]=e.useState(new Set),[S,T]=e.useState(),[C,A]=e.useState(),[I,P]=e.useState(!1),[L,$]=e.useState(!1),[M,F]=e.useState(null),O=e.useMemo((()=>l&&(s?[...l].sort((()=>Math.random()-.5)):l)),[l,s]),U=e=>{if(!f&&p){if(n&&""===y&&[h.MULTILINE_TEXT,h.TEXT].includes(t))return F(w("question.requiredError")),void W();$(!0),F(null),p({...e,onCancel:()=>{$(!1)},onError:e=>{$(!1),F(e||"Sorry, something went wrong saving your answer. Please try again.")}})}},W=e.useCallback((()=>{!f&&E.current&&E.current.focus()}),[f]),[B,D]=e.useState(!1);e.useEffect((()=>{B&&(W(),D(!1))}),[W,B]);const V=e.createElement("div",{className:"userflowjs-bubble-buttons"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:()=>U({answer:{kind:"text",value:y}}),tabIndex:f?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||w("question.submit"))));let z=null,K=0;if(t===h.NPS)u=u||w("question.npsLabelLeft"),d=d||w("question.npsLabelRight"),z=[0,1,2,3,4,5,6,7,8,9,10],K=z.length;else if([h.SCALE,h.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===h.MULTIPLE_CHOICE&&(K=(O?O.length:0)+(o&&!I?1:0));const[J,G]=e.useState(-1),H=-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=H+t;r<0?r=n.length-1:r>n.length-1&&(r=0),G(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 h.MULTILINE_TEXT:Q=e.createElement(e.Fragment,null,e.createElement("textarea",{ref:E,className:"userflowjs-textarea userflowjs-bubble-question__textarea",value:y,onChange:e=>k(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&"Enter"===e.key&&U({answer:{kind:"text",value:y}})},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-1:void 0,rows:3,"aria-required":n?"true":void 0,"aria-invalid":null!=M?"true":void 0}),V);break;case h.MULTIPLE_CHOICE:{const t=()=>{y&&U({answer:{kind:"text",value:y},animationPromise:R()})},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)=>_.has(t))).map((e=>e.value));o&&I&&""!==y&&e.push(y),l!==s||e.length===l?e.length<l?F(w("question.multiple_selection_too_few",{count:l})):e.length>s?F(w("question.multiple_selection_too_many",{count:s})):U({answer:{kind:"list",values:e}}):F(w("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":!!M})},w("question.multiple_selection_hint",{replace:{selected:_.size+(o&&I&&""!==y?1:0),range:l===s?l:`${l}-${s}`}}),M&&e.createElement(e.Fragment,null,". ",e.createElement("span",{role:"alert"},M))),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}),role:i?"group":"radiogroup",tabIndex:f||-1!==H?-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?_.has(r):L&&!I&&y==t}),onClick:L?void 0:()=>{if(i){F(null);const e=new Set(_);_.has(r)?e.delete(r):e.add(r),N(e)}else P(!1),k(t),U({answer:{kind:"text",value:t},animationPromise:R()})},disabled:L,tabIndex:f||r!==H?-1:0,role:i?"checkbox":"radio","aria-label":n||t,"aria-checked":!I&&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(x,{icon:j}))):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&&(I?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:()=>{k(""),P(!1)}},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(x,{icon:j}))):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=>k(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key?"Escape"===e.key&&(e.stopPropagation(),k(""),P(!1)):i?u():t()},onBlur:()=>{""===y&&P(!1)},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-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":w("question.submit")},e.createElement(v,null))):e.createElement("button",{className:"userflowjs-bubble-question__multiple-choice-option",onClick:L?void 0:()=>{F(null),P(!0),D(!0)},disabled:L,tabIndex:f||O?.length!==H?-1:0,role:"radio","aria-label":w("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(x,{icon:j}))):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"},w("question.other"))))),i&&e.createElement("div",{className:"userflowjs-bubble-buttons"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:u,tabIndex:f?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||w("question.submit")))));break}case h.NPS:case h.SCALE:Q=e.createElement(e.Fragment,null,Z,e.createElement("div",{className:"userflowjs-bubble-question__scale-options",role:"radiogroup",tabIndex:f||-1!==H?-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:f||n!==H?-1:0,onClick:()=>{T(t),U({answer:{kind:"number",value:t},animationPromise:R()})},disabled:L,role:"radio","aria-checked":S==t},t)))),Y);break;case h.STARS:Q=e.createElement("div",{className:"userflowjs-bubble-question__stars-wrapper"},Z,e.createElement("div",{className:"userflowjs-bubble-question__stars",role:"radiogroup",tabIndex:f||-1!==H?-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!=C&&C>=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:f||n!==H?-1:0,onClick:()=>{T(t),U({answer:{kind:"number",value:t},animationPromise:R()})},onMouseOver:()=>A(t),onMouseLeave:()=>A(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(g,null)),e.createElement("div",{className:"userflowjs-bubble-question__star-value","aria-hidden":"true"},t))))),Y);break;case h.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=>k(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||U({answer:{kind:"text",value:y}})},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-1:void 0,"aria-required":n?"true":void 0,"aria-invalid":null!=M?"true":void 0}),V)}return e.createElement("div",{className:"userflowjs-bubble-question",style:{pointerEvents:f?"none":void 0}},M&&!(t===h.MULTIPLE_CHOICE&&i)&&e.createElement("div",{className:"userflowjs-bubble-question__error",role:"alert"},M),Q)};function R(){return new Promise((e=>window.setTimeout(e,250)))}const F=({question:t})=>{const n=N(),r=function(){const e=T();if("flow"!==e.kind)throw new Error("useFlowSession: Wrong session kind");return e}();return e.createElement(M,{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=>{w("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]})}))}L(n,r,t.actions)}})},O=({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 U(e=""){return{type:"paragraph",children:[{text:e}]}}function W(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:[U(e)]}}()}function B(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(ue(e))e.text&&n.push(e.text);else switch(e.type){case"attribute":{const r=ae(e,t);r&&n.push(r);break}default:r(e.children)}}(e)))}return r(e.children),n.join("")}function D(e){let t=!0;if(!e)return!0;"string"==typeof e&&(e=W(e));const n=new Set(["attribute","button","image","question","video"]);return ce(e,(e=>{ue(e)?""!==e.text&&(t=!1):"type"in e&&n.has(e.type)&&(t=!1)})),t}const V=e.memo((({doc:t,...n})=>t?("string"==typeof t&&(t=W(t)),e.createElement(z,{parent:t,...n})):null)),z=({parent:t,...n})=>e.createElement(e.Fragment,null,t.children.map(((r,l)=>ue(r)?e.createElement(K,{key:l,node:r}):e.createElement(G,{key:l,node:r,parent:t,...n})))),K=({node:t})=>t.text?e.createElement(J,{node:t},e.createElement(O,{text:t.text})):null,J=({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),G=({node:t,parent:n,...r})=>{const{lookupAttribute:l}=r,o=e.createElement(z,{parent:t,...r});switch(t.type){case"attribute":return e.createElement(H,{node:t,...r});case"button":return e.createElement(X,{node:t,...r});case"button-group":return e.createElement("div",{className:"userflowjs-bubble-buttons"},o);case"column":return e.createElement("div",{style:le(t,n)},o);case"column-group":return e.createElement("div",{className:"p-like",style:re(t)},o);case"container":return e.createElement("div",{className:"p-like"+(t.className?` ${t.className}`:""),style:oe(t)},o);case"image":return e.createElement(Z,{node:t,...r});case"link":return e.createElement("a",{href:B(t.href,{lookupAttribute:l}),target:"same"===t.target?"_top":"_blank",rel:"noopener noreferrer"},o);case"paragraph":return e.createElement("p",{className:te(t)},o);case"heading1":return e.createElement("h1",{className:te(t)},o);case"heading2":return e.createElement("h2",{className:te(t)},o);case"question":return e.createElement(Q,{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(Y,{node:t,...r});default:return e.createElement("div",null,o)}},H=({node:t,lookupAttribute:n})=>{let r=ae(t,n);return e.createElement(J,{node:t},r)},X=({node:t,buttons:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement($,{key:r.id,button:r}):null},Q=({node:t,questions:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement(F,{key:r.id,question:r}):null},Z=({node:t,lookupAttribute:n})=>{const{src:r,widthMode:o,displayWidth:a,width:i,height:s,marginTop:u,marginRight:c,marginBottom:d,marginLeft:m,align:b,hasLink:p,href:f}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:h,blockStyle:w}=ne({widthMode:o,displayWidth:a,width:i,height:s,marginTop:u,marginRight:c,marginBottom:d,marginLeft:m,align:b});let g=e.createElement("img",{src:l(r,(e=>encodeURIComponent(n(e)||""))),style:{...w,objectFit:"contain"}});return p&&f&&(g=e.createElement("a",{href:B(f,{lookupAttribute:n}),target:"_blank",rel:"noopener noreferrer",style:w},g)),e.createElement("div",{className:"p-like"},e.createElement("div",{style:h},g))},Y=({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}=ne({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(ee,{element:t,noFocus:!0,lookupAttribute:n}))))},ee=({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 te(e){return"right"===e.align?"userflowjs-text-align-end":"center"===e.align?"userflowjs-text-align-center":""}function ne({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 re(e){return{display:"flex",alignItems:"stretch",marginRight:`-${null==e.spacing?16:e.spacing}px`}}function le(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 oe(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 ae(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 ie(e){return Array.isArray(e.children)&&void 0===e.addMark}function se(e,t,n="type"){return ie(e)&&e[n]===t}function ue(e){return"string"==typeof e.text}function ce(e,t){function n(e){e&&e.forEach(((e,r)=>e&&function(e,r){t(e,r),ie(e)&&n(e.children)}(e,r)))}n(Array.isArray(e)?e:e.children)}const de=e.memo((({doc:t,lookupAttribute:n})=>t?e.createElement(e.Fragment,null,B(t,{lookupAttribute:n})):null));function me(e,{buttons:t,questions:n}){const r=new Set,l=new Set;if(ce(e,(e=>{se(e,"button")&&r.add(e.cvid),se(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 be(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 pe=new URL("flow-host.css",import.meta.url).href,fe=new URL("bubble-frame.css",import.meta.url).href;const he=({draftMode:t,muted:n,toggleMuted:r,close:l,minimize:o})=>{const{t:a}=q();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(E,null):e.createElement(y,null)),o&&e.createElement("button",{"data-testid":"minimize-button",className:"userflowjs-bubble-toolbar-button",onClick:o,"aria-label":"Minimize checklist"},e.createElement(k,null)),l&&e.createElement("button",{"data-testid":"close-button",className:"userflowjs-bubble-toolbar-button",onClick:l,"aria-label":a("menu.close")},e.createElement(_,null)))};export{he as B,V as R,S,de as a,fe as b,A as c,W as d,T as e,pe as f,ae as g,L as h,ue as i,me as m,I as n,D as r,B as s,C as u};
1
+ import{r as e}from"./vendor.react.js";import{c as t,b as n,i as r,d 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,q as u,m as c,r as d,S as m,E as b,v as p,U as f,w as h,d as w}from"./userflow.js";import{S as g,a as v,V as E,b as y,c as k,T as _}from"./Icons.js";import{F as x}from"./vendor.fortawesome.react-fontawesome.js";import{f as j}from"./vendor.fortawesome.pro-solid-svg-icons.js";import{u as q}from"./vendor.react-i18next.js";import{u as N}from"./client-context.js";const S=e.createContext(null);function T(){const t=e.useContext(S);if(!t)throw new Error("useSession: Session was not set");return t}function C(n){const r=T(),[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 A=({appearance:t,hidden:n,disabled:r,onMouseDown:l,onClick:o,text:i,active:s,children:u})=>e.createElement("button",{className:a({[be(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 I(e){const t=u();t!==new URL(e,t).toString()&&(i.customNavigate?i.customNavigate(e):window.setTimeout((()=>{s(e)}),0))}async function P(e,t,l){const{steps:o}=t.version;switch(l.type){case c.CLOSE_FLOW:switch(t.kind){case"launcher":await e.dismissLauncher(t,{endReason:b.ACTION});break;case"flow":case"checklist":await e.endFlow(t,{endReason:b.ACTION})}return;case c.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 c.GO_TO_STEP:{if("flow"!==t.kind)return;const n=o.find((({crossVersionId:e})=>e===l.stepCvid));if(!n)throw new f("Action points to unknown step: "+l.stepCvid);return void(await e.goToStep(t,n))}case c.NAVIGATE:{if(!l.url)return void console.warn("Userflow.js: NAVIGATE action is missing url property");const e=B(l.url,{lookupAttribute:n(t.data)});return void(l.navigateTarget===d.NEW_TAB?window.open(e):I(e))}case c.SET_ATTRIBUTE:{let t;const n=l.attributeValue||"";switch(l.attributeOperation){case p.SET:t={set:n};break;case p.SET_ONCE:t={set_once:n};break;case p.ADD:t={add:n};break;case p.SUBTRACT:t={subtract:n};break;case p.UNSET:t={set:null};break;default:return}const r=l.attributeFqn||"",o=r.split("/");return void(1===o.length?e.updateUser({[r]:t}):"group"===o[0]?e.updateGroup({[o[1]]:t}):"group_membership"===o[0]&&e.updateGroup({},{membership:{[o[1]]:t}}))}case c.SNOOZE:return void("flow"===t.kind&&l.timeValue&&l.timeUnit&&(e.endFlow(t,{endReason:b.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 c.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?m.DRAFT:m.ACTION,replaceCurrent:!0}):console.warn("Userflow.js: START_FLOW action is missing other flow"))}}async function L(e,t,n){const r=[],l=[],o=[];for(const a of n)a.type===c.NAVIGATE?a.navigateTarget===d.NEW_TAB?r.push(a):o.push(a):l.push(a);for(const a of r)P(e,t,a);await Promise.all(l.map((n=>P(e,t,n))));for(const a of o)P(e,t,a)}const $=({button:t})=>{const n=N(),l=T(),o=C(t.disabledCondition),a=C(t.hiddenCondition);return e.createElement(A,{appearance:t.appearance,hidden:a,disabled:o,onClick:()=>L(n,l,t.actions),text:r(t.text,l.data)})},M=({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:p,inert:f})=>{const{t:w}=q(),E=e.useRef(null),[y,k]=e.useState(""),[_,N]=e.useState(new Set),[S,T]=e.useState(),[C,A]=e.useState(),[I,P]=e.useState(!1),[L,$]=e.useState(!1),[M,F]=e.useState(null),O=e.useMemo((()=>l&&(s?[...l].sort((()=>Math.random()-.5)):l)),[l,s]),U=e=>{if(!f&&p){if(n&&""===y&&[h.MULTILINE_TEXT,h.TEXT].includes(t))return F(w("question.requiredError")),void W();$(!0),F(null),p({...e,onCancel:()=>{$(!1)},onError:e=>{$(!1),F(e||"Sorry, something went wrong saving your answer. Please try again.")}})}},W=e.useCallback((()=>{!f&&E.current&&E.current.focus()}),[f]),[B,D]=e.useState(!1);e.useEffect((()=>{B&&(W(),D(!1))}),[W,B]);const V=e.createElement("div",{className:"userflowjs-bubble-buttons"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:()=>U({answer:{kind:"text",value:y}}),tabIndex:f?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||w("question.submit"))));let z=null,K=0;if(t===h.NPS)u=u||w("question.npsLabelLeft"),d=d||w("question.npsLabelRight"),z=[0,1,2,3,4,5,6,7,8,9,10],K=z.length;else if([h.SCALE,h.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===h.MULTIPLE_CHOICE&&(K=(O?O.length:0)+(o&&!I?1:0));const[J,G]=e.useState(-1),H=-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=H+t;r<0?r=n.length-1:r>n.length-1&&(r=0),G(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 h.MULTILINE_TEXT:Q=e.createElement(e.Fragment,null,e.createElement("textarea",{ref:E,className:"userflowjs-textarea userflowjs-bubble-question__textarea",value:y,onChange:e=>k(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&"Enter"===e.key&&U({answer:{kind:"text",value:y}})},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-1:void 0,rows:3,"aria-required":n?"true":void 0,"aria-invalid":null!=M?"true":void 0}),V);break;case h.MULTIPLE_CHOICE:{const t=()=>{y&&U({answer:{kind:"text",value:y},animationPromise:R()})},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)=>_.has(t))).map((e=>e.value));o&&I&&""!==y&&e.push(y),l!==s||e.length===l?e.length<l?F(w("question.multiple_selection_too_few",{count:l})):e.length>s?F(w("question.multiple_selection_too_many",{count:s})):U({answer:{kind:"list",values:e}}):F(w("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":!!M})},w("question.multiple_selection_hint",{replace:{selected:_.size+(o&&I&&""!==y?1:0),range:l===s?l:`${l}-${s}`}}),M&&e.createElement(e.Fragment,null,". ",e.createElement("span",{role:"alert"},M))),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}),role:i?"group":"radiogroup",tabIndex:f||-1!==H?-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?_.has(r):L&&!I&&y==t}),onClick:L?void 0:()=>{if(i){F(null);const e=new Set(_);_.has(r)?e.delete(r):e.add(r),N(e)}else P(!1),k(t),U({answer:{kind:"text",value:t},animationPromise:R()})},disabled:L,tabIndex:f||r!==H?-1:0,role:i?"checkbox":"radio","aria-label":n||t,"aria-checked":!I&&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(x,{icon:j}))):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&&(I?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:()=>{k(""),P(!1)}},e.createElement("div",{className:"userflowjs-bubble-question__multiple-choice-checkbox-inner"},e.createElement(x,{icon:j}))):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=>k(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key?"Escape"===e.key&&(e.stopPropagation(),k(""),P(!1)):i?u():t()},onBlur:()=>{""===y&&P(!1)},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-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":w("question.submit")},e.createElement(v,null))):e.createElement("button",{className:"userflowjs-bubble-question__multiple-choice-option",onClick:L?void 0:()=>{F(null),P(!0),D(!0)},disabled:L,tabIndex:f||O?.length!==H?-1:0,role:"radio","aria-label":w("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(x,{icon:j}))):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"},w("question.other"))))),i&&e.createElement("div",{className:"userflowjs-bubble-buttons"},e.createElement("button",{className:"userflowjs-bubble-button userflowjs-bubble-button--primary",onClick:u,tabIndex:f?-1:void 0,disabled:L},e.createElement("div",{className:"userflowjs-bubble-button-text",role:"presentation"},r||w("question.submit")))));break}case h.NPS:case h.SCALE:Q=e.createElement(e.Fragment,null,Z,e.createElement("div",{className:"userflowjs-bubble-question__scale-options",role:"radiogroup",tabIndex:f||-1!==H?-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:f||n!==H?-1:0,onClick:()=>{T(t),U({answer:{kind:"number",value:t},animationPromise:R()})},disabled:L,role:"radio","aria-checked":S==t},t)))),Y);break;case h.STARS:Q=e.createElement("div",{className:"userflowjs-bubble-question__stars-wrapper"},Z,e.createElement("div",{className:"userflowjs-bubble-question__stars",role:"radiogroup",tabIndex:f||-1!==H?-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!=C&&C>=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:f||n!==H?-1:0,onClick:()=>{T(t),U({answer:{kind:"number",value:t},animationPromise:R()})},onMouseOver:()=>A(t),onMouseLeave:()=>A(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(g,null)),e.createElement("div",{className:"userflowjs-bubble-question__star-value","aria-hidden":"true"},t))))),Y);break;case h.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=>k(e.target.value),onKeyDown:e=>{e.shiftKey||"Enter"!==e.key||U({answer:{kind:"text",value:y}})},placeholder:w("question.placeholder"),readOnly:f||L,tabIndex:f?-1:void 0,"aria-required":n?"true":void 0,"aria-invalid":null!=M?"true":void 0}),V)}return e.createElement("div",{className:"userflowjs-bubble-question",style:{pointerEvents:f?"none":void 0}},M&&!(t===h.MULTIPLE_CHOICE&&i)&&e.createElement("div",{className:"userflowjs-bubble-question__error",role:"alert"},M),Q)};function R(){return new Promise((e=>window.setTimeout(e,250)))}const F=({question:t})=>{const n=N(),r=function(){const e=T();if("flow"!==e.kind)throw new Error("useFlowSession: Wrong session kind");return e}();return e.createElement(M,{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=>{w("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]})}))}L(n,r,t.actions)}})},O=({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 U(e=""){return{type:"paragraph",children:[{text:e}]}}function W(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:[U(e)]}}()}function B(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(ue(e))e.text&&n.push(e.text);else switch(e.type){case"attribute":{const r=ae(e,t);r&&n.push(r);break}default:r(e.children)}}(e)))}return r(e.children),n.join("")}function D(e){let t=!0;if(!e)return!0;"string"==typeof e&&(e=W(e));const n=new Set(["attribute","button","image","question","video"]);return ce(e,(e=>{ue(e)?""!==e.text&&(t=!1):"type"in e&&n.has(e.type)&&(t=!1)})),t}const V=e.memo((({doc:t,...n})=>t?("string"==typeof t&&(t=W(t)),e.createElement(z,{parent:t,...n})):null)),z=({parent:t,...n})=>e.createElement(e.Fragment,null,t.children.map(((r,l)=>ue(r)?e.createElement(K,{key:l,node:r}):e.createElement(G,{key:l,node:r,parent:t,...n})))),K=({node:t})=>t.text?e.createElement(J,{node:t},e.createElement(O,{text:t.text})):null,J=({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),G=({node:t,parent:n,...r})=>{const{lookupAttribute:l}=r,o=e.createElement(z,{parent:t,...r});switch(t.type){case"attribute":return e.createElement(H,{node:t,...r});case"button":return e.createElement(X,{node:t,...r});case"button-group":return e.createElement("div",{className:"userflowjs-bubble-buttons"},o);case"column":return e.createElement("div",{style:le(t,n)},o);case"column-group":return e.createElement("div",{className:"p-like",style:re(t)},o);case"container":return e.createElement("div",{className:"p-like"+(t.className?` ${t.className}`:""),style:oe(t)},o);case"image":return e.createElement(Z,{node:t,...r});case"link":return e.createElement("a",{href:B(t.href,{lookupAttribute:l}),target:"same"===t.target?"_top":"_blank",rel:"noopener noreferrer"},o);case"paragraph":return e.createElement("p",{className:te(t)},o);case"heading1":return e.createElement("h1",{className:te(t)},o);case"heading2":return e.createElement("h2",{className:te(t)},o);case"question":return e.createElement(Q,{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(Y,{node:t,...r});default:return e.createElement("div",null,o)}},H=({node:t,lookupAttribute:n})=>{let r=ae(t,n);return e.createElement(J,{node:t},r)},X=({node:t,buttons:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement($,{key:r.id,button:r}):null},Q=({node:t,questions:n})=>{const r=n?.find((e=>e.cvid===t.cvid));return r?e.createElement(F,{key:r.id,question:r}):null},Z=({node:t,lookupAttribute:n})=>{const{src:r,widthMode:o,displayWidth:a,width:i,height:s,marginTop:u,marginRight:c,marginBottom:d,marginLeft:m,align:b,hasLink:p,href:f}=t;if("string"!=typeof r||!r)return null;const{wrapperStyle:h,blockStyle:w}=ne({widthMode:o,displayWidth:a,width:i,height:s,marginTop:u,marginRight:c,marginBottom:d,marginLeft:m,align:b});let g=e.createElement("img",{src:l(r,(e=>encodeURIComponent(n(e)||""))),style:{...w,objectFit:"contain"}});return p&&f&&(g=e.createElement("a",{href:B(f,{lookupAttribute:n}),target:"same"===t.target?"_top":"_blank",rel:"noopener noreferrer",style:w},g)),e.createElement("div",{className:"p-like"},e.createElement("div",{style:h},g))},Y=({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}=ne({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(ee,{element:t,noFocus:!0,lookupAttribute:n}))))},ee=({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 te(e){return"right"===e.align?"userflowjs-text-align-end":"center"===e.align?"userflowjs-text-align-center":""}function ne({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 re(e){return{display:"flex",alignItems:"stretch",marginRight:`-${null==e.spacing?16:e.spacing}px`}}function le(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 oe(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 ae(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 ie(e){return Array.isArray(e.children)&&void 0===e.addMark}function se(e,t,n="type"){return ie(e)&&e[n]===t}function ue(e){return"string"==typeof e.text}function ce(e,t){function n(e){e&&e.forEach(((e,r)=>e&&function(e,r){t(e,r),ie(e)&&n(e.children)}(e,r)))}n(Array.isArray(e)?e:e.children)}const de=e.memo((({doc:t,lookupAttribute:n})=>t?e.createElement(e.Fragment,null,B(t,{lookupAttribute:n})):null));function me(e,{buttons:t,questions:n}){const r=new Set,l=new Set;if(ce(e,(e=>{se(e,"button")&&r.add(e.cvid),se(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 be(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 pe=new URL("flow-host.css",import.meta.url).href,fe=new URL("bubble-frame.css",import.meta.url).href;const he=({draftMode:t,muted:n,toggleMuted:r,close:l,minimize:o})=>{const{t:a}=q();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(E,null):e.createElement(y,null)),o&&e.createElement("button",{"data-testid":"minimize-button",className:"userflowjs-bubble-toolbar-button",onClick:o,"aria-label":"Minimize checklist"},e.createElement(k,null)),l&&e.createElement("button",{"data-testid":"close-button",className:"userflowjs-bubble-toolbar-button",onClick:l,"aria-label":a("menu.close")},e.createElement(_,null)))};export{he as B,V as R,S,de as a,fe as b,A as c,W as d,T as e,pe as f,ae as g,L as h,ue as i,me as m,I as n,D as r,B as s,C as u};
@@ -551,13 +551,20 @@ input[type="radio"]:checked:after {
551
551
  .progress-spinner--indeterminate {
552
552
  animation: progress-spinner-indeterminate-spin 1000ms linear infinite;
553
553
  }
554
- .progress-spinner-centerer {
554
+ .progress-spinner-center-aligner {
555
555
  width: 100%;
556
556
  height: 100%;
557
557
  display: flex;
558
558
  align-items: center;
559
559
  justify-content: center;
560
560
  }
561
+ .progress-spinner-right-aligner {
562
+ width: 100%;
563
+ height: 100%;
564
+ display: flex;
565
+ align-items: center;
566
+ justify-content: flex-end;
567
+ }
561
568
  @-moz-keyframes progress-spinner-indeterminate-spin {
562
569
  0% {
563
570
  transform: rotate(0deg);
package/hash.txt CHANGED
@@ -1 +1 @@
1
- 16de63f302bfbb71a9706196cd52d2207f1e351d
1
+ 8f8f80c45c3e207253e92e856f28eebc9fcd50b4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "userflow.js-self-hosted",
3
- "version": "0.1.1003270",
3
+ "version": "0.1.1003308",
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,s){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t,this.humanMessage=s}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}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,E;function f(e,t,{toOrigin:s}={}){e.postMessage(t,s||"*")}function T(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",(E=u||(u={})).AUTO="AUTO",E.MANUAL="MANUAL";const w=new Set;let S=!1;function g(e){return function(){if(S)return;S=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),I()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{I()}))}(),w.add(e),()=>{p(e)}}function p(e){w.delete(e)}function I(){w.forEach((e=>e()))}class C{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){f(window.opener,e,{toOrigin:"https://userflow.com"})}onBuilderMessage(e){return this.unregisterOnMessage=T(e,{fromOrigin:"https://userflow.com"}),!1}async captureScreenshot(e,t,s,i){f(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=>{T((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,A,U,L,R,y,O,v,N,_,b,D,F,M,B,P,x,H,G,W,$,V,j,K,z,Y,J,X,Z,Q,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,Ee,fe,Te,we,Se,ge,pe,Ie,Ce,me,ke,Ae,Ue,Le,Re,ye,Oe,ve,Ne,_e,be,De,Fe,Me,Be,Pe,xe,He,Ge,We,$e;(k=m||(m={})).ACTION="ACTION",k.LAUNCHER_DEACTIVATED="LAUNCHER_DEACTIVATED",k.REPLACED="REPLACED",k.SNOOZED="SNOOZED",k.TOOLTIP_TARGET_MISSING="TOOLTIP_TARGET_MISSING",k.USERFLOWJS="USERFLOWJS",k.USER_CLOSED="USER_CLOSED",(U=A||(A={})).SECOND="SECOND",U.MINUTE="MINUTE",U.HOUR="HOUR",U.DAY="DAY",(R=L||(L={})).ACTION="ACTION",R.DRAFT="DRAFT",R.LINK="LINK",R.LAUNCHER_SEEN="LAUNCHER_SEEN",R.RESOURCE_CENTER="RESOURCE_CENTER",R.USERFLOWJS="USERFLOWJS",(O=y||(y={})).LIKE="LIKE",O.DISLIKE="DISLIKE",(N=v||(v={})).STRING="STRING",N.BOOLEAN="BOOLEAN",N.NUMBER="NUMBER",N.DATETIME="DATETIME",N.LIST="LIST",N.RANDOM_AB="RANDOM_AB",N.RANDOM_NUMBER="RANDOM_NUMBER",(b=_||(_={})).FLOW="FLOW",b.CHECKLIST="CHECKLIST",b.LAUNCHER="LAUNCHER",b.RESOURCE_CENTER="RESOURCE_CENTER",(F=D||(D={})).ALWAYS_TRUE="ALWAYS_TRUE",F.ATTRIBUTE="ATTRIBUTE",F.CLAUSE="CLAUSE",F.ELEMENT="ELEMENT",F.FILLED_IN_INPUT="FILLED_IN_INPUT",F.FLOW="FLOW",F.INPUT_VALUE="INPUT_VALUE",F.PAGE="PAGE",F.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(M||(M={})),(B||(B={})).INPUT="INPUT",(x=P||(P={})).ABSOLUTE_EQ="ABSOLUTE_EQ",x.ABSOLUTE_GT="ABSOLUTE_GT",x.ABSOLUTE_LT="ABSOLUTE_LT",x.AND="AND",x.BETWEEN="BETWEEN",x.CONTAINS="CONTAINS",x.EMPTY="EMPTY",x.ENDS_WITH="ENDS_WITH",x.EQ="EQ",x.EXCLUDES_ALL="EXCLUDES_ALL",x.EXCLUDES_ANY="EXCLUDES_ANY",x.FALSE="FALSE",x.GT="GT",x.GTE="GTE",x.INCLUDES_ALL="INCLUDES_ALL",x.INCLUDES_ANY="INCLUDES_ANY",x.LT="LT",x.LTE="LTE",x.NE="NE",x.NOT_CONTAINS="NOT_CONTAINS",x.NOT_EMPTY="NOT_EMPTY",x.NOT_REGEX="NOT_REGEX",x.OR="OR",x.REGEX="REGEX",x.RELATIVE_EQ="RELATIVE_EQ",x.RELATIVE_GT="RELATIVE_GT",x.RELATIVE_LT="RELATIVE_LT",x.STARTS_WITH="STARTS_WITH",x.TRUE="TRUE",x.URL="URL",(G=H||(H={})).CLICK="CLICK",G.DISABLED="DISABLED",G.MOUSEDOWN="MOUSEDOWN",G.NOT_CLICK="NOT_CLICK",G.NOT_DISABLED="NOT_DISABLED",G.NOT_PRESENT="NOT_PRESENT",G.PRESENT="PRESENT",($=W||(W={})).ASSET="ASSET",$.CARTOON="CARTOON",$.NONE="NONE",$.URL="URL",(j=V||(V={})).INSIDE="INSIDE",j.OUTSIDE="OUTSIDE",(z=K||(K={})).TOP_LEFT="TOP_LEFT",z.TOP_CENTER="TOP_CENTER",z.TOP_RIGHT="TOP_RIGHT",z.BOTTOM_RIGHT="BOTTOM_RIGHT",z.BOTTOM_CENTER="BOTTOM_CENTER",z.BOTTOM_LEFT="BOTTOM_LEFT",z.CENTER="CENTER",(J=Y||(Y={})).GOOGLE="GOOGLE",J.STANDARD="STANDARD",(Z=X||(X={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",Z.DISMISS="DISMISS",(q=Q||(Q={})).DISMISS="DISMISS",q.NONE="NONE",(te=ee||(ee={})).DEFAULT="DEFAULT",te.PLAINTEXT="PLAINTEXT",(ie=se||(se={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",ie.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",ie.NONE="NONE",(oe=ne||(ne={})).BUBBLE="BUBBLE",oe.END="END",oe.ERROR="ERROR",oe.FLAG="FLAG",(ae=re||(re={})).MANUAL="MANUAL",ae.NONE="NONE",ae.SYNTHETIC="SYNTHETIC",(le=ce||(ce={})).BUBBLE="BUBBLE",le.HIDDEN="HIDDEN",le.MODAL="MODAL",le.TOOLTIP="TOOLTIP",(he=de||(de={})).ABOVE="ABOVE",he.BELOW="BELOW",he.LEFT="LEFT",he.RIGHT="RIGHT",(Ee=ue||(ue={})).CLOSE_FLOW="CLOSE_FLOW",Ee.EVAL_JS="EVAL_JS",Ee.GO_TO_STEP="GO_TO_STEP",Ee.NAVIGATE="NAVIGATE",Ee.SET_ATTRIBUTE="SET_ATTRIBUTE",Ee.SNOOZE="SNOOZE",Ee.START_FLOW="START_FLOW",(Te=fe||(fe={})).NEW_TAB="NEW_TAB",Te.SAME_TAB="SAME_TAB",(Se=we||(we={})).SET="SET",Se.SET_ONCE="SET_ONCE",Se.ADD="ADD",Se.SUBTRACT="SUBTRACT",Se.UNSET="UNSET",(pe=ge||(ge={})).MULTILINE_TEXT="MULTILINE_TEXT",pe.MULTIPLE_CHOICE="MULTIPLE_CHOICE",pe.NPS="NPS",pe.SCALE="SCALE",pe.STARS="STARS",pe.TEXT="TEXT",(Ce=Ie||(Ie={})).ACTION="ACTION",Ce.ASSISTANT="ASSISTANT",Ce.CHECKLIST="CHECKLIST",Ce.CONTACT="CONTACT",Ce.FLOWS="FLOWS",Ce.KNOWLEDGE_BASE="KNOWLEDGE_BASE",Ce.MESSAGE="MESSAGE",Ce.SUBPAGE="SUBPAGE",(ke=me||(me={})).CRISP="CRISP",ke.CUSTOM="CUSTOM",ke.FRESHCHAT="FRESHCHAT",ke.HELPSCOUT="HELPSCOUT",ke.HUBSPOT="HUBSPOT",ke.INTERCOM="INTERCOM",ke.ZENDESK="ZENDESK",ke.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ue=Ae||(Ae={})).BUTTON="BUTTON",Ue.INPUT="INPUT",(Re=Le||(Le={})).LAUNCHER_CLICK="LAUNCHER_CLICK",Re.LAUNCHER_HOVER="LAUNCHER_HOVER",Re.TARGET_CLICK="TARGET_CLICK",Re.TARGET_HOVER="TARGET_HOVER",Re.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",Re.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(Oe=ye||(ye={})).ACTIVATE="ACTIVATE",Oe.DEACTIVATE="DEACTIVATE",Oe.NEVER="NEVER",(Ne=ve||(ve={})).AUTO="AUTO",Ne.TOP="TOP",Ne.RIGHT="RIGHT",Ne.BOTTOM="BOTTOM",Ne.LEFT="LEFT",(be=_e||(_e={})).START="START",be.CENTER="CENTER",be.END="END",(Fe=De||(De={})).PERCENT="PERCENT",Fe.PX="PX",(Be=Me||(Me={})).BEACON="BEACON",Be.BUTTON="BUTTON",Be.HIDDEN="HIDDEN",Be.ICON="ICON",(xe=Pe||(Pe={})).LAUNCHER="LAUNCHER",xe.TARGET="TARGET",(Ge=He||(He={})).ACTIVE="ACTIVE",Ge.COMPLETED="COMPLETED",Ge.ENDED="ENDED",Ge.NOT_SEEN="NOT_SEEN",($e=We||(We={})).HIGHLIGHT="HIGHLIGHT",$e.MODAL="MODAL",$e.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Ve={customInputs:[],customNavigate:null,urlFilter:null,customScrollIntoView:null,scrollPadding:null,inferenceAttributeNames:["data-for","data-id","data-testid","data-test-id","for","id","name","placeholder","role"],inferenceAttributeFilters:{id:[e=>!e.match(/\d$/)],"data-id":[e=>!e.match(/\d$/)]},inferenceClassNameFilters:[e=>!e.startsWith("css-")],baseZIndex:1234500};function je(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function Ke(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function ze(){let e=d();if(Ve.urlFilter){if(e=Ve.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 Ye=(localStorage.getItem("debug")||"").split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),Je=Ze("log");let Xe;function Ze(e){return function(t,...s){if(Ye){const i=performance.now(),n=Xe?Math.round(i-Xe):0;Xe=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#1a57e6;","","color:#1a57e6;",...s)}}}Je.group=Ze("group"),Je.groupCollapsed=Ze("groupCollapsed"),Je.groupEnd=function(){Ye&&console.groupEnd()};const Qe=()=>n((()=>import("./ResourceCenterApp.js").then((function(e){return e.R}))),[new URL("ResourceCenterApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("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()]);function qe(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class et{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 tt=["page:before-change","page:change","turbo:before-cache","turbo:load","turbo:visit","turbolinks:before-cache","turbolinks:load","turbolinks:visit"],st=import.meta.url;class it{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.refCounter=1,this.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{Je(`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(),this.remountIfNecessary=()=>{this.ui?.container&&!document.contains(this.ui.container)&&(Je("remounting UI because container was missing"),this.remount())},Je("constructor, build=1003270"),g(this.onUrlChange),this.setTargetEnv(new C),this.checkTestUserAtBoot(),this.toggleUI();for(const e of tt)document.addEventListener(e,this.remountIfNecessary)}get socketStatus(){return this._socketStatus}destroy(){Je("destroy"),this.reset(),p(this.onUrlChange),this.destroyTargetEnv();for(const e of tt)document.removeEventListener(e,this.remountIfNecessary)}setTargetEnv(e){this.destroyTargetEnv(),this.targetEnv=e,e.onBuilderMessage(this.onBuilderMessage)}destroyTargetEnv(){this.targetEnv&&(this.targetEnv.destroy(),this.targetEnv=null)}getTargetEnv(){if(!this.targetEnv)throw new o("Userflow.js: Cannot call getTargetEnv when protocol is not set");return this.targetEnv}setSessionStorageState(e){const t=e(this.getSessionStorageState());c.setItem("userflowClientState",JSON.stringify(t)),this.sessionStorageState=t,this.toggleUI()}getSessionStorageState(){let e=this.sessionStorageState;if(!e){const 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&&(Je("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(Je("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?Je("init() ignoring new token since a test user has been identified"):(this.clientToken&&(Je("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",Je("connecting to socket");let t="e.userflow.com";"js.getuserflow.com"===new URL(st).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((()=>{Je("socket opened")})),this.socket.onClose((()=>{this.emit("private:disconnect")})),this.socket.onError((e=>{console.log("Userflow.js socket error",e),this.reportCspIssue()})),this.channel=this.socket.channel(`end_users:${this.externalId}`,(()=>this.makeChannelJoinPayload())),this.channel.join().receive("ok",(e=>{this.logrocketAppId=e.logrocketAppId,this.featureFlags=new Set(e.featureFlags),Je("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:"1003270",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 Je("channel join payload",t),t}disconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.socket&&this.socket.disconnect(),this._socketStatus="disconnected",this.socket=null,this.channel=null}debounceInactiveDisconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.debounceInactiveDisconnectTimeout=window.setTimeout((()=>{this.hasDraftSession()||this.assistantMessageInProgress?this.debounceInactiveDisconnect():(Je("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,endBatch:s,handlesRejection:i}={}){return this.inBatch&&["ToggleClientCondition","UpdateClientContext"].includes(e.kind)||this.checkPushRateLimit(),this.ensureConnected(),t&&!this.inBatch&&(this.inBatch=!0,this.sendRaw({kind:"BeginBatch"})),this.inBatch&&(window.clearTimeout(this.endBatchTimeout),s?this.endBatch():this.endBatchTimeout=window.setTimeout((()=>{this.endBatch()}),50)),this.sendRaw(e,{handlesRejection:i})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel){const s=`Userflow.js: send() should not be called if channel is not set. Message kind=${e.kind}`;if(t)throw Error(s);return void console.log(s,"\nClient message:",e)}Je(`push ${e.kind} message`,e);const n=this.clientClock,r=()=>{this.serverClock=n,this.channel?.off("phx_error",a)},a=this.channel.on("phx_error",(s=>{r();const n=`Userflow.js send ${e.kind} got phx_error`;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,t.message))}))}))}endBatch(){this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}checkPushRateLimit(){const e=Date.now();if(this.pushRateLimitMinuteExpires<e&&(this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=e+6e4),this.pushRateLimitMinute>=100)throw new o("This Userflow.js client has reached a maximum of 100 operations in the last 1 minute. This is usually due to one of the following:\n\n - Excessive calls to Userflow.js. Check if any of userflow.track(), userflow.identify(), userflow.updateUser() or similar are called repeatedly.\n - The URL changing too frequently. Look into https://userflow.com/docs/userflow-js#seturlfilter and filter out the changing part of the URL.\n - The user legitimately being very active, in which case you can just ignore this error.\n \n If in doubt, reach out to us at support@userflow.com.");this.pushRateLimitMinute++}handleServerMessage(e){Je(`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"AssistantMessageEventWrapper":return void this.emit("private:assistantMessageEvent",e);case"CancelConditionWaitTimer":return window.clearTimeout(this.conditionWaitTimers.get(e.conditionId)),void this.conditionWaitTimers.delete(e.conditionId);case"ChecklistTaskCompleted":return void this.unackedTasks.add(e.taskCvid);case"ForceGoToStep":return i>t?void Je(`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()):Je(`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()):Je(`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 Je(`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 Je(`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(Je("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)Je("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&&(Je("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={}){Je("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if(Je("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)Je("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={}){Je("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 v.STRING;case"number":return v.NUMBER;case"boolean":return v.BOOLEAN;case"datetime":return v.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=v.STRING;break;case"boolean":n=v.BOOLEAN;break;case"integer":case"decimal":n=v.NUMBER;break;case"datetime":n=v.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}={}){Je(`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&&(Je(`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:ze(),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(){Je("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}),Je(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return Je("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(),Je("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?qe(t):0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Ie.CHECKLIST))}async endFlow(e,{endReason:t,batch:s}){this.ensureIdentified(),this.optimisticClockUIUpdate((()=>{const{clientClock:t}=this;this.flowSession?.id===e.id&&this.setFlowSession(null,t),this.checklistSession?.id===e.id&&this.setChecklistSession(null,t),this.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===_.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===_.FLOW&&this.emit("flowEnded",{flow:n,endReason:t});const o={kind:"EndFlow",sessionId:e.id,endReason:t};await this.send(o,{batch:s})}async goToStep(e,t){Je("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(){Je("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){Je("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===_.CHECKLIST&&this.endFlow(e,{endReason:m.USERFLOWJS})}setFlowSession(e,t=this.clientClock){const s=this.flowSession;this.flowSession=e,this.flowSessionClock=t,e&&!s&&(this.hideChecklist(),this.closeResourceCenter()),null==e&&this.originalActiveElement&&("function"==typeof this.originalActiveElement.focus&&this.originalActiveElement.focus(),this.originalActiveElement=void 0)}setChecklistSession(e,t=this.clientClock){const s=this.checklistSession;this.checklistSession=e,this.checklistSessionClock=t,null===e&&(this.checklistExpanded=!1,this.checklistExpandPending=!1),e&&e.id!==s?.id&&(this.checklistExpanded=!!c.getItem(`checklistExpanded:${e.id}`),e.expandPending&&(this.checklistExpandPending=!0)),this.emit("checklistChanged"),this.emit("resourceCenterChanged")}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===ye.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&&(Je("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&(Je("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&&Qe();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;Je("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 et([]),condition:e,callback:t=>{i.isTrue!==t&&(Je("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&&(Je("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 et(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,Je("csp issue detected"),f(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)}nextRef(){return this.refCounter++}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new it;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&&Ve.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Ve.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Ve.customNavigate=e},setUrlFilter(e){Ve.urlFilter=e},setInferenceAttributeNames(e){Ve.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Ve.inferenceAttributeFilters[e]=je(t)},setInferenceClassNameFilter(e){Ve.inferenceClassNameFilters=je(e)},setScrollPadding(e){Ve.scrollPadding=e},setCustomScrollIntoView(e){Ve.customScrollIntoView=e},prepareAudio(){e.playAudio(null)},setShadowDomEnabled(e){console.warn("Userflow.js: userflow.setShadowDomEnabled() has been deprecated. Please remove this call from your Userflow.js snippet. Shadow DOM is supported by default now.")},setPageTrackingDisabled(t){e.pageTrackingDisabled=t},setBaseZIndex(e){Ve.baseZIndex=e},_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;Je(`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)}Je("queue processed")}()}export{W as A,V as B,me as C,X as D,m as E,P as F,ne as G,ce as H,K as I,de as J,Le as K,Me as L,Q as M,ve as N,Pe as O,_e as P,De as Q,Qe as R,L as S,tt as T,o as U,re as V,y as W,n as _,B as a,M as b,Ve as c,Je as d,D as e,H as f,ze as g,Ie as h,c as i,qe as j,se as k,ee as l,ue as m,Ae as n,g as o,_ as p,d as q,fe as r,l as s,Ke as t,p as u,we as v,ge as w,et as x,Y as y,a as z};export default window.userflow;
1
+ import{S as e}from"./vendor.phoenix.js";import{v as t}from"./vendor.uuid.js";let s;const i={},n=function(e,t){if(!t)return e();if(void 0===s){const e=document.createElement("link").relList;s=e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}return Promise.all(t.map((e=>{if(e in i)return;i[e]=!0;const t=e.endsWith(".css"),n=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${n}`))return;const o=document.createElement("link");return o.rel=t?"stylesheet":s,t||(o.as="script",o.crossOrigin=""),o.href=e,document.head.appendChild(o),t?new Promise(((e,t)=>{o.addEventListener("load",e),o.addEventListener("error",t)})):void 0}))).then((()=>e()))};class o extends Error{constructor(e,t,s){super(e),Object.setPrototypeOf(this,o.prototype),this.name="UserflowError",this.code=t,this.humanMessage=s}}class r{constructor(e){this.type=e,this.testState={}}formatKey(e){return`userflow:${e}`}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,E;function f(e,t,{toOrigin:s}={}){e.postMessage(t,s||"*")}function T(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",(E=u||(u={})).AUTO="AUTO",E.MANUAL="MANUAL";const w=new Set;let S=!1;function g(e){return function(){if(S)return;S=!0;const{history:e}=window,t=t=>{const s=e[t];e[t]=(...t)=>{s.apply(e,t),I()}};t("pushState"),t("replaceState"),window.addEventListener("popstate",(()=>{I()}))}(),w.add(e),()=>{p(e)}}function p(e){w.delete(e)}function I(){w.forEach((e=>e()))}class C{destroy(){this.unregisterOnMessage&&this.unregisterOnMessage()}postBuilderMessage(e){f(window.opener,e,{toOrigin:"https://userflow.com"})}onBuilderMessage(e){return this.unregisterOnMessage=T(e,{fromOrigin:"https://userflow.com"}),!1}async captureScreenshot(e,t,s,i){f(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=>{T((t=>{const s=n(t);return!!s&&(e(s),!0)}))})))).imageDataUrl}}var m,k,A,U,L,R,y,O,v,N,_,b,D,F,M,B,P,x,H,G,W,$,V,j,K,z,Y,J,X,Z,Q,q,ee,te,se,ie,ne,oe,re,ae,ce,le,de,he,ue,Ee,fe,Te,we,Se,ge,pe,Ie,Ce,me,ke,Ae,Ue,Le,Re,ye,Oe,ve,Ne,_e,be,De,Fe,Me,Be,Pe,xe,He,Ge,We,$e;(k=m||(m={})).ACTION="ACTION",k.LAUNCHER_DEACTIVATED="LAUNCHER_DEACTIVATED",k.REPLACED="REPLACED",k.SNOOZED="SNOOZED",k.TOOLTIP_TARGET_MISSING="TOOLTIP_TARGET_MISSING",k.USERFLOWJS="USERFLOWJS",k.USER_CLOSED="USER_CLOSED",(U=A||(A={})).SECOND="SECOND",U.MINUTE="MINUTE",U.HOUR="HOUR",U.DAY="DAY",(R=L||(L={})).ACTION="ACTION",R.DRAFT="DRAFT",R.LINK="LINK",R.LAUNCHER_SEEN="LAUNCHER_SEEN",R.RESOURCE_CENTER="RESOURCE_CENTER",R.USERFLOWJS="USERFLOWJS",(O=y||(y={})).LIKE="LIKE",O.DISLIKE="DISLIKE",(N=v||(v={})).STRING="STRING",N.BOOLEAN="BOOLEAN",N.NUMBER="NUMBER",N.DATETIME="DATETIME",N.LIST="LIST",N.RANDOM_AB="RANDOM_AB",N.RANDOM_NUMBER="RANDOM_NUMBER",(b=_||(_={})).FLOW="FLOW",b.CHECKLIST="CHECKLIST",b.LAUNCHER="LAUNCHER",b.RESOURCE_CENTER="RESOURCE_CENTER",(F=D||(D={})).ALWAYS_TRUE="ALWAYS_TRUE",F.ATTRIBUTE="ATTRIBUTE",F.CLAUSE="CLAUSE",F.ELEMENT="ELEMENT",F.FILLED_IN_INPUT="FILLED_IN_INPUT",F.FLOW="FLOW",F.INPUT_VALUE="INPUT_VALUE",F.PAGE="PAGE",F.TIME="TIME",function(e){e.AUTO="AUTO",e.MANUAL="MANUAL"}(M||(M={})),(B||(B={})).INPUT="INPUT",(x=P||(P={})).ABSOLUTE_EQ="ABSOLUTE_EQ",x.ABSOLUTE_GT="ABSOLUTE_GT",x.ABSOLUTE_LT="ABSOLUTE_LT",x.AND="AND",x.BETWEEN="BETWEEN",x.CONTAINS="CONTAINS",x.EMPTY="EMPTY",x.ENDS_WITH="ENDS_WITH",x.EQ="EQ",x.EXCLUDES_ALL="EXCLUDES_ALL",x.EXCLUDES_ANY="EXCLUDES_ANY",x.FALSE="FALSE",x.GT="GT",x.GTE="GTE",x.INCLUDES_ALL="INCLUDES_ALL",x.INCLUDES_ANY="INCLUDES_ANY",x.LT="LT",x.LTE="LTE",x.NE="NE",x.NOT_CONTAINS="NOT_CONTAINS",x.NOT_EMPTY="NOT_EMPTY",x.NOT_REGEX="NOT_REGEX",x.OR="OR",x.REGEX="REGEX",x.RELATIVE_EQ="RELATIVE_EQ",x.RELATIVE_GT="RELATIVE_GT",x.RELATIVE_LT="RELATIVE_LT",x.STARTS_WITH="STARTS_WITH",x.TRUE="TRUE",x.URL="URL",(G=H||(H={})).CLICK="CLICK",G.DISABLED="DISABLED",G.MOUSEDOWN="MOUSEDOWN",G.NOT_CLICK="NOT_CLICK",G.NOT_DISABLED="NOT_DISABLED",G.NOT_PRESENT="NOT_PRESENT",G.PRESENT="PRESENT",($=W||(W={})).ASSET="ASSET",$.CARTOON="CARTOON",$.NONE="NONE",$.URL="URL",(j=V||(V={})).INSIDE="INSIDE",j.OUTSIDE="OUTSIDE",(z=K||(K={})).TOP_LEFT="TOP_LEFT",z.TOP_CENTER="TOP_CENTER",z.TOP_RIGHT="TOP_RIGHT",z.BOTTOM_RIGHT="BOTTOM_RIGHT",z.BOTTOM_CENTER="BOTTOM_CENTER",z.BOTTOM_LEFT="BOTTOM_LEFT",z.CENTER="CENTER",(J=Y||(Y={})).GOOGLE="GOOGLE",J.STANDARD="STANDARD",(Z=X||(X={})).DISMISS_FIRST_MENU_AFTER="DISMISS_FIRST_MENU_AFTER",Z.DISMISS="DISMISS",(q=Q||(Q={})).DISMISS="DISMISS",q.NONE="NONE",(te=ee||(ee={})).DEFAULT="DEFAULT",te.PLAINTEXT="PLAINTEXT",(ie=se||(se={})).CHECKLIST_OVERRIDE="CHECKLIST_OVERRIDE",ie.RESOURCE_CENTER_ONLY="RESOURCE_CENTER_ONLY",ie.NONE="NONE",(oe=ne||(ne={})).BUBBLE="BUBBLE",oe.END="END",oe.ERROR="ERROR",oe.FLAG="FLAG",(ae=re||(re={})).MANUAL="MANUAL",ae.NONE="NONE",ae.SYNTHETIC="SYNTHETIC",(le=ce||(ce={})).BUBBLE="BUBBLE",le.HIDDEN="HIDDEN",le.MODAL="MODAL",le.TOOLTIP="TOOLTIP",(he=de||(de={})).ABOVE="ABOVE",he.BELOW="BELOW",he.LEFT="LEFT",he.RIGHT="RIGHT",(Ee=ue||(ue={})).CLOSE_FLOW="CLOSE_FLOW",Ee.EVAL_JS="EVAL_JS",Ee.GO_TO_STEP="GO_TO_STEP",Ee.NAVIGATE="NAVIGATE",Ee.SET_ATTRIBUTE="SET_ATTRIBUTE",Ee.SNOOZE="SNOOZE",Ee.START_FLOW="START_FLOW",(Te=fe||(fe={})).NEW_TAB="NEW_TAB",Te.SAME_TAB="SAME_TAB",(Se=we||(we={})).SET="SET",Se.SET_ONCE="SET_ONCE",Se.ADD="ADD",Se.SUBTRACT="SUBTRACT",Se.UNSET="UNSET",(pe=ge||(ge={})).MULTILINE_TEXT="MULTILINE_TEXT",pe.MULTIPLE_CHOICE="MULTIPLE_CHOICE",pe.NPS="NPS",pe.SCALE="SCALE",pe.STARS="STARS",pe.TEXT="TEXT",(Ce=Ie||(Ie={})).ACTION="ACTION",Ce.ASSISTANT="ASSISTANT",Ce.CHECKLIST="CHECKLIST",Ce.CONTACT="CONTACT",Ce.FLOWS="FLOWS",Ce.KNOWLEDGE_BASE="KNOWLEDGE_BASE",Ce.MESSAGE="MESSAGE",Ce.SUBPAGE="SUBPAGE",(ke=me||(me={})).CRISP="CRISP",ke.CUSTOM="CUSTOM",ke.FRESHCHAT="FRESHCHAT",ke.HELPSCOUT="HELPSCOUT",ke.HUBSPOT="HUBSPOT",ke.INTERCOM="INTERCOM",ke.ZENDESK="ZENDESK",ke.ZENDESK_MESSENGER="ZENDESK_MESSENGER",(Ue=Ae||(Ae={})).BUTTON="BUTTON",Ue.INPUT="INPUT",(Re=Le||(Le={})).LAUNCHER_CLICK="LAUNCHER_CLICK",Re.LAUNCHER_HOVER="LAUNCHER_HOVER",Re.TARGET_CLICK="TARGET_CLICK",Re.TARGET_HOVER="TARGET_HOVER",Re.LAUNCHER_TARGET_CLICK="LAUNCHER_TARGET_CLICK",Re.LAUNCHER_TARGET_HOVER="LAUNCHER_TARGET_HOVER",(Oe=ye||(ye={})).ACTIVATE="ACTIVATE",Oe.DEACTIVATE="DEACTIVATE",Oe.NEVER="NEVER",(Ne=ve||(ve={})).AUTO="AUTO",Ne.TOP="TOP",Ne.RIGHT="RIGHT",Ne.BOTTOM="BOTTOM",Ne.LEFT="LEFT",(be=_e||(_e={})).START="START",be.CENTER="CENTER",be.END="END",(Fe=De||(De={})).PERCENT="PERCENT",Fe.PX="PX",(Be=Me||(Me={})).BEACON="BEACON",Be.BUTTON="BUTTON",Be.HIDDEN="HIDDEN",Be.ICON="ICON",(xe=Pe||(Pe={})).LAUNCHER="LAUNCHER",xe.TARGET="TARGET",(Ge=He||(He={})).ACTIVE="ACTIVE",Ge.COMPLETED="COMPLETED",Ge.ENDED="ENDED",Ge.NOT_SEEN="NOT_SEEN",($e=We||(We={})).HIGHLIGHT="HIGHLIGHT",$e.MODAL="MODAL",$e.HIGHLIGHT_MODAL="HIGHLIGHT_MODAL";const Ve={customInputs:[],customNavigate:null,urlFilter:null,customScrollIntoView:null,scrollPadding:null,inferenceAttributeNames:["data-for","data-id","data-testid","data-test-id","for","id","name","placeholder","role"],inferenceAttributeFilters:{id:[e=>!e.match(/\d$/)],"data-id":[e=>!e.match(/\d$/)]},inferenceClassNameFilters:[e=>!e.startsWith("css-")],baseZIndex:1234500};function je(e){return Array.isArray(e)||(e=e?[e]:[]),e=e.map((e=>"string"==typeof e?new RegExp(e):e))}function Ke(e,t){return e.every((e=>"function"==typeof e?e(t):!(e instanceof RegExp)||e.test(t)))}function ze(){let e=d();if(Ve.urlFilter){if(e=Ve.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 Ye=(localStorage.getItem("debug")||"").split(",").some((e=>"*"===e||e.startsWith("userflow:*"))),Je=Ze("log");let Xe;function Ze(e){return function(t,...s){if(Ye){const i=performance.now(),n=Xe?Math.round(i-Xe):0;Xe=i,console[e](`%cuserflow %c${t} %c+${n}ms`,"color:#1a57e6;","","color:#1a57e6;",...s)}}}Je.group=Ze("group"),Je.groupCollapsed=Ze("groupCollapsed"),Je.groupEnd=function(){Ye&&console.groupEnd()};const Qe=()=>n((()=>import("./ResourceCenterApp.js").then((function(e){return e.R}))),[new URL("ResourceCenterApp.js",import.meta.url).toString(),new URL("vendor.react.js",import.meta.url).toString(),new URL("vendor.object-assign.js",import.meta.url).toString(),new URL("client-context.js",import.meta.url).toString(),new URL("vendor.i18next.js",import.meta.url).toString(),new URL("vendor.react-i18next.js",import.meta.url).toString(),new URL("vendor.babel.runtime.js",import.meta.url).toString(),new URL("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()]);function qe(e){const t=e.version.checklist.tasks.length;return Math.max(0,t-e.taskCompletions.length)}class et{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 tt=["page:before-change","page:change","turbo:before-cache","turbo:load","turbo:visit","turbolinks:before-cache","turbolinks:load","turbolinks:visit"],st=import.meta.url;class it{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.refCounter=1,this.onBuilderMessage=e=>(this.handleBuilderMessage(e),!1),this.handleBuilderMessage=async e=>{Je(`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(),this.remountIfNecessary=()=>{this.ui?.container&&!document.contains(this.ui.container)&&(Je("remounting UI because container was missing"),this.remount())},Je("constructor, build=1003308"),g(this.onUrlChange),this.setTargetEnv(new C),this.checkTestUserAtBoot(),this.toggleUI();for(const e of tt)document.addEventListener(e,this.remountIfNecessary)}get socketStatus(){return this._socketStatus}destroy(){Je("destroy"),this.reset(),p(this.onUrlChange),this.destroyTargetEnv();for(const e of tt)document.removeEventListener(e,this.remountIfNecessary)}setTargetEnv(e){this.destroyTargetEnv(),this.targetEnv=e,e.onBuilderMessage(this.onBuilderMessage)}destroyTargetEnv(){this.targetEnv&&(this.targetEnv.destroy(),this.targetEnv=null)}getTargetEnv(){if(!this.targetEnv)throw new o("Userflow.js: Cannot call getTargetEnv when protocol is not set");return this.targetEnv}setSessionStorageState(e){const t=e(this.getSessionStorageState());c.setItem("userflowClientState",JSON.stringify(t)),this.sessionStorageState=t,this.toggleUI()}getSessionStorageState(){let e=this.sessionStorageState;if(!e){const 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&&(Je("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(Je("init",e),!e)throw new o("userflow.init() was called but missing Userflow.js Token");this.clientToken!==e&&(this.testUserIdentified?Je("init() ignoring new token since a test user has been identified"):(this.clientToken&&(Je("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",Je("connecting to socket");let t="e.userflow.com";"js.getuserflow.com"===new URL(st).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((()=>{Je("socket opened")})),this.socket.onClose((()=>{this.emit("private:disconnect")})),this.socket.onError((e=>{console.log("Userflow.js socket error",e),this.reportCspIssue()})),this.channel=this.socket.channel(`end_users:${this.externalId}`,(()=>this.makeChannelJoinPayload())),this.channel.join().receive("ok",(e=>{this.logrocketAppId=e.logrocketAppId,this.featureFlags=new Set(e.featureFlags),Je("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:"1003308",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 Je("channel join payload",t),t}disconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.socket&&this.socket.disconnect(),this._socketStatus="disconnected",this.socket=null,this.channel=null}debounceInactiveDisconnect(){window.clearTimeout(this.debounceInactiveDisconnectTimeout),this.debounceInactiveDisconnectTimeout=window.setTimeout((()=>{this.hasDraftSession()||this.assistantMessageInProgress?this.debounceInactiveDisconnect():(Je("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,endBatch:s,handlesRejection:i}={}){return this.inBatch&&["ToggleClientCondition","UpdateClientContext"].includes(e.kind)||this.checkPushRateLimit(),this.ensureConnected(),t&&!this.inBatch&&(this.inBatch=!0,this.sendRaw({kind:"BeginBatch"})),this.inBatch&&(window.clearTimeout(this.endBatchTimeout),s?this.endBatch():this.endBatchTimeout=window.setTimeout((()=>{this.endBatch()}),50)),this.sendRaw(e,{handlesRejection:i})}async sendRaw(e,{handlesRejection:t}={}){return new Promise(((s,i)=>{if(!this.channel){const s=`Userflow.js: send() should not be called if channel is not set. Message kind=${e.kind}`;if(t)throw Error(s);return void console.log(s,"\nClient message:",e)}Je(`push ${e.kind} message`,e);const n=this.clientClock,r=()=>{this.serverClock=n,this.channel?.off("phx_error",a)},a=this.channel.on("phx_error",(s=>{r();const n=`Userflow.js send ${e.kind} got phx_error`;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,t.message))}))}))}endBatch(){this.inBatch=!1,this.sendRaw({kind:"EndBatch"})}checkPushRateLimit(){const e=Date.now();if(this.pushRateLimitMinuteExpires<e&&(this.pushRateLimitMinute=0,this.pushRateLimitMinuteExpires=e+6e4),this.pushRateLimitMinute>=100)throw new o("This Userflow.js client has reached a maximum of 100 operations in the last 1 minute. This is usually due to one of the following:\n\n - Excessive calls to Userflow.js. Check if any of userflow.track(), userflow.identify(), userflow.updateUser() or similar are called repeatedly.\n - The URL changing too frequently. Look into https://userflow.com/docs/userflow-js#seturlfilter and filter out the changing part of the URL.\n - The user legitimately being very active, in which case you can just ignore this error.\n \n If in doubt, reach out to us at support@userflow.com.");this.pushRateLimitMinute++}handleServerMessage(e){Je(`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"AssistantMessageEventWrapper":return void this.emit("private:assistantMessageEvent",e);case"CancelConditionWaitTimer":return window.clearTimeout(this.conditionWaitTimers.get(e.conditionId)),void this.conditionWaitTimers.delete(e.conditionId);case"ChecklistTaskCompleted":return void this.unackedTasks.add(e.taskCvid);case"ForceGoToStep":return i>t?void Je(`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()):Je(`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()):Je(`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 Je(`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 Je(`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(Je("identify",e),this.ensureInit(),this.testUserIdentified&&e!==this.externalId)Je("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&&(Je("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={}){Je("updateUser"),this.ensureIdentified(),await this.send({kind:"UpsertUser",attributes:this.normalizeAttributes(e)},{batch:!0})}async group(e,t={},{signature:s,membership:i}={}){if(Je("group",e),this.ensureIdentified(),this.testUserIdentified&&e!==this.groupId)Je("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={}){Je("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 v.STRING;case"number":return v.NUMBER;case"boolean":return v.BOOLEAN;case"datetime":return v.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=v.STRING;break;case"boolean":n=v.BOOLEAN;break;case"integer":case"decimal":n=v.NUMBER;break;case"datetime":n=v.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}={}){Je(`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&&(Je(`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:ze(),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(){Je("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}),Je(`startFlow ${e}`,{startReason:s}),this.checklistSession?.flow.id===e)return Je("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(),Je("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?qe(t):0}}resourceCenterEmbedsChecklist(){const e=this.resourceCenterSession;return!!e&&!!e.version.resourceCenter?.blocks.some((e=>e.type===Ie.CHECKLIST))}async endFlow(e,{endReason:t,batch:s}){this.ensureIdentified(),this.optimisticClockUIUpdate((()=>{const{clientClock:t}=this;this.flowSession?.id===e.id&&this.setFlowSession(null,t),this.checklistSession?.id===e.id&&this.setChecklistSession(null,t),this.resourceCenterSession?.id===e.id&&this.setResourceCenterSession(null)}));const{flow:i}=e,n={id:i.id,type:i.type.toLowerCase()};i.type===_.CHECKLIST?this.emit("checklistEnded",{checklist:n,endReason:t}):i.type===_.FLOW&&this.emit("flowEnded",{flow:n,endReason:t});const o={kind:"EndFlow",sessionId:e.id,endReason:t};await this.send(o,{batch:s})}async goToStep(e,t){Je("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(){Je("endAllFlows"),this.optimisticClockUIUpdate((()=>{const{clientClock:e}=this;this.setFlowSession(null,e),this.setChecklistSession(null,e)})),await this.send({kind:"EndAllFlows"})}async endChecklist(){Je("endChecklist");const e=this.checklistSession||this.flowSession;e?.flow.type===_.CHECKLIST&&this.endFlow(e,{endReason:m.USERFLOWJS})}setFlowSession(e,t=this.clientClock){const s=this.flowSession;this.flowSession=e,this.flowSessionClock=t,e&&!s&&(this.hideChecklist(),this.closeResourceCenter()),null==e&&this.originalActiveElement&&("function"==typeof this.originalActiveElement.focus&&this.originalActiveElement.focus(),this.originalActiveElement=void 0)}setChecklistSession(e,t=this.clientClock){const s=this.checklistSession;this.checklistSession=e,this.checklistSessionClock=t,null===e&&(this.checklistExpanded=!1,this.checklistExpandPending=!1),e&&e.id!==s?.id&&(this.checklistExpanded=!!c.getItem(`checklistExpanded:${e.id}`),e.expandPending&&(this.checklistExpandPending=!0)),this.emit("checklistChanged"),this.emit("resourceCenterChanged")}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===ye.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&&(Je("mount UI"),this.ui=e,this.ui.mount())}}unmountUI(){this.ui&&(Je("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&&Qe();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;Je("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 et([]),condition:e,callback:t=>{i.isTrue!==t&&(Je("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&&(Je("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 et(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,Je("csp issue detected"),f(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)}nextRef(){return this.refCounter++}}if(void 0===window.userflow||window.userflow._stubbed){const e=Object.assign(window.userflow||{},function(){const e=new it;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&&Ve.customInputs.push({cssSelector:e})},registerCustomInput(e,t){Ve.customInputs.push({cssSelector:e,getValue:t})},setCustomNavigate(e){Ve.customNavigate=e},setUrlFilter(e){Ve.urlFilter=e},setInferenceAttributeNames(e){Ve.inferenceAttributeNames=e},setInferenceAttributeFilter(e,t){Ve.inferenceAttributeFilters[e]=je(t)},setInferenceClassNameFilter(e){Ve.inferenceClassNameFilters=je(e)},setScrollPadding(e){Ve.scrollPadding=e},setCustomScrollIntoView(e){Ve.customScrollIntoView=e},prepareAudio(){e.playAudio(null)},setShadowDomEnabled(e){console.warn("Userflow.js: userflow.setShadowDomEnabled() has been deprecated. Please remove this call from your Userflow.js snippet. Shadow DOM is supported by default now.")},setPageTrackingDisabled(t){e.pageTrackingDisabled=t},setBaseZIndex(e){Ve.baseZIndex=e},_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;Je(`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)}Je("queue processed")}()}export{W as A,V as B,me as C,X as D,m as E,P as F,ne as G,ce as H,K as I,de as J,Le as K,Me as L,Q as M,ve as N,Pe as O,_e as P,De as Q,Qe as R,L as S,tt as T,o as U,re as V,y as W,n as _,B as a,M as b,Ve as c,Je as d,D as e,H as f,ze as g,Ie as h,c as i,qe as j,se as k,ee as l,ue as m,Ae as n,g as o,_ as p,d as q,fe as r,l as s,Ke as t,p as u,we as v,ge as w,et as x,Y as y,a as z};export default window.userflow;