"use strict";(()=>{var ie=Object.create;var x=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty;var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var le=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of se(t))!ae.call(e,o)&&o!==r&&x(e,o,{get:()=>t[o],enumerable:!(i=oe(t,o))||i.enumerable});return e};var ce=(e,t,r)=>(r=e!=null?ie(ne(e)):{},le(t||!e||!e.__esModule?x(r,"default",{value:e,enumerable:!0}):r,e));var Y=de((lt,J)=>{"use strict";var L=Object.defineProperty,ue=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,me=Object.prototype.hasOwnProperty,we=(e,t)=>{for(var r in t)L(e,r,{get:t[r],enumerable:!0})},ve=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ge(t))!me.call(e,o)&&o!==r&&L(e,o,{get:()=>t[o],enumerable:!(i=ue(t,o))||i.enumerable});return e},fe=e=>ve(L({},"__esModule",{value:!0}),e),H={};we(H,{createContextualWidget:()=>st});J.exports=fe(H);var ye=e=>!!e.getInstance,We=e=>!!e.getDeviceId,N=e=>{let t=null,r=null;if(!e.amplitude)return{userId:t,deviceId:r};if(ye(e.amplitude)){let i=e.amplitude?.getInstance();t=i?.options?.userId??null,r=i?.options?.deviceId??null}return We(e.amplitude)&&(t=e.amplitude?.getUserId?.()??null,r=e.amplitude?.getDeviceId?.()??null),{userId:t,deviceId:r}},Ie=500,Ee=5,U=null,Ue=(e,t)=>{let{delay:r=Ie,times:i=Ee}=t||{},o=0;return s=>{s.cohortUserId||(U&&e.removeEventListener("load",U),U=()=>{let a=setInterval(()=>{o+=1;let{userId:d}=N(e);if(d){s.identifyUser({cohortUserId:d}),clearInterval(a);return}o>=i&&clearInterval(a)},r)},e.addEventListener("load",U))}},Ae={apiKey:"",snippetCdnUrl:"https://snippet.maze.co",apiUrl:"https://prompts.maze.co/api",testingPagesUrl:"https://t.maze.co"},Re=480,Le=e=>({...Ae,...e.mazeContextualSettings||{}}),B=class{constructor(e){this.cacheClearTimeouts={},this.cachedItems=new Set,this.storage=e}getValue(e){let t=this.storage.getItem(e);if(!t)return null;let r=JSON.parse(t);return this.isValueExpired(r)?(this.removeValue(e),null):r.value}setValue(e,t,r=0){let i={value:t,expiresIn:r>0?Date.now()+r*60*1e3:0};this.storage.setItem(e,JSON.stringify(i)),this.cachedItems.add(e),this.cacheClearTimeouts[e]&&clearTimeout(this.cacheClearTimeouts[e]),r>0&&(this.cacheClearTimeouts[e]=setTimeout(()=>{this.removeValue(e)},r*60*1e3))}removeValue(e){this.storage.removeItem(e),this.cachedItems.delete(e),this.cacheClearTimeouts[e]&&(clearTimeout(this.cacheClearTimeouts[e]),delete this.cacheClearTimeouts[e])}clearAll(){this.cachedItems.forEach(e=>{this.removeValue(e)})}isValueExpired(e){return e.expiresIn>0&&e.expiresIn0&&this.supportsExipresIn&&(this.cacheClearTimeouts[e]=setTimeout(()=>{this.removeValue(e)},r*60*1e3))}removeValue(e){delete this.storage[e],this.cacheClearTimeouts[e]&&(clearTimeout(this.cacheClearTimeouts[e]),delete this.cacheClearTimeouts[e])}clearAll(){Object.keys(this.storage).forEach(e=>{this.removeValue(e)})}},be="__contextual-widget__",xe=({type:e,action:t,payload:r,channel:i})=>({type:e,action:t,payload:r,channel:i}),F=e=>`${be}${e}`,Ce=(e,t={})=>{let{id:r="PROMPT"}=t,i=[];return{send:o=>{let s=xe({channel:F(r),...o});e.postMessage(s,"*")},listen:o=>{let s=d=>{let{data:l}=d,{channel:u,...g}=l;u===F(r)&&o(g)};e.addEventListener("message",s);let a=()=>{e.removeEventListener("message",s)};i.push(a)},close:()=>{i.forEach(o=>{o()}),i=[]}}},K=class extends Error{constructor(e){super(e),this.name="ScriptLoadError"}},Te=(e,t)=>{let r=e.location.href;return i=>{let o=t.body||t,{location:s}=e;function a(){s.href!==r&&(r=s.href,i(s.href))}let d=new MutationObserver(a);o&&d.observe(o,{subtree:!0,childList:!0})}},k=e=>(t,r={})=>{let i=e.createElement("script");return i.src=t,i.async=r.async||!1,i.defer=r.defer||!1,i.id=r.id||"",e.getElementsByTagName("head")[0].appendChild(i),i},Pe="https://snippet.maze.co",Fe="maze-scaffold-helper-script",Se=async(e,t,r={})=>new Promise((i,o)=>{let{snippetCdnUrl:s=Pe}=r,a=Fe;if(e.getElementById(a)){i(e.getElementById(a));return}let d=`${s}/contextualScaffoldHelpers.js`,l=k(e)(d,{id:a,async:!0});l.addEventListener("load",()=>{i(l)}),l.addEventListener("error",()=>{o(new K(`Error loading script ${d}`))})}),De="https://snippet.maze.co",ze="maze-widget-app-script",Me=(e,t,r={})=>{let{snippetCdnUrl:i=De}=r,o=ze;if(e.getElementById(o))return e.getElementById(o);let s=`${i}/contextualWidgetAppScaffold.js`;return k(e)(s,{id:o,async:!0})},S={0:void 0,1:"color: cyan",3:void 0,5:"color: yellow",9:"color: red"};function _e(e){try{if(!e?.localStorage)return;let t=e.localStorage.getItem("maze-log-level");return t?Number.parseInt(t,10):void 0}catch{return}}var j=class R{static initializeLoggerMode(t){t&&(R._window=t,t.MAZE_LOG_LEVEL=_e(t)??9)}getCurrentLogLevel(){return R._window?.MAZE_LOG_LEVEL??9}verbose(t,r){this.logEvent(t,1,r)}info(t,r){this.logEvent(t,3,r)}warning(t,r){this.logEvent(t,5,r)}error(t,r){this.logEvent(t,9,r)}logEvent(t,r=3,i){let o=this.getCurrentLogLevel();r>=o&&(i===void 0?console.info(`%c maze-snippet: ${t}`,S[r]):console.info(`%c maze-snippet: ${t}`,S[r],i))}},n=new j,q=class extends Error{constructor(e,t,r){super(e),this.statusCode=t,this.correlationId=r,this.name="WidgetLoadError"}};function Ve(e,t){return Math.random()*(t-e)+e}function Oe(){return`${Date.now()}-${Ve(0,1e4)}`}function $e({apiUrl:e,apiKey:t}){return async function(r,i,o){let s=await fetch(`${e}/${r}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t,"x-maze-snippet-src":"contextual-widget","x-maze-correlation-id":o},body:JSON.stringify(i)});if(s.ok)return s;let a="Error fetching contextual prompts.";try{a=(await s.json()).message||a}catch{}throw new q(a,s.status,o)}}var G=({apiUrl:e,apiKey:t})=>{let r=$e({apiUrl:e,apiKey:t}),i=typeof window<"u"?window.navigator?.userAgent:"unknown",o=Oe();return{getWidgetsForVisitor:async({cohortProvider:s,cohortUserId:a})=>{try{return await(await r("widgets",{cohortProvider:s,cohortUserId:a},o)).json()}catch(d){return n.error("Error fetching contextual prompts.",{error:d}),[]}},logEvent:async({source:s,level:a,message:d,data:l})=>{try{await r("event",{source:s,level:a,message:d,data:{...l,userAgent:i,pathname:window?.location?.pathname||""}},o)}catch(u){n.error("Error logging events to the API.",{error:u})}}}},He=typeof window<"u"&&window.localStorage?new B(window.localStorage):new I,D=new I,z=!1,M=e=>{if(z)return D.getValue(e)||[];try{return He.getValue(e)||[]}catch{return z=!0,n.warning("[getWidgetIdsFromKey] Failed to get widget key from cache. Using fallback."),D.getValue(e)||[]}},Ne=()=>{let e=M("maze-contextual-widget-dismissed"),t=M("maze-contextual-widget-started");return[...e,...t]},Be={promptHostElement:{self:{default:2147483647},children:{contextualWidgetBranding:{self:{default:10}}}},mediaHostElement:{self:{hidden:0,shown:2147483647},children:{imageZoomControlButtons:{self:{default:10}}}}},Ke=(e,t)=>{let r="maze-contextual-widget-fonts";if(t.contentWindow?.document?.querySelector(`link#${r}`))return;let i=e.createElement("link");i.href="https://assets-cdn.maze.co/fonts/roobert-pro.css",i.rel="stylesheet",i.type="text/css",i.id=r,t?.contentWindow?.document?.head.appendChild(i)},A=e=>`${e}px`;function ke(e,{id:t}){return e.querySelector(`#${t}`)}function je(e,{id:t,tag:r}){let i=ke(e,{id:t});if(i)return i;let o=e.createElement(r);return o.id=t,e.body.appendChild(o),o}var Z=({id:e,_document:t=document})=>t.querySelector(`#${e}`),qe=(e,t,{id:r,className:i})=>{let o=Z({_document:t.contentWindow?.document,id:r});return o||(o=e.createElement("div"),o.id=r),o.classList.contains(i)||o.classList.add(i),o.style.cssText=` width: 100%; height: 100%; position:relative; `,o},Ge=(e,t)=>({id:r})=>{let i=`${r}-host`,o=`${r}-container`,s=je(t,{id:i,tag:"iframe"}),a=qe(t,s,{id:o,className:o});return s.contentWindow?.document?.body?.appendChild(a),s.addEventListener("load",()=>{Z({_document:s.contentWindow?.document,id:o})||s.contentWindow?.document?.body?.appendChild(a)}),{host:s,container:a}},Ze="maze-contextual-widget",_=16,V={compact:{height:A(430),width:A(420+_)},expanded:{height:A(680),width:A(420+_)}},Je=` height: ${V.compact.height}; width: ${V.compact.width}; max-width: 100%; position: fixed; border: none; overflow: hidden; z-index: ${Be.promptHostElement.self.default}; color-scheme: normal; `,O={BOTTOM_LEFT:{left:"0",bottom:"0",transform:"initial",right:"initial",top:"initial"},BOTTOM_RIGHT:{right:"0",bottom:"0",transform:"initial",left:"initial",top:"initial"},MIDDLE_LEFT:{left:"0",top:"50%",transform:"translateY(-50%)",right:" initial",bottom:"initial"},MIDDLE_RIGHT:{right:"0",top:"50%",transform:"translateY(-50%)",left:"initial",bottom:"initial"},CENTERED:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",right:"initial",bottom:"initial"}},Ye={left:"0",right:"0",bottom:"0",top:"initial",transform:"initial"},$=e=>Object.entries(e).reduce((t,[r,i])=>`${t}${r}:${i}; `,""),Qe=e=>{if(e.hostMaxWidth(e.style.cssText=Je+Qe({position:t,hostMaxWidth:r}),e),et=(e,t)=>({position:r})=>{let{host:i,container:o}=Ge(window,document)({id:Ze});return Xe(i,{position:r,hostMaxWidth:window.outerWidth}),Ke(t,i),{host:i,container:o}};function tt(e,t,r){return function(i){let{container:o,host:s}=et(e,t)({position:i?.styles.position||"BOTTOM_RIGHT"});if(!o)throw new Error("Cannot mount app");return r?r({host:s,container:o},i):(console.warn("mountApp is not defined"),null)}}var rt=class{constructor(e,t){this.config=e,this.cacheManager=t,this.unmountWidgetApp=null,this.widgetApp=null,this.identifyUser=r=>r.cohortUserId?(this.cohortUserId=r.cohortUserId,this.cohortProvider="AMPLITUDE",this.hasIdentifiedUser()&&(this.clearWidgetsForDomain(),this.config.onUserIdentified?.({cohortUserId:this.cohortUserId})),!0):!1,this.registerWidgetApp=r=>{this.widgetApp=r},this.deregisterWidgetApp=()=>{this.unMountApp(),this.widgetApp=null},this.renderWidget=async(r,i,{forceRequest:o}={})=>{let s={step:"start",hasUnmountWidgetAppCallback:!!this.unmountWidgetApp};try{n.verbose("[renderWidget] START",{url:this.url,forceRequest:o});let{shouldRender:a,widgetsForRoute:d,widgetsForDomain:l}=await this.shouldRenderWidget({forceRequest:o,errorLogInfo:s});if(s.step="fetchedWidgets",s.hasWidgetsForDomain=!!l.length,s.hasWidgetsForRoute=!!d.length,s.widgetsForDomain=l.map(f=>f.uuid),s.widgetsForRoute=d.map(f=>f.uuid),s.shouldRender=a,n.verbose("[renderWidget] shouldRenderWidget",{shouldRender:a,widgetsForRoute:d,widgetsForDomain:l,widgetApp:this.widgetApp}),this.widgetApp||(s.step="registeringWidgetApp",await this.config.onShouldRegisterWidgetApp?.({widgets:l,filteredWidgets:d})),s.step="registeredWidgetApp",s.registeredWidgetApp=!!this.widgetApp,!a){this.unMountApp();return}let[u]=d;if(this.unMountApp(),!this.widgetApp)return;let g=await this.executeGetVariablesFromRouteLazy({url:this.url,paths:u.paths});s.routeVariables=g,s.step="renderingWidget",this.unmountWidgetApp=tt(r,i,this.widgetApp)({...u,testingPagesUrl:this.config.testingPagesUrl,cohortUserId:this.cohortUserId,cohortProvider:this.cohortProvider,routeVariables:g,apiKey:this.config.apiKey})}catch(a){let d=a,l={};throw d instanceof q&&(l={statusCode:d.statusCode,correlationId:d.correlationId}),n.error("[renderWidget] error",{error:d}),this.mazeApi.logEvent({source:"contextualScaffold",level:s.shouldRender?"error":"warn",message:"Error while rendering widget",data:{message:d.message,stack:d.stack,errorName:d.name,...l,errorLogInfo:s}}),d}},this.setUrl=r=>{this.url=r},this.hasIdentifiedUser=()=>!!this.cohortUserId,this.clearWidgetsForDomain=()=>{this.widgetsForDomain=null},this.getWidgetsForDomain=async()=>(n.verbose("[getWidgetsForDomain] START",{currentWidgetsForDomain:this.widgetsForDomain}),this.widgetsForDomain?(n.verbose("[getWidgetsForDomain] returned widgets from cache"),this.widgetsForDomain):(this.widgetsForDomain=await this.mazeApi.getWidgetsForVisitor({cohortProvider:this.cohortProvider,cohortUserId:this.cohortUserId}),n.verbose("[getWidgetsForDomain] API result",{widgetsForDomain:this.widgetsForDomain}),this.widgetsForDomain)),this.getWidgetsToRender=async({forceRequest:r}={})=>{r&&this.clearWidgetsForDomain();let i=await this.getWidgetsForDomain(),o=Ne();return i?.filter(s=>!o.includes(s.uuid))??[]},this.filterWidgetsForRoute=async r=>{let i=r.map(async o=>{let{paths:s=[]}=o;return s.length===0||await this.executePathMatchesPatternLazy({url:this.url,paths:s})?o:null});return(await Promise.all(i)).filter(Boolean)},this.shouldRenderWidget=async({forceRequest:r,errorLogInfo:i}={})=>{let o=await this.getWidgetsToRender({forceRequest:r});if(i&&(i.step="getWidgetsToRender"),n.verbose("[shouldRenderWidget] filteredWidgetsForDomain",{filteredWidgetsForDomain:o,forceRequest:r}),!o.length)return{shouldRender:!1,widgetsForRoute:o,widgetsForDomain:o};let s=await this.filterWidgetsForRoute(o);return i&&(i.step="filterWidgetsForRoute"),{shouldRender:!!s.length,widgetsForRoute:s,widgetsForDomain:o}},this.unMountApp=()=>{this.unmountWidgetApp&&(this.unmountWidgetApp(),this.unmountWidgetApp=null)},this.initHelpers=async()=>{this.helpersLoadPromise&&await this.helpersLoadPromise,!this.helpers&&(this.helpersLoadPromise=this.config.onLoadWidgetHelper?.(),this.helpers=await this.helpersLoadPromise,n.verbose("[initHelpers] helpers",{helpers:this.helpers}))},this.cohortUserId=e.cohortUserId,this.cohortProvider=e.cohortProvider,this.url=e.url,this.mazeApi=G({apiUrl:e.apiUrl,apiKey:e.apiKey})}get widgetsForDomain(){return this.cacheManager.getValue("maze:widgets")}set widgetsForDomain(e){try{this.cacheManager.setValue("maze:widgets",e,15),n.verbose("[set widgetsForDomain] cached widgets",{value:e})}catch(t){this.cacheManager=new I,this.cacheManager.setValue("maze:widgets",e),n.error("[set widgetsForDomain] error while saving to cache (using fallback)",{error:t,value:e}),this.mazeApi.logEvent({source:"contextualScaffold",level:"warn",message:"Failed to save widgets to session storage. Using fallback.",data:{message:t.message,value:e}})}}async executeGetVariablesFromRouteLazy({url:e,paths:t}){return this.helpers||await this.initHelpers(),this.helpers?.getVariablesFromRoute?this.helpers.getVariablesFromRoute({url:e,paths:t}):(n.error("[executeGetVariablesFromRouteLazy] helpers not initialized"),{})}async executePathMatchesPatternLazy({url:e,paths:t}){return this.helpers||await this.initHelpers(),this.helpers?.pathMatchesPattern?this.helpers.pathMatchesPattern({url:e,paths:t}):(n.error("[executePathMatchesPatternLazy] helpers not initialized"),!1)}},it=(e,t)=>{let r={...Le(e),...t||{}},{userId:i}=N(e);return!r.cohortUserId&&i&&(r.cohortUserId=i,r.cohortProvider="AMPLITUDE"),r},ot=(e,t)=>t.debug?new I:typeof e<"u"&&e.sessionStorage?new B(e.sessionStorage):new I;function st(e,t){let r=Ce(e);j.initializeLoggerMode(e);let i=window.location.href;return n.verbose("[createContextualWidget] START"),function(o){let s=it(e,o),a=ot(e,s),d=Ue(e),l=G({apiUrl:s.apiUrl,apiKey:s.apiKey}),u=!1,g=c=>{p.setUrl(c),p.renderWidget(e,t).catch(h=>{n.error("[handleRouteChange] renderWidget",{error:h})})},f=({widgets:c,filteredWidgets:h})=>new Promise((w,v)=>{if(n.verbose("[onShouldRegisterWidgetApp] START",{attachedRouteChangeListener:u,widgetsForDomain:c,widgetsForPath:h}),c?.length&&!u){u=!0;let re=Te(e,t);e.addEventListener("hashchange",W=>{n.verbose("[onShouldRegisterWidgetApp] hashChange event",{url:W.newURL}),g(W.newURL)}),re(W=>{n.verbose("[onShouldRegisterWidgetApp] onRouteChange",{url:W}),g(W)})}if(!h||h.length===0){w(!1);return}n.verbose("[onShouldRegisterWidgetApp] loadWidgetAppScript",{snippetCdnUrl:s.snippetCdnUrl});let b=Me(t,e,{snippetCdnUrl:s.snippetCdnUrl});b.onload=()=>{n.verbose("[onShouldRegisterWidgetApp] loadWidgetAppScript onLoad event"),w(!0)},b.onerror=()=>{v(new K("Error loading widget app script"))}}),ee=async()=>(n.verbose("[onLoadWidgetHelper] load helper script",{snippetCdnUrl:s.snippetCdnUrl}),await Se(t,e,{snippetCdnUrl:s.snippetCdnUrl}),e.mazeHelpers);r.listen(({type:c,payload:h})=>{if(c==="registerWidgetApp"){n.verbose("[onWidgetEvent] registerWidgetApp",{type:c}),p.renderWidget(e,t).catch(w=>{n.error("[onWidgetEvent] renderWidget",{type:c,error:w})});return}c==="deregisterWidgetApp"&&(n.verbose("[onWidgetEvent] deregisterWidgetApp",{type:c}),p.deregisterWidgetApp()),c==="widgetAppError"&&(n.error("[widgetAppError]",{...h}),l.logEvent({source:"widgetApp",level:"error",message:"Error in widget React app",data:h}))});let te=async()=>{await p.renderWidget(e,t)},p=new rt({...s,communicate:r,onShouldRegisterWidgetApp:f,onLoadWidgetHelper:ee,onUserIdentified:te,url:i},a);d(p);let m=!1,y=0,E=setInterval(()=>{if(y+=1,m){n.verbose("[detection] widget already loaded",{siteLoaded:m,activationAttempt:y}),clearInterval(E);return}if(y>10){n.warning("[detection] max activation attempt triggered",{activationAttempt:y,siteLoaded:m}),clearInterval(E);return}(t.readyState==="complete"||t.readyState==="interactive")&&(n.verbose("[detection] readyState triggered",{siteLoaded:m,activationAttempt:y}),clearInterval(E),m=!0,p.renderWidget(e,t))},1e3);return e.addEventListener("load",async()=>{n.verbose("[window] onLoad",{siteLoaded:m}),clearInterval(E),m=!0,await p.renderWidget(e,t)}),{...p,render:({forceRequest:c=!1,forRoute:h}={})=>{if(n.verbose("[render] START",{forceRequest:c,forRoute:h}),h){let w=new URL(e.location.href).origin;try{let v=new URL(w+h);n.verbose("[render] set new URL",{newUrl:v}),p.setUrl(v.href)}catch(v){n.error("[render] Invalid URL",{baseUrl:w,forRoute:h,error:v});return}}p.renderWidget(e,t,{forceRequest:c})}}}}});var he=(e,t)=>e&&t?`${e}/static/${t}`:"",pe="f02c5fca13ea83bdcca248ce921e15c3500da08d",C=he("https://snippet.maze.co",pe);var T="https://prompts.maze.co/api",P="https://t.maze.co";var Q=ce(Y()),X=(e,t)=>{let r=e?.mazeUniversalSnippetApiKey||"",i={...e?.mazePromptsSettings||{apiKey:r}};return(o={})=>{!i.apiKey&&r&&(i.apiKey=r),e.mazePrompts=(0,Q.createContextualWidget)(e,t)({...i,...o})}};var nt={apiUrl:T,testingPagesUrl:P,snippetCdnUrl:C};X(window,document)(nt);})();