UNPKG

@flows/js

Version:

Flows JS SDK - Build native product growth experiences, your way

2 lines (1 loc) 15.6 kB
import{A as J,B as Q,C as D,D as ve,E as A,F as y,G as V,a as g,b as k,c as me,h as B,i as G,l as ge,q as ke,u as ye,v as h,w,x as N,y as I,z as C}from"./chunk-FMURHS7N.mjs";var be=(e,{body:t,method:r,version:o})=>fetch(e,{method:r,headers:{"Content-Type":"application/json","x-flows-version":o},body:t?JSON.stringify(t):void 0}).then(async n=>{var i;let s=await n.text(),a=s?JSON.parse(s):void 0;if(!n.ok){let c=a;throw new Error((i=c==null?void 0:c.message)!=null?i:n.statusText)}return a}),_=(e,t)=>({getBlocks:r=>be(`${e}/v2/sdk/blocks`,{method:"POST",body:r,version:t}),sendEvent:r=>be(`${e}/v2/sdk/events`,{method:"POST",body:r,version:t})});import{set as U}from"es-toolkit/compat";import{mapValues as F}from"es-toolkit";var W=(e,t)=>{let r="",o=0;for(;o<e.length;){let n=e.indexOf("{{",o);if(n===-1){r+=e.slice(o);break}r+=e.slice(o,n);let s=e.indexOf("}}",n+2);if(s===-1){r+=e.slice(n);break}let i=e.slice(n+2,s).trim(),c=i.indexOf("|"),m=(c===-1?i:i.slice(0,c)).trim(),p=c===-1?void 0:i.slice(c+1).trim(),f=e.slice(n,s+2);if(!m){r+=f,o=s+2;continue}let u=t[m];if(typeof u=="string"||typeof u=="number"||typeof u=="boolean"){r+=u.toString(),o=s+2;continue}r+=p!=null?p:"",o=s+2}return r};var Be=({propMeta:e,userProperties:t})=>{let r=e.value,o={label:W(r.label,t),openInNew:r.openInNew};return r.url!==void 0&&(o.url=W(r.url,t)),o},X=e=>{var p,f;let{block:t,exitNodeCb:r,removeBlock:o,setStateMemory:n}=e,s=({properties:u,parentKey:l})=>{var $;let d=g({},u);return delete d.f__exit_nodes,($=u.f__exit_nodes)==null||$.forEach(x=>{let S=()=>r({key:[l,x].filter(T=>T!==void 0).join("."),blockId:t.id});d[x]=S}),Object.entries(u).forEach(([x,S])=>{Array.isArray(S)&&(d[x]=S.map((T,je)=>typeof T=="object"?s({properties:T,parentKey:[l,x,je].filter(ze=>ze!==void 0).join(".")}):T))}),d},a=s({properties:t.data}),i=({value:u,parentKey:l})=>typeof u=="string"?W(u,e.userProperties):Array.isArray(u)?u.map((d,$)=>d&&typeof d=="object"?F(d,(x,S)=>{let T=[l,$,S].join(".");return i({value:x,parentKey:T})}):d):u,c=F(a,(u,l)=>i({value:u,parentKey:l}));for(let u of(p=t.propertyMeta)!=null?p:[]){if(u.type==="state-memory"){let l={value:u.value,setValue:d=>{n({key:u.key,value:d,blockId:t.id})},triggers:(f=u.triggers)!=null?f:[]};U(c,u.key,l)}if(u.type==="block-state"){let l=X(k(g({},e),{block:u.value}));U(c,u.key,l)}if(u.type==="action"){let l=Be({propMeta:u,userProperties:e.userProperties}),d=u.value.exitNode;d&&(l.callAction=()=>(t.exitNodes.includes(d)&&o(t.id),r({key:d,blockId:t.id}))),U(c,u.key,l)}}let m=t.exitNodes.reduce((u,l)=>{let d=()=>(o(t.id),r({key:l,blockId:t.id}));return u[l]=d,u},{});return g(g({__flows:{id:t.id,key:t.key,workflowId:t.workflowId}},c),m)},we=({tourSteps:e,tourStep:t,currentIndex:r,userProperties:o,handleCancel:n,handleContinue:s,handlePrevious:a})=>{var u;let i=r===0,c=l=>typeof l=="string"?W(l,o):Array.isArray(l)?l.map(d=>d&&typeof d=="object"?F(d,c):d):l,m=F(t.data,c);for(let l of(u=t.propertyMeta)!=null?u:[])if(l.type==="action"){let d=Be({propMeta:l,userProperties:o});l.value.exitNode&&(d.callAction=async()=>{l.value.exitNode==="continue"&&s(),l.value.exitNode==="previous"&&a(),l.value.exitNode==="cancel"&&n()}),U(m,l.key,d)}let p=e.filter(l=>l.type==="tour-component"),f=p.findIndex(l=>l.id===t.id);return k(g({__flows:{id:t.id,key:t.key,workflowId:t.workflowId,tourVisibleStepCount:p.length,tourVisibleStepIndex:f}},m),{continue:s,previous:i?void 0:a,cancel:n})};var he=e=>{var t;if(!(!e||e==="disabled"))return e==="automatic"?(t=navigator.languages.at(0))!=null?t:navigator.language:e};var Y=(e,t)=>t?Array.isArray(t)?t.some(r=>Y(e,r)):typeof e!="string"?!1:new RegExp(t).test(e):!0,Z=(e,t)=>t===void 0?!0:Array.isArray(t)?t.some(r=>Z(e,r)):e===t,ee=(e,t)=>t===void 0?!0:Array.isArray(t)?t.every(r=>ee(e,r)):e!==t;var te=(e,t)=>t?Array.isArray(t)?t.some(r=>te(e,r)):typeof e!="string"?!1:e.includes(t):!0,re=(e,t)=>t?Array.isArray(t)?t.every(r=>re(e,r)):typeof e!="string"?!1:!e.includes(t):!0,oe=(e,t)=>t?Array.isArray(t)?t.some(r=>oe(e,r)):typeof e!="string"?!1:e.startsWith(t):!0,ne=(e,t)=>t?Array.isArray(t)?t.some(r=>ne(e,r)):typeof e!="string"?!1:e.endsWith(t):!0,se=(e,t)=>t?Array.isArray(t)?t.every(r=>se(e,r)):typeof e!="string"?!1:!e.startsWith(t):!0,ie=(e,t)=>t?Array.isArray(t)?t.every(r=>ie(e,r)):typeof e!="string"?!1:!e.endsWith(t):!0;var b=({operator:e,pathname:t,value:r})=>e==="eq"?Z(t,r):e==="ne"?ee(t,r):e==="contains"?te(t,r):e==="notContains"?re(t,r):e==="startsWith"?oe(t,r):e==="endsWith"?ne(t,r):e==="notStartsWith"?se(t,r):e==="notEndsWith"?ie(t,r):e==="regex"?Y(t,r):!0,K=({eventTarget:e,value:t})=>t?Array.from(document.querySelectorAll(t)).some(r=>r.contains(e)):!1,Ie=e=>typeof e!="string"?!1:e.trim()?!!document.querySelector(e):!0,Pe=e=>typeof e!="string"?!1:e.trim()?!document.querySelector(e):!0;var P=()=>window.location.pathname+window.location.search;var xe=(e,t)=>{var n;let r=e.tour_trigger;return((n=e.currentTourIndex)!=null?n:0)>0||!r?!0:r.$and?r.$and.every(s=>{let a=s.type;if(a==="navigation"){if(!s.operator)return!0;let i=s.values;return i!=null&&i.every(c=>!c)?!0:b({operator:s.operator,pathname:t.pathname,value:i})}if(a==="dom-element"){let i=s.value;return typeof i!="string"?!1:i?!!document.querySelector(i):!0}if(a==="not-dom-element"){let i=s.value;return typeof i!="string"?!1:i?!document.querySelector(i):!0}if(a==="click"){let i=s.value;if(typeof i!="string")return!1;if(!i)return!0;if(!t.event||!(t.event instanceof MouseEvent))return!1;let c=t.event.target;return!c||!(c instanceof Element)?!1:K({eventTarget:c,value:i})}return B.error(`Aborting tour start due to an unrecognized tour trigger type: ${a}. Try updating the SDK or changing the tour trigger configuration.`),!1}):(B.error("Aborting tour start due to an unsupported tour trigger format. Try updating the SDK or changing the tour trigger configuration."),!1)};var ae=(e,t)=>new Proxy(e,{get(r,o,n){return o==="props"&&t(e.id),Reflect.get(r,o,n)}});var Te=e=>{let t=e.data;if(typeof t!="string")return null;try{let r=JSON.parse(t);if(He(r))return{type:"block-updates",exitedBlockIds:r.exitedBlockIds,updatedBlocks:r.updatedBlocks}}catch(r){}return null};function He(e){return typeof e=="object"&&e!==null&&"exitedBlockIds"in e&&"updatedBlocks"in e}import{effect as q}from"@preact/signals-core";import{debounce as Ge}from"es-toolkit";var v=async e=>{let t=h.value;if(!t)return;let{environment:r,organizationId:o,userId:n,apiUrl:s}=t;await _(s,V).sendEvent(k(g({},e),{environment:r,organizationId:o,userId:n}))},Ee=new Set,ce=async e=>{Ee.has(e)||(Ee.add(e),await v({name:"block-activated",blockId:e}))};var ue=(e,t)=>{let r=new Set(y.peek().map(o=>o.blockId));e.forEach(o=>{var s;r.has(o.id)||!xe(o,t)||(y.value=[...y.peek(),{blockId:o.id,currentBlockIndex:(s=o.currentTourIndex)!=null?s:0}])})},Me=(e,t)=>{y.value=y.value.map(r=>r.blockId===e?t(r):r)},Se=(e,t)=>{if(t===0)return;let o=t-1;v({name:"tour-update",blockId:e.id,properties:{currentTourIndex:o}}),setTimeout(()=>{Me(e.id,n=>k(g({},n),{currentBlockIndex:o}))},0)},E=(e,t)=>{var o,n;if(t===((n=(o=e.tourBlocks)==null?void 0:o.length)!=null?n:1)-1)D(e.id),v({name:"transition",blockId:e.id,propertyKey:"complete"});else{let s=t+1;v({name:"tour-update",blockId:e.id,properties:{currentTourIndex:s}}),setTimeout(()=>{Me(e.id,a=>k(g({},a),{currentBlockIndex:s}))},0)}},Ae=e=>{D(e),v({name:"transition",blockId:e,propertyKey:"cancel"})},Je=e=>{let t=new Map(I.peek().map(r=>[r.id,r]));y.value.forEach(r=>{var a,i,c;let o=t.get(r.blockId);if(!o)return;let n=(a=o.tourBlocks)==null?void 0:a.at(r.currentBlockIndex);if(!n)return;let s=n.tourWait;if(s&&s.interaction==="click"){let m=b({pathname:P(),operator:(i=s.page)==null?void 0:i.operator,value:(c=s.page)==null?void 0:c.value});K({eventTarget:e,value:s.element})&&m&&E(o,r.currentBlockIndex)}})},Ce=e=>{let t=e.target;t instanceof Element&&Je(t),ue(A.value,{pathname:P(),event:e})},R=new Map;q(()=>{let e=w.value,t=y.value,r=A.value,o=new Map(r.map(n=>[n.id,n]));t.forEach(n=>{var m,p,f;let s=o.get(n.blockId);if(!s)return;let a=(m=s.tourBlocks)==null?void 0:m.at(n.currentBlockIndex);if(!a)return;let i=R.get(n.blockId);i&&i.stepId!==a.id&&(clearTimeout(i.timeoutId),R.delete(n.blockId));let c=a.tourWait;if(c&&(c.interaction==="navigation"&&b({pathname:e,operator:(p=c.page)==null?void 0:p.operator,value:(f=c.page)==null?void 0:f.value})&&E(s,n.currentBlockIndex),c.interaction==="delay"&&c.ms!==void 0&&!R.has(n.blockId))){let u=window.setTimeout(()=>{E(s,n.currentBlockIndex),R.delete(n.blockId)},c.ms);R.set(n.blockId,{timeoutId:u,stepId:a.id})}})});q(()=>{let e=A.value,t=new Set(e.map(r=>r.id));y.value=y.peek().filter(r=>t.has(r.blockId))});q(()=>{let e=A.value,t=w.value;t&&ue(e,{pathname:t})});var Qe=e=>{let t=new Map(I.peek().map(r=>[r.id,r]));e.forEach(r=>{var i,c,m,p,f;let o=t.get(r.blockId);if(!o)return;let n=(i=o.tourBlocks)==null?void 0:i.at(r.currentBlockIndex);if(!n)return;let s=n.tourWait;if(!s)return;let a=s.element;if(s.interaction==="dom-element"){let u=b({pathname:P(),operator:(c=s.page)==null?void 0:c.operator,value:(m=s.page)==null?void 0:m.value});Ie(a)&&u&&E(o,r.currentBlockIndex)}if(s.interaction==="not-dom-element"){let u=b({pathname:P(),operator:(p=s.page)==null?void 0:p.operator,value:(f=s.page)==null?void 0:f.value});Pe(a)&&u&&E(o,r.currentBlockIndex)}})};q(()=>{if(typeof window=="undefined")return;let e=A.value,t=y.value,o=Ge(()=>{ue(e,{pathname:P()}),Qe(t)},32),n=new MutationObserver(o);return n.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),o(),()=>{n.disconnect()}});var De=e=>{Ce(e)};var le=0,We=e=>{let t=()=>{let r=new WebSocket(e.url);Q.value=!1;let o=()=>{e.onOpen(),le=0},n=()=>{setTimeout(()=>{t()},Math.min(1e3*4**le,12e4)),le+=1},s=()=>{Q.value=!0};return r.addEventListener("message",e.onMessage),r.addEventListener("open",o),r.addEventListener("close",n),r.addEventListener("error",s),{disconnect:()=>{r.removeEventListener("message",e.onMessage),r.removeEventListener("open",o),r.removeEventListener("close",n),r.removeEventListener("error",s),r.readyState===WebSocket.CONNECTING?r.addEventListener("open",()=>{r.close()}):r.close()}}};return t()};var M=null,Re=e=>{let{environment:t,organizationId:r,userId:o,apiUrl:n}=e,s={environment:t,organizationId:r,userId:o},a=`${n.replace("https://","wss://").replace("http://","ws://")}/ws/sdk/block-updates?${new URLSearchParams(s).toString()}`,i=()=>{J.value=!1,_(n,V).getBlocks(k(g({},s),{language:he(e.language),userProperties:e.userProperties})).then(p=>{var u;let f=C.value.reduce(G,p.blocks);N.value=f,C.value=[],(u=p.meta)!=null&&u.usage_limited&&(M==null||M())}).catch(p=>{J.value=!0,B.error("Failed to load blocks",p)})},c=p=>{let f=Te(p);f&&f.type==="block-updates"&&(N.value?N.value=G(I.value,f):C.value=[...C.value,f])};M==null||M(),M=We({url:a,onMessage:c,onOpen:i}).disconnect};var Oe=[],Le=e=>{Oe.forEach(({type:t,handler:r})=>{document.removeEventListener(t,r,!0)}),e.forEach(({type:t,handler:r})=>{document.addEventListener(t,r,!0)}),Oe=e};import{effect as Xe,signal as Ye}from"@preact/signals-core";var O="flows-debug-panel",L=Ye({enabled:!1,forceOpen:!1}),Ze=async()=>{if(typeof window!="undefined"&&!document.querySelector(O))try{let{DebugPanel:e}=await import("./debug-panel-6IPNW3ME.mjs");customElements.get(O)||customElements.define(O,e);let t=document.createElement(O);t.forceOpen=L.value.forceOpen,document.body.appendChild(t)}catch(e){B.error("Failed to load the DebugPanel module",e)}},et=()=>{if(typeof window=="undefined")return;let e=document.querySelector(O);e&&e.remove()};Xe(()=>{L.value.enabled?Ze():et()});var $e=e=>t=>{if((e!=null?e:ye)(t)){let o=!L.value.enabled;sessionStorage.setItem(ge,String(o)),o?B.info("Debug mode enabled"):B.info("Debug mode disabled"),L.value={enabled:o,forceOpen:o}}},Ne=e=>{L.value={enabled:ke(e),forceOpen:!1}};var pe=null,Zt=o=>{var n=o,{debug:e,onDebugShortcut:t}=n,r=me(n,["debug","onDebugShortcut"]);var f;let s=(f=r.apiUrl)!=null?f:"https://api.flows-cloud.com";h.value=k(g({},r),{apiUrl:s});let{environment:a,organizationId:i,userId:c,userProperties:m,language:p}=r;Re({apiUrl:s,environment:a,organizationId:i,userId:c,userProperties:m,language:p}),pe!==null&&clearInterval(pe),pe=window.setInterval(()=>{let u=P();w.value!==u&&(w.value=u)},250),Le([{type:"click",handler:De},{type:"keydown",handler:$e(t)}]),Ne(e)};import{computed as tt,effect as Fe}from"@preact/signals-core";var j=({block:e,userProperties:t})=>{if(!e.componentType)return[];let o=X({block:e,userProperties:t,removeBlock:D,exitNodeCb:({key:s,blockId:a})=>v({name:"transition",blockId:a,propertyKey:s}),setStateMemory:async({blockId:s,key:a,value:i})=>{ve(s,c=>{var m;return k(g({},c),{propertyMeta:(m=c.propertyMeta)==null?void 0:m.map(p=>p.type==="state-memory"&&p.key===a?k(g({},p),{value:i}):p)})}),await v({name:"set-state-memory",blockId:s,propertyKey:a,properties:{value:i}})}}),n={id:e.id,type:"component",component:e.componentType,props:o};return ae(n,ce)},z=({block:e,currentIndex:t,userProperties:r})=>{let o=e.tourBlocks;if(!(o!=null&&o.length))return[];let n=o.at(t);if(!(n!=null&&n.componentType))return[];let s=we({tourSteps:o,tourStep:n,currentIndex:t,userProperties:r,handleContinue:()=>{E(e,t)},handlePrevious:()=>{Se(e,t)},handleCancel:()=>{Ae(e.id)}}),a={id:n.id,tourBlockId:e.id,type:"tour-component",component:n.componentType,props:s};return ae(a,ce)};import{computed as H}from"@preact/signals-core";var Ve=H(()=>I.value.filter(e=>b({pathname:w.value,operator:e.page_targeting_operator,value:e.page_targeting_values}))),de=H(()=>{let e=new Map(I.value.map(t=>[t.id,t]));return y.value.filter(t=>{var n;let r=e.get(t.blockId),o=(n=r==null?void 0:r.tourBlocks)==null?void 0:n.at(t.currentBlockIndex);return b({pathname:w.value,operator:o==null?void 0:o.page_targeting_operator,value:o==null?void 0:o.page_targeting_values})}).flatMap(t=>{let r=e.get(t.blockId);return r?k(g({},t),{block:r}):[]})}),fe=H(()=>{let e=h.value,t=Ve.value.filter(o=>!o.slottable).flatMap(o=>{var n;return j({block:o,userProperties:(n=e==null?void 0:e.userProperties)!=null?n:{}})}),r=de.value.filter(o=>{var s;let n=(s=o.block.tourBlocks)==null?void 0:s.at(o.currentBlockIndex);return!(n!=null&&n.slottable)}).flatMap(o=>{var n;return z({block:o.block,currentIndex:o.currentBlockIndex,userProperties:(n=e==null?void 0:e.userProperties)!=null?n:{}})});return[...t,...r]}),_e=H(()=>Ve.value.filter(e=>e.slottable));var Ke=e=>"type"in e,Ue=e=>{var r,o,n;if(Ke(e))return(r=e.slotIndex)!=null?r:0;let t=(o=e.block.tourBlocks)==null?void 0:o.at(e.currentBlockIndex);return(n=t==null?void 0:t.slotIndex)!=null?n:0},qe=new Map,rt=e=>{let t=tt(()=>{let r=h.value,o=_e.value.filter(a=>a.slottable&&a.slotId===e),n=de.value.filter(a=>{var c;let i=(c=a.block.tourBlocks)==null?void 0:c.at(a.currentBlockIndex);return(i==null?void 0:i.slottable)&&i.slotId===e});return[...o,...n].sort((a,i)=>Ue(a)-Ue(i)).flatMap(a=>{var i,c;return Ke(a)?j({block:a,userProperties:(i=r==null?void 0:r.userProperties)!=null?i:{}}):z({block:a.block,currentIndex:a.currentBlockIndex,userProperties:(c=r==null?void 0:r.userProperties)!=null?c:{}})})});return qe.set(e,t),t},br=()=>fe.value,ot=e=>{var t,r;return(r=(t=qe.get(e))==null?void 0:t.value)!=null?r:rt(e).value},Br=e=>Fe(()=>{e(fe.value)}),wr=(e,t)=>Fe(()=>{t(ot(e))}),hr=()=>v({name:"reset-progress"}),Ir=e=>v({name:"reset-progress",workflowId:e}),Pr=e=>v({name:"workflow-start",blockKey:e});export{Br as addFloatingBlocksChangeListener,wr as addSlotBlocksChangeListener,br as getCurrentFloatingBlocks,ot as getCurrentSlotBlocks,Zt as init,hr as resetAllWorkflowsProgress,Ir as resetWorkflowProgress,Pr as startWorkflow};