flowgrid-sdk 1.6.4 → 1.6.5
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/dist/flowgrid.min.js +1 -1
- package/dist/flowgrid.min.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +14 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/features/core/experiment.d.ts +8 -0
- package/dist/lib/features/core/experiment.js +16 -0
- package/dist/lib/features/core/experiment.js.map +1 -1
- package/dist/lib/features/ecommerce/cart.js +1 -0
- package/dist/lib/features/ecommerce/cart.js.map +1 -1
- package/dist/lib/helpers/consent.d.ts +87 -0
- package/dist/lib/helpers/consent.js +125 -0
- package/dist/lib/helpers/consent.js.map +1 -0
- package/dist/lib/helpers/identity.d.ts +45 -0
- package/dist/lib/helpers/identity.js +104 -0
- package/dist/lib/helpers/identity.js.map +1 -0
- package/dist/lib/helpers/index.d.ts +21 -0
- package/dist/lib/helpers/index.js +29 -0
- package/dist/lib/helpers/index.js.map +1 -0
- package/dist/lib/tracking/core/experiment.d.ts +12 -0
- package/dist/lib/tracking/core/experiment.js +14 -0
- package/dist/lib/tracking/core/experiment.js.map +1 -1
- package/dist/umd/index.js +1 -1
- package/dist/umd/index.js.map +1 -1
- package/package.json +1 -1
package/dist/flowgrid.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.flowgrid=t():e.flowgrid=t()}(this,()=>(()=>{"use strict";var e,t,r={748(e,t,r){r.d(t,{o:()=>i});class i{constructor(e,t,r,i,s,n){if(!e?.trim()||!t?.trim())throw new Error("SDK init failed: webId and endpoint are required.");this.webId=e.trim(),this.endpoint=this.normalizeEndpoint(t),this.apiKey=r,this.identityManager=s,this.visitorId=i??"",this.transportConfig={botDetection:n?.botDetection??"block",respectDNT:n?.respectDNT??!0,sampleRate:n?.sampleRate??1},this.drainEventBuffer()}static setConsent(e){Object.assign(i.consent,e)}static hasConsent(e){return i.consent[e]??!1}static isLikelyBot(){return!("undefined"==typeof navigator||!navigator.webdriver&&!/bot|crawl|spider|headless|phantom|puppeteer/i.test(navigator.userAgent))}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}static getDeviceContext(){if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=window.location,t="undefined"!=typeof document?document:void 0;return{_screen_width:window.screen?.width,_screen_height:window.screen?.height,_device_type:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",_language:navigator.language,_url:e?.href,_page:e?.pathname,_referrer:t?.referrer||void 0,_title:t?.title||void 0}}sendViaBeacon(e,t={}){if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;const r=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",s=t.type||"event",n=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(s)}`,a=JSON.stringify({web_id:this.webId,visitor_id:r,event_name:e,properties:{...t,...i.getDeviceContext()}});return navigator.sendBeacon(n,new Blob([a],{type:"application/json"}))}async postRaw(e,t,r={}){if(!1===i.consent.analytics)return;if(!1!==this.transportConfig.respectDNT&&this.isDNTEnabled())return;const s=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(e)}`,n=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",a=JSON.stringify({web_id:this.webId,visitor_id:n,...t}),o=!0===r.useBeacon,c=a.length,u=o&&c<=6e4;if(o&&c>6e4){const t=JSON.stringify({...JSON.parse(a),api_key:this.apiKey});try{"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:"application/json"}))||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} beacon rejected (payload ${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} beacon error:`,t)}return}try{const t=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:a,...u?{keepalive:!0}:{}});t.ok||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} rejected: ${t.status} ${t.statusText} (${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} network error (${c} bytes):`,t)}}bufferEvent(e,t,r){if("undefined"!=typeof localStorage)try{const s=localStorage.getItem(i.EVENT_BUFFER_KEY),n=s?JSON.parse(s):[];if(n.length>=i.MAX_BUFFER_EVENTS)return;const a=JSON.stringify([...n,{url:e,method:t,body:r}]);if((new TextEncoder).encode(a).length>i.MAX_BUFFER_SIZE)return;n.push({url:e,method:t,body:r}),localStorage.setItem(i.EVENT_BUFFER_KEY,JSON.stringify(n))}catch{}}drainEventBuffer(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(i.EVENT_BUFFER_KEY);if(!e)return;const t=JSON.parse(e);localStorage.removeItem(i.EVENT_BUFFER_KEY);for(const e of t)fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:e.body}).catch(()=>{})}catch{}}async init(e,t={},r="POST"){if(!i.hasConsent("analytics"))return{};if(this.transportConfig.respectDNT&&this.isDNTEnabled())return{};if("block"===this.transportConfig.botDetection&&i.isLikelyBot())return{};this.validateInput(e,t),"tag"===this.transportConfig.botDetection&&i.isLikelyBot()&&(t={...t,_bot:!0});const s={...i.getDeviceContext(),...t},n=s.type||"event",a=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(n)}`,o=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",c=JSON.stringify({web_id:this.webId,visitor_id:o,event_name:e,properties:s});return this.executeRequest(a,r,"GET"===r?void 0:c)}async initFeature(e,t){if(this.validateInput(e,t),!t.type)throw new Error("Feature events must include a type property");const r=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(t.type)}`,i=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",s=JSON.stringify({web_id:this.webId,visitor_id:i,event_name:e,properties:t});return this.executeRequest(r,"POST",s)}async executeRequest(e,t,r,s){let n=0;for(;n<=i.MAX_RETRIES;){const a=new AbortController,o=setTimeout(()=>a.abort(),i.TIMEOUT_MS);try{const c=await fetch(e,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...s},body:r,signal:a.signal});if(clearTimeout(o),c.status>=500&&n<i.MAX_RETRIES){n++,await this.backoff(n);continue}if(!c.ok){const e=await this.safeRead(c);throw new Error(`SDK request failed (${c.status} ${c.statusText}) ${e}`)}return await c.json()}catch(s){if(clearTimeout(o),s instanceof Error&&("AbortError"===s.name||s.message.includes("fetch"))&&n<i.MAX_RETRIES){n++,await this.backoff(n);continue}if(n>=i.MAX_RETRIES&&(r&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(e,new Blob([r],{type:"application/json"}))||this.bufferEvent(e,t,r)),s instanceof Error&&"AbortError"===s.name)throw new Error("SDK request timed out");throw s}}throw new Error("SDK request exhausted retries without resolution")}backoff(e){const t=Math.min(1e3*Math.pow(2,e-1),3e4),r=Math.random()*t;return new Promise(e=>setTimeout(e,r))}validateInput(e,t){if(!e||"string"!=typeof e||!e.trim())throw new Error("Event name must be a non-empty string");if(e.length>100)throw new Error("Event name must be less than 100 characters");let r;try{r=JSON.stringify({web_id:this.webId,visitor_id:this.visitorId??"",event_name:e,properties:t})}catch{throw new Error("Properties must be JSON serializable")}if((new TextEncoder).encode(r).length>i.MAX_PAYLOAD_SIZE)throw new Error("Event payload too large (max 10KB)");const s=["password","token","secret","apikey","authorization"],n=r.toLowerCase();for(const e of s)n.includes(e)&&console.warn(`SDK Warning: Properties may contain sensitive data (${e}).`)}normalizeEndpoint(e){let t=e.trim();return t.startsWith("http://")||t.startsWith("https://")||(t=`https://${t}`),t.replace(/\/+$/,"")}async safeRead(e){try{return await e.text()}catch{return""}}}i.MAX_PAYLOAD_SIZE=1e4,i.TIMEOUT_MS=1e4,i.MAX_RETRIES=3,i.MAX_BUFFER_EVENTS=100,i.MAX_BUFFER_SIZE=5e4,i.EVENT_BUFFER_KEY="fg_event_buffer",i.consent={analytics:!0,marketing:!0}},547(e,t,r){function i(){return"undefined"!=typeof window?window:void 0}function s(){return"undefined"!=typeof document?document:void 0}function n(){return"undefined"!=typeof window&&"undefined"!=typeof document}function a(...e){return()=>{for(const t of e)if("function"==typeof t)try{t()}catch{}}}r.d(t,{Bd:()=>n,YE:()=>s,vs:()=>a,zk:()=>i})}},i={};function s(e){var t=i[e];if(void 0!==t)return t.exports;var n=i[e]={exports:{}};return r[e](n,n.exports,s),n.exports}s.m=r,s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,r)=>(s.f[r](e,t),t),[])),s.u=e=>({137:"flowgrid-enterprise",717:"flowgrid-vitals",897:"flowgrid-replay"}[e]+".flowgrid.chunk.js"),s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="flowgrid:",s.l=(r,i,n,a)=>{if(e[r])e[r].push(i);else{var o,c;if(void 0!==n)for(var u=document.getElementsByTagName("script"),p=0;p<u.length;p++){var d=u[p];if(d.getAttribute("src")==r||d.getAttribute("data-webpack")==t+n){o=d;break}}o||(c=!0,(o=document.createElement("script")).charset="utf-8",s.nc&&o.setAttribute("nonce",s.nc),o.setAttribute("data-webpack",t+n),o.src=r),e[r]=[i];var l=(t,i)=>{o.onerror=o.onload=null,clearTimeout(h);var s=e[r];if(delete e[r],o.parentNode&&o.parentNode.removeChild(o),s&&s.forEach(e=>e(i)),t)return t(i)},h=setTimeout(l.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=l.bind(null,o.onerror),o.onload=l.bind(null,o.onload),c&&document.head.appendChild(o)}},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{var e={792:0};s.f.j=(t,r)=>{var i=s.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var n=new Promise((r,s)=>i=e[t]=[r,s]);r.push(i[2]=n);var a=s.p+s.u(t),o=new Error;s.l(a,r=>{if(s.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var n=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,i[1](o)}},"chunk-"+t,t)}};var t=(t,r)=>{var i,n,[a,o,c]=r,u=0;if(a.some(t=>0!==e[t])){for(i in o)s.o(o,i)&&(s.m[i]=o[i]);c&&c(s)}for(t&&t(r);u<a.length;u++)n=a[u],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},r=this.webpackChunkflowgrid=this.webpackChunkflowgrid||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var n={};s.r(n),s.d(n,{FlowGrid:()=>xe,default:()=>qe});var a=s(748);function o(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}const c="fg_visitor_id",u="fg_session_id",p="fg_session_touch";class d{constructor(e){this.visitorId="",this.sessionId="",this.memoryStore={},this.config={visitorId:e?.visitorId??"",cookieDomain:e?.cookieDomain??"",visitorMaxAgeDays:e?.visitorMaxAgeDays??365,sessionTimeoutMinutes:e?.sessionTimeoutMinutes??30,storage:e?.storage??(this.detectBrowser()?"cookie":"memory"),serverCookies:e?.serverCookies,compat:e?.compat??!0},this.visitorId=this.resolveVisitorId(),this.sessionId=""}getVisitorId(){return this.visitorId||(this.visitorId=this.resolveVisitorId()),this.visitorId}getSessionId(){if("memory"===this.config.storage)return this.getMemorySessionId();if(!this.detectBrowser())return this.getMemorySessionId();try{const e=sessionStorage.getItem(u),t=sessionStorage.getItem(p);if(e&&t){if(Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return sessionStorage.setItem(p,String(Date.now())),this.sessionId=e,e}const r=this.generateSessionId();return sessionStorage.setItem(u,r),sessionStorage.setItem(p,String(Date.now())),this.sessionId=r,r}catch{return this.getMemorySessionId()}}setVisitorId(e){this.visitorId=e,this.persistVisitorId(e)}clearSession(){if(this.sessionId="",delete this.memoryStore[u],delete this.memoryStore[p],this.detectBrowser())try{sessionStorage.removeItem(u),sessionStorage.removeItem(p)}catch{}}clearAll(){if(this.visitorId="",this.sessionId="",this.memoryStore={},this.detectBrowser())try{this.deleteCookie(this.visitorCookieName),this.deleteCookie(c),localStorage.removeItem(this.visitorCookieName),localStorage.removeItem(c),localStorage.removeItem("fg_exp_assignments"),sessionStorage.removeItem(u),sessionStorage.removeItem(p)}catch{}}isBrowser(){return this.detectBrowser()}get visitorCookieName(){return this.config.compat?"visitor_id":c}resolveVisitorId(){if(this.config.visitorId)return this.config.visitorId;if(this.detectBrowser()){const e=function(){try{return o("visitor_id")||localStorage.getItem("visitor_id")}catch{return o("visitor_id")}}();if(e){const t=this.readCookie(c)||this.readLocalStorage(c);return t&&t!==e&&this.removeLegacyCookie(),this.persistVisitorId(e),e}}if(this.config.compat){const e=this.readCookie(c)||this.readLocalStorage(c);if(e)return this.persistVisitorId(e),this.removeLegacyCookie(),e}const e=this.readCookie(this.visitorCookieName);if(e)return e;if(this.detectBrowser())try{const e=localStorage.getItem(this.visitorCookieName);if(e)return e}catch{}if(this.config.serverCookies){const e=this.readServerCookie(this.visitorCookieName);if(e)return e}if(this.memoryStore[this.visitorCookieName])return this.memoryStore[this.visitorCookieName];const t=this.generateVisitorId();return this.persistVisitorId(t),t}readLocalStorage(e){if(!this.detectBrowser())return null;try{return localStorage.getItem(e)}catch{return null}}removeLegacyCookie(){if(this.deleteCookie(c),this.detectBrowser())try{localStorage.removeItem(c)}catch{}}persistVisitorId(e){const t=this.visitorCookieName;if("memory"!==this.config.storage)if(this.detectBrowser()){this.writeCookie(t,e,this.config.visitorMaxAgeDays);try{localStorage.setItem(t,e)}catch{}}else this.memoryStore[t]=e;else this.memoryStore[t]=e}getMemorySessionId(){const e=this.memoryStore[u],t=this.memoryStore[p];if(e&&t&&Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return this.memoryStore[p]=String(Date.now()),this.sessionId=e,e;const r=this.generateSessionId();return this.memoryStore[u]=r,this.memoryStore[p]=String(Date.now()),this.sessionId=r,r}readCookie(e){return this.config.serverCookies?this.readServerCookie(e):this.detectBrowser()?o(e):null}readServerCookie(e){if(!this.config.serverCookies)return null;const t=this.config.serverCookies.get(e);return t?"object"==typeof t&&"value"in t?t.value||null:"string"==typeof t&&t||null:null}writeCookie(e,t,r){if(!this.detectBrowser())return;const i=24*r*60*60,s=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",n="https:"===location.protocol?"; Secure":"";document.cookie=`${e}=${encodeURIComponent(t)}; Path=/; Max-Age=${i}; SameSite=Lax${n}${s}`}deleteCookie(e){if(!this.detectBrowser())return;const t=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${e}=; Path=/; Max-Age=0${t}`}generateVisitorId(){return`fg_${this.uuidV4()}`}generateSessionId(){return`fgs_${Date.now()}_${this.randomHex(8)}`}uuidV4(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}randomHex(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}detectBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}}class l extends a.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"activation",timestamp:(new Date).toISOString()})}async trackOnboardingStep(e){return await this.init("onboarding_step",{type:"activation",subtype:"onboarding_step",userId:e.userId,stepId:e.stepId,stepName:e.stepName,stepOrder:e.stepOrder,totalSteps:e.totalSteps,progress:Math.round(e.stepOrder/e.totalSteps*100),timeSpent:e.timeSpent,skipped:e.skipped||!1,...e.properties,timestamp:(new Date).toISOString()})}async completeOnboarding(e,t,r,i){return await this.init("onboarding_completed",{type:"activation",subtype:"onboarding_complete",userId:e,totalTimeSpent:t,stepsCompleted:r,stepsSkipped:i,completionRate:Math.round(r/(r+i)*100),timestamp:(new Date).toISOString()})}async trackFirstAction(e){return await this.init("first_action",{type:"activation",subtype:"first_action",userId:e.userId,actionName:e.actionName,timeSinceSignup:e.timeSinceSignup,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async trackSignup(e,t,r,i){return await this.init("signup_completed",{type:"activation",subtype:"signup",userId:e,method:t,source:r,...i,timestamp:(new Date).toISOString()})}}class h extends a.o{async create(e){return await this.init("create_tracking",{type:"feature_usage",subtype:"create_custom",userId:e.userId,category:e.category,action:e.action,...e.properties,timestamp:(new Date).toISOString()})}async trackUsage(e){return await this.init("feature_usage",{type:"feature_usage",subtype:e.action,featureId:e.featureId,featureName:e.featureName,userId:e.userId,action:e.action,duration:e.duration,success:e.success,category:e.category,...e.properties,timestamp:(new Date).toISOString()})}}class m extends a.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"prompt",timestamp:(new Date).toISOString()})}async trackSubmission(e){return await this.init("prompt_submitted",{type:"prompt",subtype:"submission",promptId:e.promptId,userId:e.userId,promptType:e.promptType,model:e.model,inputTokens:e.inputTokens,conversationId:e.conversationId,...e.properties,timestamp:(new Date).toISOString()})}async trackResponse(e){return await this.init("prompt_response",{type:"prompt",subtype:"response",promptId:e.promptId,responseTime:e.responseTime,outputTokens:e.outputTokens,completed:e.completed,error:e.error,qualityScore:e.qualityScore,timestamp:(new Date).toISOString()})}async trackFeedback(e){return await this.init("prompt_feedback",{type:"prompt",subtype:"feedback",promptId:e.promptId,userId:e.userId,feedbackType:e.feedbackType,rating:e.rating,comment:e.comment,timestamp:(new Date).toISOString()})}async trackConversation(e,t,r,i){return await this.init("prompt_conversation",{type:"prompt",subtype:"conversation",conversationId:e,userId:t,turnCount:r,totalDuration:i,timestamp:(new Date).toISOString()})}}function g(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=16777619*t>>>0;return t}const y="fg_exp_assignments",I="fg_exp_assignments";class f extends a.o{constructor(){super(...arguments),this.experiments={},this.assignments={}}parseAssignmentCookie(e){if(!e)return{};try{const t=decodeURIComponent(e),r=JSON.parse(t);return r&&"object"==typeof r?r:{}}catch{return{}}}readAssignmentCookie(){return this.parseAssignmentCookie(o(I))}writeAssignmentCookie(){try{if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.assignments)),t=31536e3,r="Lax",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${I}=${e}; Path=/; Max-Age=${t}; SameSite=${r}${i}`}catch{}}loadAssignments(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(y);if(e){const t=JSON.parse(e);if(t&&"object"==typeof t)return t}}}catch{}const e=this.readAssignmentCookie();return Object.keys(e).length>0?e:{}}saveAssignments(){try{"undefined"!=typeof localStorage&&localStorage.setItem(y,JSON.stringify(this.assignments))}catch{}this.writeAssignmentCookie()}injectAssignments(e){this.assignments={...this.assignments,...e}}getAssignments(){return{...this.assignments}}hydrateFromCookies(e){const t=e.get(I),r="string"==typeof t?t:t?.value??null,i=this.parseAssignmentCookie(r??null);Object.keys(i).length>0&&this.injectAssignments(i)}hydrateFromCookieHeader(e){if(!e)return;const t=e.split(/;\s*/),r=`${I}=`,i=t.find(e=>e.startsWith(r));if(!i)return;const s=this.parseAssignmentCookie(i.slice(r.length));Object.keys(s).length>0&&this.injectAssignments(s)}serializeAssignmentCookie(){const e=encodeURIComponent(JSON.stringify(this.assignments));return`${I}=${e}; Path=/; Max-Age=31536000; SameSite=Lax`}clearAssignments(){this.assignments={};try{"undefined"!=typeof localStorage&&localStorage.removeItem(y)}catch{}try{"undefined"!=typeof document&&(document.cookie=`${I}=; Path=/; Max-Age=0; SameSite=Lax`)}catch{}}getOrCreateAnonId(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(f.ANON_ID_KEY);if(e)return e;const t="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return localStorage.setItem(f.ANON_ID_KEY,t),t}}catch{}return"anon_"+g(String(Math.random())).toString(36)}deterministicAssign(e,t,r){const i=g(e+t);let s=0;for(const e of r)s+=e.weight;const n=i%1e4/1e4*s;let a=0;for(const e of r)if(a+=e.weight,n<a)return e.id;return r[r.length-1].id}assignVariant(e,t){this.assignments=this.loadAssignments();const r=this.assignments[e];if(r&&t.some(e=>e.id===r))return;const i=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId(),s=this.deterministicAssign(i,e,t);this.assignments[e]=s,this.saveAssignments(),this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:i,variantId:s,source:"random",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}async verifyExperiments(e){const t={web_id:this.webId,experiments:e.map(e=>({experiment_id:e.id,variants:e.variants,properties:e.properties||{}}))};try{const e=await fetch(`${this.endpoint}/api/v1/experiments/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await e.json();if(r.ok&&Array.isArray(r.data))for(const e of r.data)"error"!==e.action&&(this.experiments[e.experiment_id]={variants:e.variants,properties:e.properties??{},verified:!0},this.assignVariant(e.experiment_id,e.variants))}catch{for(const t of e)this.experiments[t.id]={variants:t.variants,properties:t.properties||{},verified:!1},this.assignVariant(t.id,t.variants)}}async initExperiments(e){this.assignments=this.loadAssignments(),e.length>0&&await this.verifyExperiments(e)}getLocalVariant(e){return this.assignments=this.loadAssignments(),this.assignments[e]??null}async trackLocalConversion(e,t="conversion",r=1){const i=this.getLocalVariant(e);if(!i)return;const s=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e,userId:s,variantId:i,metricName:t,value:r,timestamp:(new Date).toISOString()})}async track(e){return await this.init(e.eventName,{...e.properties,type:"experiment",subtype:"custom",variant:e.variant,timestamp:(new Date).toISOString()})}async define(e){return await this.init("experiment_definition",{type:"experiment",subtype:"definition",...e,timestamp:(new Date).toISOString()})}async assign(e){return await this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,source:e.source||"random",timestamp:(new Date).toISOString()})}async trackConversion(e){return await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,metricName:e.metricName,value:e.value,timestamp:(new Date).toISOString()})}async trackExposure(e,t,r){return await this.init("experiment_exposure",{type:"experiment",subtype:"exposure",experimentId:e,userId:t,variantId:r,timestamp:(new Date).toISOString()})}}f.ANON_ID_KEY="fg_anon_id";var v=s(547);class w extends a.o{async track(e){return await this.init("page_view",{type:"page_view",url:e.url,path:e.path,title:e.title||"",referrer:e.referrer||"",userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackScrollDepth(e){return await this.init("scroll_depth",{type:"scroll_depth",path:e.path,scrollDepth:Math.min(100,Math.max(0,e.scrollDepth)),timeAtDepth:e.timeAtDepth,timestamp:(new Date).toISOString()})}async trackTimeOnPage(e){return await this.init("time_on_page",{type:"time_on_page",path:e.path,duration:e.duration,engaged:e.engaged??!1,timestamp:(new Date).toISOString()})}async trackExit(e,t,r){return await this.init("page_exit",{type:"page_exit",path:e,duration:t,scrollDepth:r,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=(0,v.YE)();let i=t.location.pathname,s=Date.now(),n=0;const a=new Set,o=()=>{this.track({url:t.location.href,path:t.location.pathname,title:r.title,referrer:r.referrer,userId:e.userId,sessionId:e.sessionId})},c=()=>{const e=Math.round((Date.now()-s)/1e3);e<=0||this.trackTimeOnPage({path:i,duration:e,engaged:n>10})},u=()=>{t.location.pathname!==i&&(c(),i=t.location.pathname,s=Date.now(),n=0,a.clear(),o())},p=t.history.pushState,d=t.history.replaceState;t.history.pushState=function(...e){const r=p.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r},t.history.replaceState=function(...e){const r=d.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r};const l=()=>u(),h=()=>u();t.addEventListener("popstate",l),t.addEventListener("flowgrid:locationchange",h);const m=()=>{const e=r.documentElement,s=t.scrollY||e.scrollTop,o=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(s/o*100));c>n&&(n=c);for(const e of[25,50,75,100])c>=e&&!a.has(e)&&(a.add(e),this.trackScrollDepth({path:i,scrollDepth:e}))};t.addEventListener("scroll",m,{passive:!0});const g=()=>{"hidden"===r.visibilityState&&c()};return r.addEventListener("visibilitychange",g),t.addEventListener("pagehide",c),o(),(0,v.vs)(()=>t.removeEventListener("popstate",l),()=>t.removeEventListener("flowgrid:locationchange",h),()=>t.removeEventListener("scroll",m),()=>r.removeEventListener("visibilitychange",g),()=>t.removeEventListener("pagehide",c),()=>{t.history.pushState=p,t.history.replaceState=d})}}class S extends a.o{async start(e={}){return await this.init("session_start",{type:"session_start",user:e.user,device:e.device,location:e.location,source:e.source||e.utm?.utmSource,medium:e.medium||e.utm?.utmMedium,campaign:e.campaign||e.utm?.utmCampaign,utm:e.utm,landingPage:e.landingPage||("undefined"!=typeof window?window.location.href:""),referrer:e.referrer||("undefined"!=typeof document?document.referrer:""),...e.properties,timestamp:(new Date).toISOString()})}async update(e,t){return await this.init("session_update",{type:"session_update",sessionId:e,...t,timestamp:(new Date).toISOString()})}async end(e){return await this.init("session_end",{type:"session_end",sessionId:e,timestamp:(new Date).toISOString()})}async heartbeat(e){return await this.init("session_heartbeat",{type:"session_heartbeat",sessionId:e,timestamp:(new Date).toISOString()})}autoTrack(e={},t={}){if(!(0,v.Bd)())return()=>{};const r=(0,v.zk)(),i=(0,v.YE)(),s=t.heartbeatMs??3e4,n="flowgrid:sessionId";let a;try{a=r.sessionStorage.getItem(n)||void 0}catch{}const o=a?Promise.resolve(a):this.start(e).then(e=>{a=e.response.sessionId;try{r.sessionStorage.setItem(n,a)}catch{}return a}).catch(()=>{}),c=r.setInterval(()=>{a&&"visible"===i.visibilityState&&this.heartbeat(a)},s),u=()=>{a&&this.end(a)};return r.addEventListener("pagehide",u),(0,v.vs)(()=>r.clearInterval(c),()=>r.removeEventListener("pagehide",u),()=>{o.then(()=>{a&&this.end(a)})},()=>{try{r.sessionStorage.removeItem(n)}catch{}})}}class _ extends a.o{async track(e){return await this.init("custom_event",{type:"custom_event",eventName:e.eventName,category:e.category||"general",action:e.action,label:e.label,value:e.value,nonInteraction:e.nonInteraction||!1,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackBatch(e){const t=e.events.map(e=>({...e,timestamp:(new Date).toISOString()}));return await this.init("batch_events",{type:"batch_events",events:t,count:t.length,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("click_event",{type:"click_event",...e,timestamp:(new Date).toISOString()})}async trackForm(e){return await this.init("form_event",{type:"form_event",...e,timestamp:(new Date).toISOString()})}async trackSearch(e){return await this.init("search_event",{type:"search_event",query:e.query,category:e.category,resultsCount:e.resultsCount,resultClicked:e.resultClicked,clickedPosition:e.clickedPosition,filters:e.filters,timestamp:(new Date).toISOString()})}async trackError(e){return await this.init("error_event",{type:"error_event",message:e.message,stack:e.stack,errorType:e.type,fatal:e.fatal||!1,context:e.context,userAction:e.userAction,timestamp:(new Date).toISOString()})}}class k extends a.o{async user(e){return await this.init("identify_user",{type:"identify",userId:e.userId,anonymousId:e.anonymousId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async updateTraits(e,t){return await this.init("update_traits",{type:"update_traits",userId:e,traits:t,timestamp:(new Date).toISOString()})}async alias(e){return await this.init("alias_user",{type:"alias",previousId:e.previousId,userId:e.userId,timestamp:(new Date).toISOString()})}async group(e){return await this.init("group_user",{type:"group",userId:e.userId,groupId:e.groupId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async reset(e){return await this.init("reset_identity",{type:"reset",userId:e,timestamp:(new Date).toISOString()})}}class b extends a.o{async define(e){return await this.init("define_funnel",{type:"define_funnel",funnelId:e.funnelId,name:e.name,description:e.description,steps:e.steps,timestamp:(new Date).toISOString()})}async trackStep(e){return await this.init("funnel_step",{type:"funnel_step",funnelId:e.funnelId,step:e.step,stepNumber:e.stepNumber,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackComplete(e,t,r){return await this.init("funnel_complete",{type:"funnel_complete",funnelId:e,userId:t,...r,timestamp:(new Date).toISOString()})}async trackAbandon(e,t,r,i){return await this.init("funnel_abandon",{type:"funnel_abandon",funnelId:e,lastStep:t,userId:r,reason:i,timestamp:(new Date).toISOString()})}async analyze(e,t){return await this.init("analyze_funnel",{type:"query",funnelId:e,filter:t||{range:"last30days"},timestamp:(new Date).toISOString()})}async compare(e,t,r){return await this.init("compare_funnel",{type:"query",funnelId:e,baselineFilter:t,comparisonFilter:r,timestamp:(new Date).toISOString()})}async list(){return await this.init("list_funnels",{type:"query",timestamp:(new Date).toISOString()})}}class T extends a.o{async trackActivity(e){return await this.init("user_activity",{type:"user_activity",userId:e.userId,action:e.action||"active",sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackLifecycleChange(e,t,r){return await this.init("lifecycle_change",{type:"lifecycle_change",userId:e,stage:t,previousStage:r,timestamp:(new Date).toISOString()})}}class x extends a.o{async trackTouchpoint(e){return await this.init("attribution_touchpoint",{type:"attribution_touchpoint",userId:e.userId,channel:e.channel,campaign:e.campaign,medium:e.medium,source:e.source,content:e.content,term:e.term,referrer:e.referrer,landingPage:e.landingPage,...e.properties,timestamp:(new Date).toISOString()})}async recordConversion(e){return await this.init("attribution_conversion",{type:"attribution_conversion",userId:e.userId,conversionType:e.conversionType,value:e.value,conversionId:e.conversionId,...e.properties,timestamp:(new Date).toISOString()})}captureFromUrl(e){if(!(0,v.Bd)())return null;const t=(0,v.zk)(),r=(0,v.YE)();if(!t||!r)return null;const i=new URLSearchParams(t.location.search),s={utmSource:i.get("utm_source")??void 0,utmMedium:i.get("utm_medium")??void 0,utmCampaign:i.get("utm_campaign")??void 0,utmTerm:i.get("utm_term")??void 0,utmContent:i.get("utm_content")??void 0},n=r.referrer||void 0;if(!(s.utmSource||s.utmMedium||s.utmCampaign||n))return null;const a={userId:e,channel:s.utmSource||(n?"referral":"direct"),campaign:s.utmCampaign,medium:s.utmMedium,source:s.utmSource,content:s.utmContent,term:s.utmTerm,referrer:n,landingPage:t.location.pathname};return this.trackTouchpoint(a),a}}class C extends a.o{constructor(){super(...arguments),this.lastMovementTime=0,this.lastScrollTime=0}async trackClick(e){return await this.init("heatmap_click",{type:"heatmap_click",pageUrl:e.pageUrl,x:e.x,y:e.y,normalizedX:e.x/e.viewportWidth,normalizedY:e.y/e.viewportHeight,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,elementSelector:e.elementSelector,elementText:e.elementText?.substring(0,50),userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackMovement(e){const t=Date.now();return t-this.lastMovementTime<C.MOVEMENT_THROTTLE_MS?{eventName:"heatmap_movement",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastMovementTime=t,await this.init("heatmap_movement",{type:"heatmap_movement",pageUrl:e.pageUrl,path:e.path,viewport:e.viewport,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackScroll(e){const t=Date.now();return t-this.lastScrollTime<C.SCROLL_THROTTLE_MS?{eventName:"heatmap_scroll",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastScrollTime=t,await this.init("heatmap_scroll",{type:"heatmap_scroll",pageUrl:e.pageUrl,maxScrollDepth:e.maxScrollDepth,pageHeight:e.pageHeight,viewportHeight:e.viewportHeight,timeAtDepths:e.timeAtDepths,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackRageClick(e,t,r,i){return await this.init("heatmap_rage_click",{type:"heatmap_rage_click",pageUrl:e,x:t,y:r,clickCount:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=(0,v.YE)(),i=r=>{const i=r.target;var s;this.trackClick({pageUrl:t.location.pathname,x:r.clientX,y:r.clientY+t.scrollY,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,elementSelector:(s=i,s?s.id?`#${s.id}`:`${s.tagName.toLowerCase()}${s.className&&"string"==typeof s.className?"."+s.className.trim().split(/\s+/).slice(0,2).join("."):""}`:""),elementText:(i?.textContent||"").trim().slice(0,50),userId:e.userId,sessionId:e.sessionId})};r.addEventListener("click",i,{capture:!0,passive:!0});let s=0,n=!1;const a=()=>{n=!1;const i=r.documentElement;this.trackScroll({pageUrl:t.location.pathname,maxScrollDepth:s,pageHeight:i.scrollHeight,viewportHeight:t.innerHeight,sessionId:e.sessionId})},o=()=>{const e=r.documentElement,i=t.scrollY||e.scrollTop,o=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(i/o*100));c>s&&(s=c),n||(n=!0,t.addEventListener("pagehide",a,{once:!0}))};let c;if(t.addEventListener("scroll",o,{passive:!0}),e.movement){let i=[];const s=Date.now(),n=r=>{if(i.push({x:r.clientX,y:r.clientY,t:Date.now()-s}),i.length>=50){const r=i;i=[],this.trackMovement({pageUrl:t.location.pathname,path:r,viewport:{width:t.innerWidth,height:t.innerHeight},sessionId:e.sessionId})}};r.addEventListener("mousemove",n,{passive:!0}),c=()=>r.removeEventListener("mousemove",n)}return(0,v.vs)(()=>r.removeEventListener("click",i,{capture:!0}),()=>t.removeEventListener("scroll",o),()=>t.removeEventListener("pagehide",a),c)}}C.MOVEMENT_THROTTLE_MS=100,C.SCROLL_THROTTLE_MS=500;class E extends a.o{async trackWebVitals(e){return await this.init("web_vitals",{type:"web_vitals",...e,timestamp:(new Date).toISOString()})}async trackPageLoad(e){return await this.init("page_load",{type:"page_load",...e,timestamp:(new Date).toISOString()})}async trackResource(e){return await this.init("resource_timing",{type:"resource_timing",...e,timestamp:(new Date).toISOString()})}async trackApiCall(e,t,r,i){return await this.init("api_timing",{type:"api_timing",endpoint:e,duration:t,success:r,statusCode:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=t.location.pathname,i=[];let n=!1;s.e(717).then(s.bind(s,237)).then(t=>{if(n)return;const i=t=>{const i=t.name.toLowerCase(),s={pageUrl:r,userId:e.userId};s[i]=t.value,this.trackWebVitals(s)};t.onLCP?.(i),t.onCLS?.(i),t.onINP?.(i),t.onFCP?.(i),t.onTTFB?.(i),t.onFID?.(i)}).catch(()=>{}),i.push(()=>{n=!0});const a=()=>{const e=t.performance?.getEntriesByType?.("navigation")?.[0];e&&this.trackPageLoad({pageUrl:r,dnsTime:Math.max(0,e.domainLookupEnd-e.domainLookupStart),tcpTime:Math.max(0,e.connectEnd-e.connectStart),ttfb:Math.max(0,e.responseStart-e.requestStart),domContentLoaded:e.domContentLoadedEventEnd,loadTime:e.loadEventEnd,domInteractive:e.domInteractive,transferSize:e.transferSize})};if("complete"===t.document.readyState)a();else{const e=()=>a();t.addEventListener("load",e,{once:!0}),i.push(()=>t.removeEventListener("load",e))}if(e.resources&&"function"==typeof t.PerformanceObserver){const s=e.minDuration??200,n=new t.PerformanceObserver(e=>{for(const t of e.getEntries()){if(t.duration<s)continue;const e=t.initiatorType;this.trackResource({resourceUrl:t.name,resourceType:["script","stylesheet","image","font","fetch","xhr"].includes(e)?e:"other",duration:Math.round(t.duration),transferSize:t.transferSize,pageUrl:r})}});try{n.observe({type:"resource",buffered:!0}),i.push(()=>n.disconnect())}catch{}}return(0,v.vs)(...i)}}function D(){if(!(0,v.Bd)())return!1;try{return"granted"===localStorage.getItem("flowgrid:replayConsent")}catch{return!1}}const q="flowgrid:replaySessionId",O="rrweb@2";class P extends a.o{constructor(){super(...arguments),this.disabled=!1,this.active=null,this.state="idle"}async start(e={}){if(!1===e.enabled||this.disabled)return this.setState("disabled",e),()=>{};if(this.active&&!this.active.stopped)return this.emitStatus(this.active.options),()=>this.stop("manual");if(!(0,v.Bd)())return()=>{};if(!0===e.requireConsent&&!D()&&!a.o.hasConsent("analytics"))return this.setState("disabled",e),()=>{};this.setState("starting",e);const t=e.sampleRate??1;if(t<1&&Math.random()>t)return this.setState("sampled_out",e),()=>{};let r;try{r=await s.e(897).then(s.bind(s,546))}catch(t){return"undefined"!=typeof console&&console.error("[FlowGrid] Session replay failed to load rrweb:",t),this.handleError(this.toError(t),{phase:"import"},e),()=>{}}const i=(0,v.YE)();if(!i)return()=>{};const n=e.sessionId??this.resolveSessionId(),o=this.normalizeOptions(e),c=Date.now(),u={sessionId:n,userId:e.userId??this.boundUserId,startedAtMs:c,startedAt:new Date(c).toISOString(),sequence:0,buffer:[],bufferBytes:0,totalBytes:0,droppedEvents:0,stopped:!1,initialSnapshotCaptured:!1,flushTimer:setInterval(()=>{this.flush("interval")},o.flushIntervalMs),durationGuard:setTimeout(()=>this.stop("max_duration"),o.maxDurationMs),onVisibility:()=>{"hidden"===i.visibilityState&&this.flush("visibility_hidden",{useBeacon:!0})},onPageHide:()=>{this.flush("pagehide",{useBeacon:!0})},options:o};this.active=u;try{u.stopRecording=r.record({emit:e=>this.captureEvent(e),maskAllInputs:o.maskAllInputs,maskTextClass:o.maskTextClass??"fg-mask",blockClass:o.blockClass??"fg-block",ignoreClass:o.ignoreClass??"fg-ignore",checkoutEveryNth:200,checkoutEveryNms:3e4,inlineImages:!1,collectFonts:!1})}catch(e){return this.handleError(this.toError(e),{phase:"record",sessionId:n},o),u.stopped=!0,this.cleanupActive("stop"),this.active=null,()=>{}}return i.addEventListener("visibilitychange",u.onVisibility),window.addEventListener("pagehide",u.onPageHide),this.setState("recording",o),()=>this.stop("manual")}enable(e={}){return this.disabled=!1,this.start({...e,enabled:!0})}disable(){this.disabled=!0,this.stop("manual"),this.setState("disabled",this.active?.options)}stop(e="stop"){const t=this.active;t&&!t.stopped&&(t.stopped=!0,this.cleanupActive(e),this.flush(e,{useBeacon:!0,isFinal:!0}),this.setState("stopped",t.options,e),this.active=null)}async flush(e="manual",t={}){const r=this.active;if(!r||0===r.buffer.length)return;const i=r.buffer,s=i.length,n=r.bufferBytes,a=r.sequence++;r.buffer=[],r.bufferBytes=0;const o=(new Date).toISOString(),c=this.createIdempotencyKey(r.sessionId,a,n),u={sessionId:r.sessionId,userId:r.userId,sequence:a,eventsCount:s,byteSize:n,reason:e,isFinal:!0===t.isFinal,droppedEvents:r.droppedEvents,capturedAt:o,idempotencyKey:c};try{await this.postReplayChunk(r.sessionId,i,{userId:r.userId,sequence:a,useBeacon:t.useBeacon,startedAt:r.startedAt,capturedAt:o,pageUrl:this.getPageUrl(),isFinal:u.isFinal,reason:e,privacy:this.createPrivacyMetadata(r.options,"sampled_in"),droppedEvents:r.droppedEvents,recorderVersion:O},c),r.options.onFlush?.(u),this.emitStatus(r.options,e)}catch(e){this.handleError(this.toError(e),{phase:"flush",sessionId:r.sessionId},r.options)}}identify(e){this.boundUserId=e,this.active&&(this.active.userId=e,this.emitStatus(this.active.options))}getStatus(){return this.createStatus(this.active?.options)}async sendChunk(e,t,r={}){0!==t.length&&await this.postReplayChunk(e,t,r)}async postReplayChunk(e,t,r,i=this.createIdempotencyKey(e,r.sequence??0,this.measureEvents(t))){await this.postRaw("replay_chunk",{type:"replay_chunk",session_id:e,user_id:r.userId,sequence:r.sequence??0,started_at:r.startedAt,captured_at:r.capturedAt??(new Date).toISOString(),events:t,page_url:r.pageUrl??this.getPageUrl(),idempotency_key:i,compression:"none",is_final:!0===r.isFinal,chunk_kind:r.isFinal?"final":"partial",flush_reason:r.reason??"manual",dropped_events:r.droppedEvents??0,recorder_version:r.recorderVersion??O,privacy:r.privacy??this.createPrivacyMetadata(void 0,"sampled_in")},{useBeacon:r.useBeacon})}captureEvent(e){const t=this.active;if(!t||t.stopped)return;let r=0;try{r=JSON.stringify(e).length}catch{return t.droppedEvents++,void t.options.onDrop?.({sessionId:t.sessionId,reason:"serialization_error",droppedEvents:t.droppedEvents})}return t.totalBytes+r>t.options.maxBytes?(t.droppedEvents++,t.options.onDrop?.({sessionId:t.sessionId,reason:"max_bytes",droppedEvents:t.droppedEvents,byteSize:t.totalBytes+r,maxBytes:t.options.maxBytes}),void this.stop("max_bytes")):(t.totalBytes+=r,t.buffer.push(e),t.bufferBytes+=r,t.initialSnapshotCaptured||2!==e.type?void(t.bufferBytes>=t.options.flushBytes&&this.flush("size")):(t.initialSnapshotCaptured=!0,void Promise.resolve().then(()=>{this.flush("manual")})))}cleanupActive(e){const t=this.active;if(!t)return;const r=(0,v.YE)();clearInterval(t.flushTimer),clearTimeout(t.durationGuard),r?.removeEventListener("visibilitychange",t.onVisibility),window.removeEventListener("pagehide",t.onPageHide);try{t.stopRecording?.()}catch(e){this.handleError(this.toError(e),{phase:"stop",sessionId:t.sessionId},t.options)}this.emitStatus(t.options,e)}normalizeOptions(e){return{...e,flushIntervalMs:e.flushIntervalMs??5e3,flushBytes:e.flushBytes??524288,maxDurationMs:e.maxDurationMs??18e5,maxBytes:e.maxBytes??10485760,maskAllInputs:e.maskAllInputs??!0}}createStatus(e,t){const r=this.active;return{state:this.state,sessionId:r?.sessionId,userId:r?.userId??this.boundUserId,startedAt:r?.startedAt,sequence:r?.sequence??0,bufferedEvents:r?.buffer.length??0,bufferedBytes:r?.bufferBytes??0,totalBytes:r?.totalBytes??0,droppedEvents:r?.droppedEvents??0,recorderVersion:O,lastFlushReason:t,lastError:this.lastError}}setState(e,t,r){this.state=e,this.emitStatus(t,r)}emitStatus(e,t){e?.onStatus?.(this.createStatus(e,t))}handleError(e,t,r){this.lastError=e.message,this.state="error",r?.onError?.(e,t),this.emitStatus(r)}createPrivacyMetadata(e,t="sampled_in"){const r=D()||a.o.hasConsent("analytics");return{masking_mode:!1===e?.maskAllInputs?"selective":"all_inputs",blocked_selectors:this.selectorList(e?.blockClass??"fg-block"),redacted_fields:this.selectorList(e?.maskTextClass??"fg-mask"),consent_state:r?"granted":"denied",sampling_state:t}}selectorList(e){return"string"==typeof e?[e]:[e.source]}getPageUrl(){try{return"undefined"!=typeof location?location.href:""}catch{return""}}createIdempotencyKey(e,t,r){return`${this.webId}:${e}:${t}:${r}`}measureEvents(e){try{return JSON.stringify(e).length}catch{return 0}}toError(e){return e instanceof Error?e:new Error(String(e))}resolveSessionId(){try{const e=sessionStorage.getItem(q);if(e)return e;const t=this.generateId();return sessionStorage.setItem(q,t),t}catch{return this.generateId()}}generateId(){const e="undefined"!=typeof crypto?crypto:void 0;return e?.randomUUID?e.randomUUID():`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}}class A extends a.o{async view(e){return await this.init("product_view",{type:"ecommerce",subtype:"product_view",product:{productId:e.productId,name:e.name,brand:e.brand,category:e.category,variant:e.variant,price:e.price,currency:e.currency,url:e.url,imageUrl:e.imageUrl,rating:e.rating,reviewCount:e.reviewCount,stockStatus:e.stockStatus,attributes:e.attributes},source:e.source,searchQuery:e.searchQuery,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async impression(e){return await this.init("product_impression",{type:"ecommerce",subtype:"product_impression",list:e.list,productCount:e.list.products.length,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("product_click",{type:"ecommerce",subtype:"product_click",product:e.product,listId:e.listId,position:e.position,userId:e.userId,timestamp:(new Date).toISOString()})}async quickView(e,t){return await this.init("product_quick_view",{type:"ecommerce",subtype:"product_quick_view",product:e,listId:t,timestamp:(new Date).toISOString()})}async interaction(e,t,r){return await this.init("product_interaction",{type:"ecommerce",subtype:"product_interaction",productId:e,action:t,...r,timestamp:(new Date).toISOString()})}}class M extends a.o{async addItem(e){const t=e.product.price*e.quantity-(e.product.discount||0);return await this.init("add_to_cart",{type:"ecommerce",subtype:"add_to_cart",product:e.product,quantity:e.quantity,lineTotal:t,cartId:e.cartId,userId:e.userId,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async removeItem(e){return await this.init("remove_from_cart",{type:"ecommerce",subtype:"remove_from_cart",product:e.product,quantity:e.quantity,cartId:e.cartId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async updateItem(e){return await this.init("update_cart_item",{type:"ecommerce",subtype:"update_cart_item",product:e.product,previousQuantity:e.previousQuantity,newQuantity:e.newQuantity,quantityChange:e.newQuantity-e.previousQuantity,cartId:e.cartId,timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_cart",{type:"ecommerce",subtype:"view_cart",cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t){return await this.init("cart_abandoned",{type:"ecommerce",subtype:"cart_abandoned",cart:e,cartValue:e.total,itemCount:e.itemCount,reason:t,timestamp:(new Date).toISOString()})}async applyCoupon(e,t,r,i){return await this.init("apply_coupon",{type:"ecommerce",subtype:"apply_coupon",cartId:e,couponCode:t,success:r,discount:i,timestamp:(new Date).toISOString()})}}class N extends a.o{async begin(e){return await this.init("begin_checkout",{type:"ecommerce",subtype:"begin_checkout",cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async step(e){return await this.init("checkout_step",{type:"ecommerce",subtype:"checkout_step",step:e.step,stepNumber:e.stepNumber,cart:e.cart,option:e.option,userId:e.userId,timestamp:(new Date).toISOString()})}async addShipping(e){return await this.init("add_shipping_info",{type:"ecommerce",subtype:"shipping_info",cart:e.cart,shipping:e.shipping,shippingMethod:e.shipping.method,shippingCost:e.shipping.cost,userId:e.userId,timestamp:(new Date).toISOString()})}async addPayment(e){return await this.init("add_payment_info",{type:"ecommerce",subtype:"payment_info",cart:e.cart,payment:e.payment,paymentMethod:e.payment.method,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t,r){return await this.init("checkout_abandoned",{type:"ecommerce",subtype:"checkout_abandoned",cart:e,step:t,cartValue:e.total,reason:r,timestamp:(new Date).toISOString()})}async paymentAttempt(e,t,r,i){return await this.init("payment_attempt",{type:"ecommerce",subtype:"payment_attempt",success:e,cart:t,payment:r,errorCode:i,timestamp:(new Date).toISOString()})}}class B extends a.o{async track(e){const t=e.order;return await this.init("purchase",{type:"ecommerce",subtype:"purchase",order:{orderId:t.orderId,items:t.items,subtotal:t.subtotal,discountTotal:t.discountTotal,shippingTotal:t.shippingTotal,taxTotal:t.taxTotal,total:t.total,currency:t.currency,shipping:t.shipping,payment:t.payment,coupons:t.coupons,affiliation:t.affiliation},revenue:t.total,itemCount:t.items.reduce((e,t)=>e+t.quantity,0),userId:e.userId,sessionId:e.sessionId,attribution:e.attribution,...e.properties,timestamp:(new Date).toISOString()})}async statusChange(e,t,r){return await this.init("order_status_change",{type:"ecommerce",subtype:"order_status_change",orderId:e,newStatus:t,previousStatus:r,timestamp:(new Date).toISOString()})}async shipped(e,t){return await this.init("order_shipped",{type:"ecommerce",subtype:"order_shipped",orderId:e,shipping:t,timestamp:(new Date).toISOString()})}async delivered(e,t){return await this.init("order_delivered",{type:"ecommerce",subtype:"order_delivered",orderId:e,deliveredAt:t||(new Date).toISOString(),timestamp:(new Date).toISOString()})}}class F extends a.o{async track(e){return await this.init("refund",{type:"ecommerce",subtype:"refund",orderId:e.orderId,refundId:e.refundId,items:e.items,amount:e.amount,currency:e.currency,reason:e.reason,isFullRefund:e.isFullRefund,userId:e.userId,initiatedBy:e.initiatedBy,...e.properties,timestamp:(new Date).toISOString()})}async request(e,t,r){return await this.init("refund_requested",{type:"ecommerce",subtype:"refund_requested",orderId:e,items:t,reason:r,timestamp:(new Date).toISOString()})}async approve(e,t){return await this.init("refund_approved",{type:"ecommerce",subtype:"refund_approved",refundId:e,approvedAmount:t,timestamp:(new Date).toISOString()})}async deny(e,t){return await this.init("refund_denied",{type:"ecommerce",subtype:"refund_denied",refundId:e,denialReason:t,timestamp:(new Date).toISOString()})}async complete(e,t){return await this.init("refund_completed",{type:"ecommerce",subtype:"refund_completed",refundId:e,processedAmount:t,timestamp:(new Date).toISOString()})}}class U extends a.o{async view(e){return await this.init("promotion_view",{type:"ecommerce",subtype:"promotion_view",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,page:e.page,userId:e.userId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("promotion_click",{type:"ecommerce",subtype:"promotion_click",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,destinationUrl:e.destinationUrl,userId:e.userId,timestamp:(new Date).toISOString()})}async couponUsed(e){return await this.init("coupon_used",{type:"ecommerce",subtype:"coupon_used",code:e.code,orderId:e.orderId,discountValue:e.discountValue,discountType:e.discountType,orderValueBefore:e.orderValueBefore,orderValueAfter:e.orderValueAfter,savings:e.orderValueBefore-e.orderValueAfter,userId:e.userId,timestamp:(new Date).toISOString()})}async couponAttempt(e,t,r){return await this.init("coupon_attempt",{type:"ecommerce",subtype:"coupon_attempt",code:e,success:t,failureReason:r,timestamp:(new Date).toISOString()})}}class L extends a.o{async add(e){return await this.init("add_to_wishlist",{type:"ecommerce",subtype:"add_to_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,source:e.source,timestamp:(new Date).toISOString()})}async remove(e){return await this.init("remove_from_wishlist",{type:"ecommerce",subtype:"remove_from_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_wishlist",{type:"ecommerce",subtype:"view_wishlist",wishlistId:e.wishlistId,itemCount:e.items.length,timestamp:(new Date).toISOString()})}async moveToCart(e,t){return await this.init("wishlist_to_cart",{type:"ecommerce",subtype:"wishlist_to_cart",product:e,wishlistId:t,timestamp:(new Date).toISOString()})}async share(e,t){return await this.init("share_wishlist",{type:"ecommerce",subtype:"share_wishlist",wishlistId:e,method:t,timestamp:(new Date).toISOString()})}}class R extends a.o{async recordAcquisitionCost(e){return await this.init("record_acquisition_cost",{type:"ecommerce",subtype:"acquisition_cost",userId:e.userId,cost:e.cost,channel:e.channel,campaign:e.campaign,timestamp:(new Date).toISOString()})}async updateSegment(e,t){return await this.init("update_customer_segment",{type:"ecommerce",subtype:"update_customer_segment",userId:e,segment:t,timestamp:(new Date).toISOString()})}}class V extends a.o{async track(e){return await this.init("site_search",{type:"ecommerce",subtype:"site_search",query:e.query,resultsCount:e.resultsCount,hasResults:e.resultsCount>0,category:e.category,filters:e.filters,sortBy:e.sortBy,page:e.page||1,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("search_result_click",{type:"ecommerce",subtype:"search_result_click",query:e.query,product:e.product,position:e.position,page:e.page||1,timestamp:(new Date).toISOString()})}async trackRefinement(e,t,r){return await this.init("search_refinement",{type:"ecommerce",subtype:"search_refinement",originalQuery:e,refinedQuery:t,refinementType:r,timestamp:(new Date).toISOString()})}async trackSuggestion(e,t,r){return await this.init("search_suggestion",{type:"ecommerce",subtype:"search_suggestion",partialQuery:e,selectedSuggestion:t,suggestionPosition:r,timestamp:(new Date).toISOString()})}}class $ extends a.o{async start(e){return await this.init("subscription_start",{type:"ecommerce",subtype:"subscription_start",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,mrr:e.mrr,billingCycle:e.billingCycle,trialDays:e.trialDays,coupon:e.coupon,isTrialing:(e.trialDays||0)>0,...e.properties,timestamp:(new Date).toISOString()})}async change(e){const t=e.newMrr.amount-e.previousMrr.amount;return await this.init("subscription_change",{type:"ecommerce",subtype:"subscription_change",subscriptionId:e.subscriptionId,userId:e.userId,previousPlan:e.previousPlan,newPlan:e.newPlan,previousMrr:e.previousMrr,newMrr:e.newMrr,mrrChange:t,changeType:e.changeType,timestamp:(new Date).toISOString()})}async cancel(e){return await this.init("subscription_cancel",{type:"ecommerce",subtype:"subscription_cancel",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,lostMrr:e.lostMrr,reason:e.reason,feedback:e.feedback,immediate:e.immediate,timestamp:(new Date).toISOString()})}async renew(e,t,r){return await this.init("subscription_renew",{type:"ecommerce",subtype:"subscription_renew",subscriptionId:e,userId:t,mrr:r,timestamp:(new Date).toISOString()})}async trialConverted(e,t,r,i){return await this.init("trial_converted",{type:"ecommerce",subtype:"trial_converted",subscriptionId:e,userId:t,plan:r,mrr:i,timestamp:(new Date).toISOString()})}async trialExpired(e,t){return await this.init("trial_expired",{type:"ecommerce",subtype:"trial_expired",subscriptionId:e,userId:t,timestamp:(new Date).toISOString()})}}class j{constructor(e){this.client=e}signup(e,t,r,i){return this.client.trackSignup(e,t,r,i)}onboardingStep(e,t,r,i,s,n){return this.client.trackOnboardingStep({userId:e,stepId:t,stepName:r,stepOrder:i,totalSteps:s,...n})}onboardingComplete(e,t,r,i=0){return this.client.completeOnboarding(e,t,r,i)}firstAction(e,t,r,i){return this.client.trackFirstAction({userId:e,actionName:t,timeSinceSignup:r,properties:i})}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class z{constructor(e){this.client=e}used(e,t,r="used",i){return this.client.trackUsage({featureId:e,featureName:t,action:r,properties:i})}create(e,t,r,i){return this.client.create({userId:e,action:t,properties:{featureName:r,...i}})}}class H{constructor(e){this.client=e}submitted(e,t,r){return this.client.trackSubmission({promptId:e,promptType:t,properties:r})}responded(e,t,r,i){return this.client.trackResponse({promptId:e,responseTime:t,completed:r,properties:i})}feedback(e,t,r){return this.client.trackFeedback({promptId:e,feedbackType:t,properties:r})}conversation(e,t,r,i){return this.client.trackConversation(e,t,r,i)}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class K{constructor(e){this.client=e}define(e){return this.client.define(e)}init(e){return this.client.initExperiments(e)}variant(e){return this.client.getLocalVariant(e)}assign(e,t,r,i="targeted"){return this.client.assign({experimentId:e,userId:t,variantId:r,source:i})}exposure(e,t,r){return this.client.trackExposure(e,t,r)}conversion(e,t,r,i,s=1){return this.client.trackConversion({experimentId:e,userId:t,variantId:r,metricName:i,value:s})}localConversion(e,t="conversion",r=1){return this.client.trackLocalConversion(e,t,r)}hydrateFromCookies(e){this.client.hydrateFromCookies(e)}hydrateFromCookieHeader(e){this.client.hydrateFromCookieHeader(e)}injectAssignments(e){this.client.injectAssignments(e)}getAssignments(){return this.client.getAssignments()}serializeAssignmentCookie(){return this.client.serializeAssignmentCookie()}clearAssignments(){this.client.clearAssignments()}}class Y{constructor(e){this.client=e}view(e,t,r){const i=function(){const e="undefined"!=typeof window&&"undefined"!=typeof document;return{url:e?window.location.href:"",path:e?window.location.pathname:"",title:e?document.title:void 0,referrer:e?document.referrer:void 0}}(),s=e&&/^https?:\/\//i.test(e),n=s?e:i.url,a=s?new URL(e).pathname:e??i.path;return this.client.track({url:n,path:a,title:r?.title??i.title,referrer:r?.referrer??i.referrer,userId:r?.userId,sessionId:r?.sessionId,properties:t})}scroll(e,t,r){return this.client.trackScrollDepth({path:e,scrollDepth:t,timeAtDepth:r})}time(e,t){return this.client.trackTimeOnPage({path:e,duration:t})}exit(e,t,r){return this.client.trackExit(e,t,r)}autoTrack(e){return this.client.autoTrack(e)}}class Q{constructor(e){this.client=e}start(e){return this.client.start(e)}update(e,t){return this.client.update(e,t)}end(e){return this.client.end(e)}heartbeat(e){return this.client.heartbeat(e)}autoTrack(e,t){return this.client.autoTrack(e,t)}}class J{constructor(e){this.client=e}track(e,t,r){return this.client.track({eventName:e,properties:t,userId:r?.userId,sessionId:r?.sessionId})}batch(e){return this.client.trackBatch({events:e})}click(e,t,r){return this.client.trackClick({elementId:e,elementText:t,properties:r})}form(e,t,r){return this.client.trackForm({formId:e,formName:t,properties:r})}search(e,t,r){return this.client.trackSearch({query:e,category:t,properties:r})}error(e,t,r){return this.client.trackError({message:e,type:t,properties:r})}}class G{constructor(e){this.client=e}user(e,t,r){return this.client.user({userId:e,anonymousId:r,traits:t})}updateTraits(e,t){return this.client.updateTraits(e,t)}alias(e,t){return this.client.alias({previousId:e,userId:t})}group(e,t,r){return this.client.group({userId:e,groupId:t,traits:r})}}class W{constructor(e){this.client=e}define(e){return this.client.define(e)}step(e,t,r,i,s){return this.client.trackStep({funnelId:e,step:t,stepNumber:r,userId:i,properties:s})}complete(e,t,r){return this.client.trackComplete(e,t,r)}abandon(e,t,r,i){return this.client.trackAbandon(e,t,r,i)}}class X{constructor(e){this.client=e}active(e,t){return this.client.trackActivity({userId:e,properties:t})}}class Z{constructor(e){this.client=e}touchpoint(e,t,r){return this.client.trackTouchpoint({userId:e,channel:t,properties:r})}conversion(e,t,r){return this.client.recordConversion({userId:e,conversionType:t,properties:r})}captureFromUrl(e){return this.client.captureFromUrl(e)}}class ee{constructor(e){this.client=e}click(e,t,r,i,s){return this.client.trackClick({pageUrl:e,x:t,y:r,viewportWidth:i,viewportHeight:s})}movement(e,t,r){return this.client.trackMovement({pageUrl:e,path:t,viewport:r})}scroll(e,t,r,i){return this.client.trackScroll({pageUrl:e,maxScrollDepth:t,pageHeight:r,viewportHeight:i})}autoTrack(e){return this.client.autoTrack(e)}}class te{constructor(e){this.client=e}webVitals(e,t){return this.client.trackWebVitals({pageUrl:e,...t})}pageLoad(e,t){return this.client.trackPageLoad({pageUrl:e,...t})}resource(e,t,r,i){return this.client.trackResource({pageUrl:e,resourceUrl:t,resourceType:r,duration:i})}autoTrack(e){return this.client.autoTrack(e)}}class re{constructor(e){this.client=e}start(e){return this.client.start(e??{})}enable(e){return this.client.enable(e??{})}disable(){this.client.disable()}stop(e){this.client.stop(e)}flush(e){return this.client.flush(e??"manual")}identify(e){this.client.identify(e)}status(){return this.client.getStatus()}sendChunk(e,t,r){return this.client.sendChunk(e,t,r??{})}}class ie{constructor(e){this.client=e}view(e,t){return this.client.view({...e,properties:t})}impression(e,t,r){return this.client.impression({list:{listId:e,listName:t,products:r}})}click(e,t,r){return this.client.click({product:e,listId:t,position:r})}}class se{constructor(e){this.client=e}add(e,t=1,r){return this.client.addItem({product:e,quantity:t,cartId:r})}remove(e,t=1,r){return this.client.removeItem({product:e,quantity:t,cartId:r})}update(e,t,r,i){return this.client.updateItem({product:e,previousQuantity:t,newQuantity:r,cartId:i})}view(e){return this.client.view({cart:e})}}class ne{constructor(e){this.client=e}begin(e){return this.client.begin({cart:e})}step(e,t,r){return this.client.step({step:e,stepNumber:t,cart:r})}shipping(e,t){return this.client.addShipping({cart:e,shipping:t})}payment(e,t){return this.client.addPayment({cart:e,payment:t})}}class ae{constructor(e){this.client=e}complete(e){return this.client.track({order:e})}}class oe{constructor(e){this.client=e}request(e,t,r){return this.client.request(e,t,r)}approve(e,t){return this.client.approve(e,t)}deny(e,t){return this.client.deny(e,t)}complete(e,t,r,i,s,n=!1){return this.client.track({orderId:e,refundId:t,amount:r,currency:i,reason:s,isFullRefund:n})}}class ce{constructor(e){this.client=e}view(e,t,r,i){return this.client.view({promotionId:e,name:t,creative:r,position:i})}click(e,t,r,i){return this.client.click({promotionId:e,name:t,creative:r,position:i})}coupon(e,t,r,i,s,n){return this.client.couponUsed({code:e,orderId:t,discountValue:r,discountType:i,orderValueBefore:s,orderValueAfter:n})}}class ue{constructor(e){this.client=e}add(e,t){return this.client.add({product:e,wishlistId:t})}remove(e,t){return this.client.remove({product:e,wishlistId:t})}view(e){return this.client.view(e)}moveToCart(e,t){return this.client.moveToCart(e,t)}share(e,t){return this.client.share(e,t)}}class pe{constructor(e){this.client=e}acquisitionCost(e,t,r){return this.client.recordAcquisitionCost({userId:e,cost:t,channel:r})}segment(e,t){return this.client.updateSegment(e,t)}}class de{constructor(e){this.client=e}query(e,t,r){return this.client.track({query:e,resultsCount:t,...r})}click(e,t,r){return this.client.trackClick({query:e,product:t,position:r})}refine(e,t,r){return this.client.trackRefinement(e,t,r)}suggestion(e,t,r){return this.client.trackSuggestion(e,t,r)}}class le{constructor(e){this.client=e}start(e,t,r,i,s){return this.client.start({subscriptionId:e,userId:t,plan:r,mrr:i,billingCycle:s})}change(e,t,r,i,s,n,a){return this.client.change({subscriptionId:e,userId:t,previousPlan:r,newPlan:i,previousMrr:s,newMrr:n,changeType:a})}cancel(e,t,r,i,s=!1){return this.client.cancel({subscriptionId:e,userId:t,plan:r,lostMrr:i,immediate:s})}renew(e,t,r){return this.client.renew(e,t,r)}trialConverted(e,t,r,i){return this.client.trialConverted(e,t,r,i)}trialExpired(e,t){return this.client.trialExpired(e,t)}}let he=null,me=null;function ge(){return he&&me?Promise.resolve():Promise.all([s.e(137).then(s.bind(s,78)),s.e(137).then(s.bind(s,544))]).then(([e,t])=>{he=e,me=t})}const ye={handled:!1},Ie=["productId","name","brand","category","variant","price","currency","quantity","discount","coupon","position","url","imageUrl","rating","reviewCount","stockStatus","attributes"];function fe(e){return{handled:!0,value:e}}function ve(e,t){const r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function we(e,t){const r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function Se(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function _e(e,t){const r=e[t];return function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(r)?r:void 0}function ke(e,t){const r=e[t];return null!=r&&!("string"==typeof r&&0===r.length)}function be(e,t){const r={},i=new Set([...t,"domain"]);for(const[t,s]of Object.entries(e))i.has(t)||(r[t]=s);return r}function Te(e){const t=_e(e,"product");if(t)return{...t,currency:t.currency??"USD"};if(!ke(e,"productId")||!ke(e,"name")||!ke(e,"price"))return;const r={currency:"USD"};for(const t of Ie)void 0!==e[t]&&(r[t]=e[t]);return r}class xe{static init(e){if(xe._instance)return"undefined"!=typeof console&&console.warn("[FlowGrid] init() called more than once — returning existing instance."),xe._instance;if(!e?.webId||!e?.apiKey)throw new Error("FlowGrid.init: `webId` and `apiKey` are required.");e.consent&&xe.setConsent(e.consent);const t=new xe(e.webId,e.endpoint??"https://core.flow-grid.xyz",e.apiKey,e.visitorId,e.identityManager,e.transport);xe._instance=t,ge(),e.user?.userId&&t.identifyUser(e.user.userId,e.user.traits);const r=e.autoTrack,i=e.replay,s=!1===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1,engagement:!1,replay:!1}:!0===r||void 0===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1}:r;return void 0!==i&&(s.replay=i),t._autoTrackStop=t.autoTrack({...s,userId:e.user?.userId??s.userId}),t}static instance(){return xe._instance}static loadEnterprise(){return ge()}static reset(){if(xe._instance?._autoTrackStop)try{xe._instance._autoTrackStop()}catch{}xe._instance=null}constructor(e,t,r,i,s,n){this._autoTrackStop=null,this._raw=new Map,this._wrapped=new Map,this.webId=e,this.endpoint=t,this.apiKey=r,this.visitorId=i,this.identityManager=s??new d(i?{visitorId:i}:void 0),this.config=n}raw(e,t){let r=this._raw.get(e);return r||(r=new t(this.webId,this.endpoint,this.apiKey,this.visitorId,this.identityManager,this.config),this._raw.set(e,r)),r}wrap(e,t,r){let i=this._wrapped.get(e);return i||(i=new r(this.raw(e,t)),this._wrapped.set(e,i)),i}get activation(){return this.wrap("activation",l,j)}get features(){return this.wrap("features",h,z)}get prompts(){return this.wrap("prompts",m,H)}get experiments(){return this.wrap("experiments",f,K)}get pageViews(){return this.wrap("pageViews",w,Y)}get sessions(){return this.wrap("sessions",S,Q)}get events(){return this.wrap("events",_,J)}get identify(){return this.wrap("identify",k,G)}get funnels(){return this.wrap("funnels",b,W)}get retention(){return this.wrap("retention",T,X)}get attribution(){return this.wrap("attribution",x,Z)}get heatmaps(){return this.wrap("heatmaps",C,ee)}get performance(){return this.wrap("performance",E,te)}get replay(){return this.wrap("replay",P,re)}get products(){return this.wrap("products",A,ie)}get cart(){return this.wrap("cart",M,se)}get checkout(){return this.wrap("checkout",N,ne)}get purchases(){return this.wrap("purchases",B,ae)}get refunds(){return this.wrap("refunds",F,oe)}get promotions(){return this.wrap("promotions",U,ce)}get wishlist(){return this.wrap("wishlist",L,ue)}get ltv(){return this.wrap("ltv",R,pe)}get search(){return this.wrap("search",V,de)}get subscriptions(){return this.wrap("subscriptions",$,le)}_requireEnterprise(){const e=he,t=me;if(!e||!t)throw new Error("[FlowGrid] Enterprise features are still loading. await FlowGrid.loadEnterprise() before accessing enterprise namespaces directly.");return{ent:e,entT:t}}get engagement(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("engagement",e.Engagement,t.EngagementTracker)}get cohorts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("cohorts",e.Cohorts,t.CohortTracker)}get churn(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("churn",e.ChurnAnalytics,t.ChurnTracker)}get monetization(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("monetization",e.Monetization,t.MonetizationTracker)}get multiPathFunnels(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("multiPathFunnels",e.MultiPathFunnels,t.MultiPathFunnelTracker)}get support(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("support",e.SupportAnalytics,t.SupportTracker)}get acquisition(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("acquisition",e.AcquisitionAnalytics,t.AcquisitionTracker)}get paths(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("paths",e.PathAnalytics,t.PathTracker)}get alerts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("alerts",e.AlertsAnalytics,t.AlertTracker)}get security(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("security",e.SecurityAnalytics,t.SecurityTracker)}get forecasting(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("forecasting",e.Forecasting,t.ForecastingTracker)}track(e,t={},r={}){const i=this.withTrackContext(t,r),s=this.dispatchTrack(e,i,Boolean(r.domain),r.domain);return s.handled?s.value:this.events.track(e,t,r)}withTrackContext(e,t){return{...e,...void 0!==t.userId&&void 0===e.userId?{userId:t.userId}:{},...void 0!==t.sessionId&&void 0===e.sessionId?{sessionId:t.sessionId}:{}}}requireTrackProperties(e,t,r,i){const s=r.filter(e=>!ke(t,e));if(0===s.length)return!0;if(i)throw new Error(`FlowGrid.track("${e}") missing required properties: ${s.join(", ")}`);return!1}dispatchTrack(e,t,r,i){const s=[];i&&"activation"!==i||s.push(()=>this.dispatchActivationTrack(e,t,r)),i&&"feature"!==i||s.push(()=>this.dispatchFeatureTrack(e,t,r)),i&&"prompt"!==i||s.push(()=>this.dispatchPromptTrack(e,t,r)),i&&"experiment"!==i||s.push(()=>this.dispatchExperimentTrack(e,t,r)),i&&"analytics"!==i&&"funnel"!==i&&"retention"!==i&&"attribution"!==i||s.push(()=>this.dispatchAnalyticsTrack(e,t,r,i)),i&&"ecommerce"!==i||s.push(()=>this.dispatchEcommerceTrack(e,t,r)),i&&"engagement"!==i&&"churn"!==i&&"monetization"!==i&&"support"!==i&&"acquisition"!==i&&"paths"!==i&&"security"!==i&&"multiPathFunnels"!==i||s.push(()=>this.dispatchEnterpriseTrack(e,t,r,i));for(const e of s){const t=e();if(t.handled)return t}return ye}dispatchActivationTrack(e,t,r){switch(e){case"signup_completed":return this.requireTrackProperties(e,t,["userId","method"],r)?fe(this.activation.signup(ve(t,"userId"),ve(t,"method"),ve(t,"source"),be(t,["userId","method","source"]))):ye;case"onboarding_step":return this.requireTrackProperties(e,t,["userId","stepId","stepName","stepOrder","totalSteps"],r)?fe(this.activation.onboardingStep(ve(t,"userId"),ve(t,"stepId"),ve(t,"stepName"),we(t,"stepOrder"),we(t,"totalSteps"),{skipped:Se(t,"skipped"),timeSpent:we(t,"timeSpent"),properties:be(t,["userId","stepId","stepName","stepOrder","totalSteps","skipped","timeSpent"])})):ye;case"onboarding_completed":return this.requireTrackProperties(e,t,["userId","totalTimeSpent","stepsCompleted"],r)?fe(this.activation.onboardingComplete(ve(t,"userId"),we(t,"totalTimeSpent"),we(t,"stepsCompleted"),we(t,"stepsSkipped")??0)):ye;case"first_action":return this.requireTrackProperties(e,t,["userId","actionName","timeSinceSignup"],r)?fe(this.activation.firstAction(ve(t,"userId"),ve(t,"actionName"),we(t,"timeSinceSignup"),be(t,["userId","actionName","timeSinceSignup"]))):ye;default:return r?fe(this.activation.event(e,t)):ye}}dispatchFeatureTrack(e,t,r){const i={feature_viewed:"viewed",feature_used:"used",feature_completed:"completed",feature_abandoned:"abandoned"}[e]??("feature_usage"===e?t.action:void 0);return"feature_usage"===e||i?this.requireTrackProperties(e,t,["featureId","featureName"],r)?fe(this.features.client.trackUsage({...t,action:"string"==typeof i?i:"used"})):ye:r&&this.requireTrackProperties(e,t,["userId","featureName"],!0)?fe(this.features.create(ve(t,"userId"),e,ve(t,"featureName"),be(t,["userId","featureName"]))):ye}dispatchPromptTrack(e,t,r){switch(e){case"prompt_submitted":return this.requireTrackProperties(e,t,["promptId","promptType"],r)?fe(this.prompts.client.trackSubmission(t)):ye;case"prompt_response":return this.requireTrackProperties(e,t,["promptId","responseTime","completed"],r)?fe(this.prompts.client.trackResponse(t)):ye;case"prompt_feedback":return this.requireTrackProperties(e,t,["promptId","feedbackType"],r)?fe(this.prompts.client.trackFeedback(t)):ye;case"prompt_conversation":return this.requireTrackProperties(e,t,["conversationId","userId","turnCount","totalDuration"],r)?fe(this.prompts.conversation(ve(t,"conversationId"),ve(t,"userId"),we(t,"turnCount"),we(t,"totalDuration"))):ye;default:return r||e.startsWith("prompt_")?fe(this.prompts.event(e,t)):ye}}dispatchExperimentTrack(e,t,r){switch(e){case"experiment_assignment":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?fe(this.experiments.client.assign(t)):ye;case"experiment_exposure":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?fe(this.experiments.exposure(ve(t,"experimentId"),ve(t,"userId"),ve(t,"variantId"))):ye;case"experiment_conversion":return this.requireTrackProperties(e,t,["experimentId","userId","variantId","metricName"],r)?fe(this.experiments.client.trackConversion({...t,value:we(t,"value")??1})):ye;default:return(r||e.startsWith("experiment_"))&&this.requireTrackProperties(e,t,["variant"],r)?fe(this.experiments.client.track({eventName:e,variant:ve(t,"variant"),properties:be(t,["variant"])})):ye}}dispatchAnalyticsTrack(e,t,r,i){switch(e){case"click_event":return this.requireTrackProperties(e,t,["elementId","elementText"],r)?fe(this.events.client.trackClick(t)):ye;case"form_event":return this.requireTrackProperties(e,t,["formId","formName"],r)?fe(this.events.client.trackForm(t)):ye;case"search_event":return this.requireTrackProperties(e,t,["query","category"],r)?fe(this.events.client.trackSearch(t)):ye;case"error_event":return this.requireTrackProperties(e,t,["message","type"],r)?fe(this.events.client.trackError(t)):ye;case"funnel_step":return this.requireTrackProperties(e,t,["funnelId","step","stepNumber"],r)?fe(this.funnels.client.trackStep(t)):ye;case"funnel_complete":return this.requireTrackProperties(e,t,["funnelId"],r)?fe(this.funnels.complete(ve(t,"funnelId"),ve(t,"userId"),be(t,["funnelId","userId"]))):ye;case"funnel_abandon":return this.requireTrackProperties(e,t,["funnelId","lastStep"],r)?fe(this.funnels.abandon(ve(t,"funnelId"),ve(t,"lastStep"),ve(t,"userId"),ve(t,"reason"))):ye;case"user_activity":return i&&"retention"!==i?ye:this.requireTrackProperties(e,t,["userId"],r)?fe(this.retention.client.trackActivity(t)):ye;case"attribution_touchpoint":return this.requireTrackProperties(e,t,["userId","channel"],r)?fe(this.attribution.client.trackTouchpoint(t)):ye;case"attribution_conversion":return this.requireTrackProperties(e,t,["userId","conversionType"],r)?fe(this.attribution.client.recordConversion(t)):ye;default:return ye}}dispatchEcommerceTrack(e,t,r){switch(e){case"product_view":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}return fe(this.products.client.view({...i,...be(t,["product",...Ie])}))}case"product_impression":return this.requireTrackProperties(e,t,["list"],r)?fe(this.products.client.impression(t)):ye;case"product_click":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["listId","position"],r)?fe(this.products.client.click({...t,product:i})):ye}case"add_to_cart":case"remove_from_cart":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}const s={...be(t,["product",...Ie]),product:i,quantity:we(t,"quantity")??1};return fe("add_to_cart"===e?this.cart.client.addItem(s):this.cart.client.removeItem(s))}case"update_cart_item":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["previousQuantity","newQuantity"],r)?fe(this.cart.client.updateItem({...be(t,["product",...Ie]),product:i})):ye}case"view_cart":return this.requireTrackProperties(e,t,["cart"],r)?fe(this.cart.client.view(t)):ye;case"begin_checkout":return this.requireTrackProperties(e,t,["cart"],r)?fe(this.checkout.client.begin(t)):ye;case"checkout_step":return this.requireTrackProperties(e,t,["step","stepNumber","cart"],r)?fe(this.checkout.client.step(t)):ye;case"add_shipping_info":return this.requireTrackProperties(e,t,["cart","shipping"],r)?fe(this.checkout.client.addShipping(t)):ye;case"add_payment_info":return this.requireTrackProperties(e,t,["cart","payment"],r)?fe(this.checkout.client.addPayment(t)):ye;case"purchase":return this.requireTrackProperties(e,t,["order"],r)?fe(this.purchases.client.track(t)):ye;case"refund":return this.requireTrackProperties(e,t,["orderId","refundId","amount","currency"],r)?fe(this.refunds.client.track(t)):ye;case"refund_requested":return this.requireTrackProperties(e,t,["orderId"],r)?fe(this.refunds.client.request(ve(t,"orderId"),t.items,ve(t,"reason"))):ye;case"refund_approved":return this.requireTrackProperties(e,t,["refundId","approvedAmount"],r)?fe(this.refunds.client.approve(ve(t,"refundId"),we(t,"approvedAmount"))):ye;case"refund_denied":return this.requireTrackProperties(e,t,["refundId","reason"],r)?fe(this.refunds.client.deny(ve(t,"refundId"),ve(t,"reason"))):ye;case"refund_completed":return this.requireTrackProperties(e,t,["refundId","processedAmount"],r)?fe(this.refunds.client.complete(ve(t,"refundId"),we(t,"processedAmount"))):ye;case"promotion_view":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?fe(this.promotions.client.view(t)):ye;case"promotion_click":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?fe(this.promotions.client.click(t)):ye;case"coupon_used":return this.requireTrackProperties(e,t,["code","orderId","discountValue","discountType","orderValueBefore","orderValueAfter"],r)?fe(this.promotions.client.couponUsed(t)):ye;case"add_to_wishlist":case"remove_from_wishlist":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}const s={...be(t,["product",...Ie]),product:i};return fe("add_to_wishlist"===e?this.wishlist.client.add(s):this.wishlist.client.remove(s))}case"view_wishlist":return this.requireTrackProperties(e,t,["wishlist"],r)?fe(this.wishlist.client.view(_e(t,"wishlist"))):ye;case"wishlist_to_cart":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}return fe(this.wishlist.client.moveToCart(i,ve(t,"wishlistId")))}case"share_wishlist":return this.requireTrackProperties(e,t,["wishlistId","method"],r)?fe(this.wishlist.client.share(ve(t,"wishlistId"),ve(t,"method"))):ye;case"subscription_start":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr","billingCycle"],r)?fe(this.subscriptions.client.start(t)):ye;case"subscription_change":return this.requireTrackProperties(e,t,["subscriptionId","userId","previousPlan","newPlan","previousMrr","newMrr","changeType"],r)?fe(this.subscriptions.client.change(t)):ye;case"subscription_cancel":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","lostMrr"],r)?fe(this.subscriptions.client.cancel(t)):ye;case"subscription_renew":return this.requireTrackProperties(e,t,["subscriptionId","userId","mrr"],r)?fe(this.subscriptions.client.renew(ve(t,"subscriptionId"),ve(t,"userId"),_e(t,"mrr"))):ye;case"trial_converted":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr"],r)?fe(this.subscriptions.client.trialConverted(ve(t,"subscriptionId"),ve(t,"userId"),ve(t,"plan"),_e(t,"mrr"))):ye;case"trial_expired":return this.requireTrackProperties(e,t,["subscriptionId","userId"],r)?fe(this.subscriptions.client.trialExpired(ve(t,"subscriptionId"),ve(t,"userId"))):ye;case"record_acquisition_cost":return this.requireTrackProperties(e,t,["userId","cost","channel"],r)?fe(this.ltv.client.recordAcquisitionCost(t)):ye;case"update_customer_segment":return this.requireTrackProperties(e,t,["userId","newSegment"],r)?fe(this.ltv.client.updateSegment(ve(t,"userId"),ve(t,"newSegment"))):ye;case"site_search":return this.requireTrackProperties(e,t,["query","resultsCount"],r)?fe(this.search.client.track(t)):ye;case"search_result_click":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["query","position"],r)?fe(this.search.client.trackClick({...t,product:i})):ye}case"search_refinement":return this.requireTrackProperties(e,t,["originalQuery","refinedQuery","refinementType"],r)?fe(this.search.client.trackRefinement(ve(t,"originalQuery"),ve(t,"refinedQuery"),ve(t,"refinementType"))):ye;case"search_suggestion":return this.requireTrackProperties(e,t,["partialQuery","selectedSuggestion","suggestionPosition"],r)?fe(this.search.client.trackSuggestion(ve(t,"partialQuery"),ve(t,"selectedSuggestion"),we(t,"suggestionPosition"))):ye;default:return ye}}dispatchEnterpriseTrack(e,t,r,i){if(!he||!me)return ye;switch(e){case"engagement.dwell_time":case"engagement_dwell_time":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["featureId","dwellTimeMs"],r)?fe(this.engagement.client.trackDwellTime(t)):ye;case"engagement.session_depth":case"engagement_session_depth":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["sessionId","pagesVisited","featuresUsed","actionsTaken","durationMs"],r)?fe(this.engagement.client.trackSessionDepth(t)):ye;case"engagement.content_consumption":case"engagement_content_consumption":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["contentId","contentType","percentageConsumed","timeSpentMs"],r)?fe(this.engagement.client.trackContentConsumption(t)):ye;case"engagement.user_activity":case"engagement_user_activity":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["userId","activityType","durationMs"],r)?fe(this.engagement.client.trackUserActivity(t)):ye;case"churn.usage_decay":case"churn_usage_decay":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","metric","periods"],r)?fe(this.churn.client.trackUsageDecay(t)):ye;case"churn.nps":case"churn_nps":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","score"],r)?fe(this.churn.client.trackNPS(t)):ye;case"churn.churn_event":case"churn_churn_event":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","churnType"],r)?fe(this.churn.client.trackChurn(t)):ye;case"churn.prevention_action":case"churn_prevention_action":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","actionType"],r)?fe(this.churn.client.trackPreventionAction(t)):ye;case"monetization.revenue":case"monetization_revenue":return i&&"monetization"!==i?ye:this.requireTrackProperties(e,t,["userId","amount","currency","type"],r)?fe(this.monetization.client.trackRevenue(t)):ye;case"support.ticket_created":case"support_ticket_created":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","userId","subject","category","priority","channel"],r)?fe(this.support.client.trackTicket(t)):ye;case"support.ticket_updated":case"support_ticket_updated":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","status"],r)?fe(this.support.client.updateTicket(t)):ye;case"support.csat":case"support_csat":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","userId","score"],r)?fe(this.support.client.trackCSAT(t)):ye;case"support.feature_complaint":case"support_feature_complaint":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["userId","featureId","complaintType","severity"],r)?fe(this.support.client.trackFeatureComplaint(t)):ye;case"acquisition.acquired":case"acquisition_acquired":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["userId","source"],r)?fe(this.acquisition.client.trackAcquisition(t)):ye;case"acquisition.lifecycle_transition":case"acquisition_lifecycle_transition":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["userId","fromStage","toStage"],r)?fe(this.acquisition.client.trackLifecycleTransition(t)):ye;case"acquisition.campaign_spend":case"acquisition_campaign_spend":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["campaignId","amount","date"],r)?fe(this.acquisition.client.trackCampaignSpend(t)):ye;case"paths.transition":case"paths_transition":return i&&"paths"!==i?ye:this.requireTrackProperties(e,t,["userId","fromScreen","toScreen"],r)?fe(this.paths.client.trackTransition(t)):ye;case"paths.feature_sequence":case"paths_feature_sequence":return i&&"paths"!==i?ye:this.requireTrackProperties(e,t,["userId","feature","order"],r)?fe(this.paths.client.trackFeatureSequence(t)):ye;case"security.login_attempt":case"security_login_attempt":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","success"],r)?fe(this.security.client.trackLoginAttempt(t)):ye;case"security.role_change":case"security_role_change":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","changedBy","previousRole","newRole"],r)?fe(this.security.client.trackRoleChange(t)):ye;case"security.permission_change":case"security_permission_change":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","changedBy","permission","action"],r)?fe(this.security.client.trackPermissionChange(t)):ye;case"security.data_access":case"security_data_access":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","resourceType","accessType"],r)?fe(this.security.client.trackDataAccess(t)):ye;case"security.compliance_event":case"security_compliance_event":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","eventType"],r)?fe(this.security.client.trackComplianceEvent(t)):ye;case"multi_path_funnels.track_step":case"multi_path_funnels_track_step":return i&&"multiPathFunnels"!==i?ye:this.requireTrackProperties(e,t,["funnelId","step","userId"],r)?fe(this.multiPathFunnels.client.trackStep(t)):ye;case"multi_path_funnels.track_micro_conversion":case"multi_path_funnels_track_micro_conversion":return i&&"multiPathFunnels"!==i?ye:this.requireTrackProperties(e,t,["conversionId","userId"],r)?fe(this.multiPathFunnels.client.trackMicroConversion(t)):ye;default:return ye}}experiment(e,t){return this.experiments.exposure(e,t.userId,t.variant)}identifyUser(e,t,r){return this.identify.user(e,t,r)}page(e,t,r){return this.pageViews.view(e,t,r)}autoTrack(e={}){const t=[],r={userId:e.userId};if(!0===e.sessions&&t.push(this.sessions.autoTrack(r.userId?{user:{userId:r.userId}}:{})),!0===e.pageViews&&t.push(this.pageViews.autoTrack(r)),!0===e.performance||!1!==e.performance&&"object"==typeof e.performance){const i="object"==typeof e.performance?e.performance:{};t.push(this.performance.autoTrack({...i,userId:r.userId}))}if(!0===e.heatmaps||!1!==e.heatmaps&&"object"==typeof e.heatmaps){const i="object"==typeof e.heatmaps?e.heatmaps:{};t.push(this.heatmaps.autoTrack({...i,userId:r.userId}))}if(!1!==e.engagement){const i="object"==typeof e.engagement?e.engagement:{};let s=null,n=!1;ge().then(()=>{n||(s=this.engagement.client.autoTrack({...i,userId:r.userId}))}),t.push(()=>{if(n=!0,s)try{s()}catch{}})}if(!0===e.attribution&&r.userId&&this.attribution.captureFromUrl(r.userId),!1!==e.replay){const i="object"==typeof e.replay?e.replay:{};let s=null,n=!1;this.replay.start({userId:r.userId,...i}).then(e=>{if(n)try{e()}catch{}else s=e}),t.push(()=>{if(n=!0,s)try{s()}catch{}})}return()=>{for(const e of t)try{e()}catch{}}}}function Ce(){const e=xe.instance();if(!e)throw new Error("FlowGrid not initialized. Call FlowGrid.init() first.");return e}function Ee(e){return{...e,currency:e.currency??"USD"}}xe._instance=null,xe.setConsent=a.o.setConsent.bind(a.o),xe.hasConsent=a.o.hasConsent.bind(a.o);const De={init:e=>xe.init(e),instance:()=>xe.instance(),reset(){xe.reset()},setConsent(e){xe.setConsent(e)},hasConsent:e=>xe.hasConsent(e),autoTrack:e=>Ce().autoTrack(e),track:(e,t,r)=>Ce().track(e,t,r),page:(e,t,r)=>Ce().page(e,t,r),identify:(e,t,r)=>Ce().identifyUser(e,t,r),experiment:(e,t)=>Ce().experiment(e,t),productView:(e,t)=>Ce().products.view(Ee(e),t),addToCart:(e,t=1,r)=>Ce().cart.add(Ee(e),t,r),purchase:e=>Ce().purchases.complete(function(e){const t=e.currency??"USD",r=e.items.map(e=>({...e,currency:e.currency??t,quantity:e.quantity,lineTotal:e.price*e.quantity})),i=e.subtotal??r.reduce((e,t)=>e+t.lineTotal,0);return{orderId:e.orderId,items:r,subtotal:i,discountTotal:e.discountTotal??0,shippingTotal:e.shippingTotal??0,taxTotal:e.taxTotal??0,total:e.total,currency:t}}(e))};"undefined"!=typeof window&&(window.FlowGrid=De,window.flowgrid=De);const qe=De;return n})());
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.flowgrid=t():e.flowgrid=t()}(this,()=>(()=>{"use strict";var e,t,r={748(e,t,r){r.d(t,{o:()=>i});class i{constructor(e,t,r,i,s,n){if(!e?.trim()||!t?.trim())throw new Error("SDK init failed: webId and endpoint are required.");this.webId=e.trim(),this.endpoint=this.normalizeEndpoint(t),this.apiKey=r,this.identityManager=s,this.visitorId=i??"",this.transportConfig={botDetection:n?.botDetection??"block",respectDNT:n?.respectDNT??!0,sampleRate:n?.sampleRate??1},this.drainEventBuffer()}static setConsent(e){Object.assign(i.consent,e)}static hasConsent(e){return i.consent[e]??!1}static isLikelyBot(){return!("undefined"==typeof navigator||!navigator.webdriver&&!/bot|crawl|spider|headless|phantom|puppeteer/i.test(navigator.userAgent))}isDNTEnabled(){return"undefined"!=typeof navigator&&(!!navigator.globalPrivacyControl||"1"===navigator.doNotTrack)}static getDeviceContext(){if("undefined"==typeof window||"undefined"==typeof navigator)return{};const e=window.location,t="undefined"!=typeof document?document:void 0;return{_screen_width:window.screen?.width,_screen_height:window.screen?.height,_device_type:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",_language:navigator.language,_url:e?.href,_page:e?.pathname,_referrer:t?.referrer||void 0,_title:t?.title||void 0}}sendViaBeacon(e,t={}){if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;const r=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",s=t.type||"event",n=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(s)}`,a=JSON.stringify({web_id:this.webId,visitor_id:r,event_name:e,properties:{...t,...i.getDeviceContext()}});return navigator.sendBeacon(n,new Blob([a],{type:"application/json"}))}async postRaw(e,t,r={}){if(!1===i.consent.analytics)return;if(!1!==this.transportConfig.respectDNT&&this.isDNTEnabled())return;const s=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(e)}`,n=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",a=JSON.stringify({web_id:this.webId,visitor_id:n,...t}),o=!0===r.useBeacon,c=a.length,u=o&&c<=6e4;if(o&&c>6e4){const t=JSON.stringify({...JSON.parse(a),api_key:this.apiKey});try{"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:"application/json"}))||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} beacon rejected (payload ${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} beacon error:`,t)}return}try{const t=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:a,...u?{keepalive:!0}:{}});t.ok||"undefined"==typeof console||console.warn(`[Flowgrid] ${e} rejected: ${t.status} ${t.statusText} (${c} bytes)`)}catch(t){"undefined"!=typeof console&&console.warn(`[Flowgrid] ${e} network error (${c} bytes):`,t)}}bufferEvent(e,t,r){if("undefined"!=typeof localStorage)try{const s=localStorage.getItem(i.EVENT_BUFFER_KEY),n=s?JSON.parse(s):[];if(n.length>=i.MAX_BUFFER_EVENTS)return;const a=JSON.stringify([...n,{url:e,method:t,body:r}]);if((new TextEncoder).encode(a).length>i.MAX_BUFFER_SIZE)return;n.push({url:e,method:t,body:r}),localStorage.setItem(i.EVENT_BUFFER_KEY,JSON.stringify(n))}catch{}}drainEventBuffer(){if("undefined"!=typeof localStorage)try{const e=localStorage.getItem(i.EVENT_BUFFER_KEY);if(!e)return;const t=JSON.parse(e);localStorage.removeItem(i.EVENT_BUFFER_KEY);for(const e of t)fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:e.body}).catch(()=>{})}catch{}}async init(e,t={},r="POST"){if(!i.hasConsent("analytics"))return{};if(this.transportConfig.respectDNT&&this.isDNTEnabled())return{};if("block"===this.transportConfig.botDetection&&i.isLikelyBot())return{};this.validateInput(e,t),"tag"===this.transportConfig.botDetection&&i.isLikelyBot()&&(t={...t,_bot:!0});const s={...i.getDeviceContext(),...t},n=s.type||"event",a=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(n)}`,o=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",c=JSON.stringify({web_id:this.webId,visitor_id:o,event_name:e,properties:s});return this.executeRequest(a,r,"GET"===r?void 0:c)}async initFeature(e,t){if(this.validateInput(e,t),!t.type)throw new Error("Feature events must include a type property");const r=`${this.endpoint}/api/v1/sdk/functions?call=${encodeURIComponent(t.type)}`,i=this.identityManager?this.identityManager.getVisitorId():this.visitorId??"",s=JSON.stringify({web_id:this.webId,visitor_id:i,event_name:e,properties:t});return this.executeRequest(r,"POST",s)}async executeRequest(e,t,r,s){let n=0;for(;n<=i.MAX_RETRIES;){const a=new AbortController,o=setTimeout(()=>a.abort(),i.TIMEOUT_MS);try{const c=await fetch(e,{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...s},body:r,signal:a.signal});if(clearTimeout(o),c.status>=500&&n<i.MAX_RETRIES){n++,await this.backoff(n);continue}if(!c.ok){const e=await this.safeRead(c);throw new Error(`SDK request failed (${c.status} ${c.statusText}) ${e}`)}return await c.json()}catch(s){if(clearTimeout(o),s instanceof Error&&("AbortError"===s.name||s.message.includes("fetch"))&&n<i.MAX_RETRIES){n++,await this.backoff(n);continue}if(n>=i.MAX_RETRIES&&(r&&"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(e,new Blob([r],{type:"application/json"}))||this.bufferEvent(e,t,r)),s instanceof Error&&"AbortError"===s.name)throw new Error("SDK request timed out");throw s}}throw new Error("SDK request exhausted retries without resolution")}backoff(e){const t=Math.min(1e3*Math.pow(2,e-1),3e4),r=Math.random()*t;return new Promise(e=>setTimeout(e,r))}validateInput(e,t){if(!e||"string"!=typeof e||!e.trim())throw new Error("Event name must be a non-empty string");if(e.length>100)throw new Error("Event name must be less than 100 characters");let r;try{r=JSON.stringify({web_id:this.webId,visitor_id:this.visitorId??"",event_name:e,properties:t})}catch{throw new Error("Properties must be JSON serializable")}if((new TextEncoder).encode(r).length>i.MAX_PAYLOAD_SIZE)throw new Error("Event payload too large (max 10KB)");const s=["password","token","secret","apikey","authorization"],n=r.toLowerCase();for(const e of s)n.includes(e)&&console.warn(`SDK Warning: Properties may contain sensitive data (${e}).`)}normalizeEndpoint(e){let t=e.trim();return t.startsWith("http://")||t.startsWith("https://")||(t=`https://${t}`),t.replace(/\/+$/,"")}async safeRead(e){try{return await e.text()}catch{return""}}}i.MAX_PAYLOAD_SIZE=1e4,i.TIMEOUT_MS=1e4,i.MAX_RETRIES=3,i.MAX_BUFFER_EVENTS=100,i.MAX_BUFFER_SIZE=5e4,i.EVENT_BUFFER_KEY="fg_event_buffer",i.consent={analytics:!0,marketing:!0}},547(e,t,r){function i(){return"undefined"!=typeof window?window:void 0}function s(){return"undefined"!=typeof document?document:void 0}function n(){return"undefined"!=typeof window&&"undefined"!=typeof document}function a(...e){return()=>{for(const t of e)if("function"==typeof t)try{t()}catch{}}}r.d(t,{Bd:()=>n,YE:()=>s,vs:()=>a,zk:()=>i})}},i={};function s(e){var t=i[e];if(void 0!==t)return t.exports;var n=i[e]={exports:{}};return r[e](n,n.exports,s),n.exports}s.m=r,s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,r)=>(s.f[r](e,t),t),[])),s.u=e=>({137:"flowgrid-enterprise",717:"flowgrid-vitals",897:"flowgrid-replay"}[e]+".flowgrid.chunk.js"),s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="flowgrid:",s.l=(r,i,n,a)=>{if(e[r])e[r].push(i);else{var o,c;if(void 0!==n)for(var u=document.getElementsByTagName("script"),p=0;p<u.length;p++){var d=u[p];if(d.getAttribute("src")==r||d.getAttribute("data-webpack")==t+n){o=d;break}}o||(c=!0,(o=document.createElement("script")).charset="utf-8",s.nc&&o.setAttribute("nonce",s.nc),o.setAttribute("data-webpack",t+n),o.src=r),e[r]=[i];var l=(t,i)=>{o.onerror=o.onload=null,clearTimeout(h);var s=e[r];if(delete e[r],o.parentNode&&o.parentNode.removeChild(o),s&&s.forEach(e=>e(i)),t)return t(i)},h=setTimeout(l.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=l.bind(null,o.onerror),o.onload=l.bind(null,o.onload),c&&document.head.appendChild(o)}},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),(()=>{var e={792:0};s.f.j=(t,r)=>{var i=s.o(e,t)?e[t]:void 0;if(0!==i)if(i)r.push(i[2]);else{var n=new Promise((r,s)=>i=e[t]=[r,s]);r.push(i[2]=n);var a=s.p+s.u(t),o=new Error;s.l(a,r=>{if(s.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var n=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,i[1](o)}},"chunk-"+t,t)}};var t=(t,r)=>{var i,n,[a,o,c]=r,u=0;if(a.some(t=>0!==e[t])){for(i in o)s.o(o,i)&&(s.m[i]=o[i]);c&&c(s)}for(t&&t(r);u<a.length;u++)n=a[u],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},r=this.webpackChunkflowgrid=this.webpackChunkflowgrid||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var n={};s.r(n),s.d(n,{FlowGrid:()=>xe,default:()=>qe});var a=s(748);function o(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}const c="fg_visitor_id",u="fg_session_id",p="fg_session_touch";class d{constructor(e){this.visitorId="",this.sessionId="",this.memoryStore={},this.config={visitorId:e?.visitorId??"",cookieDomain:e?.cookieDomain??"",visitorMaxAgeDays:e?.visitorMaxAgeDays??365,sessionTimeoutMinutes:e?.sessionTimeoutMinutes??30,storage:e?.storage??(this.detectBrowser()?"cookie":"memory"),serverCookies:e?.serverCookies,compat:e?.compat??!0},this.visitorId=this.resolveVisitorId(),this.sessionId=""}getVisitorId(){return this.visitorId||(this.visitorId=this.resolveVisitorId()),this.visitorId}getSessionId(){if("memory"===this.config.storage)return this.getMemorySessionId();if(!this.detectBrowser())return this.getMemorySessionId();try{const e=sessionStorage.getItem(u),t=sessionStorage.getItem(p);if(e&&t){if(Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return sessionStorage.setItem(p,String(Date.now())),this.sessionId=e,e}const r=this.generateSessionId();return sessionStorage.setItem(u,r),sessionStorage.setItem(p,String(Date.now())),this.sessionId=r,r}catch{return this.getMemorySessionId()}}setVisitorId(e){this.visitorId=e,this.persistVisitorId(e)}clearSession(){if(this.sessionId="",delete this.memoryStore[u],delete this.memoryStore[p],this.detectBrowser())try{sessionStorage.removeItem(u),sessionStorage.removeItem(p)}catch{}}clearAll(){if(this.visitorId="",this.sessionId="",this.memoryStore={},this.detectBrowser())try{this.deleteCookie(this.visitorCookieName),this.deleteCookie(c),localStorage.removeItem(this.visitorCookieName),localStorage.removeItem(c),localStorage.removeItem("fg_exp_assignments"),sessionStorage.removeItem(u),sessionStorage.removeItem(p)}catch{}}isBrowser(){return this.detectBrowser()}get visitorCookieName(){return this.config.compat?"visitor_id":c}resolveVisitorId(){if(this.config.visitorId)return this.config.visitorId;if(this.detectBrowser()){const e=function(){try{return o("visitor_id")||localStorage.getItem("visitor_id")}catch{return o("visitor_id")}}();if(e){const t=this.readCookie(c)||this.readLocalStorage(c);return t&&t!==e&&this.removeLegacyCookie(),this.persistVisitorId(e),e}}if(this.config.compat){const e=this.readCookie(c)||this.readLocalStorage(c);if(e)return this.persistVisitorId(e),this.removeLegacyCookie(),e}const e=this.readCookie(this.visitorCookieName);if(e)return e;if(this.detectBrowser())try{const e=localStorage.getItem(this.visitorCookieName);if(e)return e}catch{}if(this.config.serverCookies){const e=this.readServerCookie(this.visitorCookieName);if(e)return e}if(this.memoryStore[this.visitorCookieName])return this.memoryStore[this.visitorCookieName];const t=this.generateVisitorId();return this.persistVisitorId(t),t}readLocalStorage(e){if(!this.detectBrowser())return null;try{return localStorage.getItem(e)}catch{return null}}removeLegacyCookie(){if(this.deleteCookie(c),this.detectBrowser())try{localStorage.removeItem(c)}catch{}}persistVisitorId(e){const t=this.visitorCookieName;if("memory"!==this.config.storage)if(this.detectBrowser()){this.writeCookie(t,e,this.config.visitorMaxAgeDays);try{localStorage.setItem(t,e)}catch{}}else this.memoryStore[t]=e;else this.memoryStore[t]=e}getMemorySessionId(){const e=this.memoryStore[u],t=this.memoryStore[p];if(e&&t&&Date.now()-parseInt(t,10)<60*this.config.sessionTimeoutMinutes*1e3)return this.memoryStore[p]=String(Date.now()),this.sessionId=e,e;const r=this.generateSessionId();return this.memoryStore[u]=r,this.memoryStore[p]=String(Date.now()),this.sessionId=r,r}readCookie(e){return this.config.serverCookies?this.readServerCookie(e):this.detectBrowser()?o(e):null}readServerCookie(e){if(!this.config.serverCookies)return null;const t=this.config.serverCookies.get(e);return t?"object"==typeof t&&"value"in t?t.value||null:"string"==typeof t&&t||null:null}writeCookie(e,t,r){if(!this.detectBrowser())return;const i=24*r*60*60,s=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"",n="https:"===location.protocol?"; Secure":"";document.cookie=`${e}=${encodeURIComponent(t)}; Path=/; Max-Age=${i}; SameSite=Lax${n}${s}`}deleteCookie(e){if(!this.detectBrowser())return;const t=this.config.cookieDomain?`; Domain=${this.config.cookieDomain}`:"";document.cookie=`${e}=; Path=/; Max-Age=0${t}`}generateVisitorId(){return`fg_${this.uuidV4()}`}generateSessionId(){return`fgs_${Date.now()}_${this.randomHex(8)}`}uuidV4(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}randomHex(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}detectBrowser(){return"undefined"!=typeof window&&"undefined"!=typeof document}}class l extends a.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"activation",timestamp:(new Date).toISOString()})}async trackOnboardingStep(e){return await this.init("onboarding_step",{type:"activation",subtype:"onboarding_step",userId:e.userId,stepId:e.stepId,stepName:e.stepName,stepOrder:e.stepOrder,totalSteps:e.totalSteps,progress:Math.round(e.stepOrder/e.totalSteps*100),timeSpent:e.timeSpent,skipped:e.skipped||!1,...e.properties,timestamp:(new Date).toISOString()})}async completeOnboarding(e,t,r,i){return await this.init("onboarding_completed",{type:"activation",subtype:"onboarding_complete",userId:e,totalTimeSpent:t,stepsCompleted:r,stepsSkipped:i,completionRate:Math.round(r/(r+i)*100),timestamp:(new Date).toISOString()})}async trackFirstAction(e){return await this.init("first_action",{type:"activation",subtype:"first_action",userId:e.userId,actionName:e.actionName,timeSinceSignup:e.timeSinceSignup,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async trackSignup(e,t,r,i){return await this.init("signup_completed",{type:"activation",subtype:"signup",userId:e,method:t,source:r,...i,timestamp:(new Date).toISOString()})}}class h extends a.o{async create(e){return await this.init("create_tracking",{type:"feature_usage",subtype:"create_custom",userId:e.userId,category:e.category,action:e.action,...e.properties,timestamp:(new Date).toISOString()})}async trackUsage(e){return await this.init("feature_usage",{type:"feature_usage",subtype:e.action,featureId:e.featureId,featureName:e.featureName,userId:e.userId,action:e.action,duration:e.duration,success:e.success,category:e.category,...e.properties,timestamp:(new Date).toISOString()})}}class m extends a.o{async create(e){return await this.init(e.eventName,{...e.properties,type:"prompt",timestamp:(new Date).toISOString()})}async trackSubmission(e){return await this.init("prompt_submitted",{type:"prompt",subtype:"submission",promptId:e.promptId,userId:e.userId,promptType:e.promptType,model:e.model,inputTokens:e.inputTokens,conversationId:e.conversationId,...e.properties,timestamp:(new Date).toISOString()})}async trackResponse(e){return await this.init("prompt_response",{type:"prompt",subtype:"response",promptId:e.promptId,responseTime:e.responseTime,outputTokens:e.outputTokens,completed:e.completed,error:e.error,qualityScore:e.qualityScore,timestamp:(new Date).toISOString()})}async trackFeedback(e){return await this.init("prompt_feedback",{type:"prompt",subtype:"feedback",promptId:e.promptId,userId:e.userId,feedbackType:e.feedbackType,rating:e.rating,comment:e.comment,timestamp:(new Date).toISOString()})}async trackConversation(e,t,r,i){return await this.init("prompt_conversation",{type:"prompt",subtype:"conversation",conversationId:e,userId:t,turnCount:r,totalDuration:i,timestamp:(new Date).toISOString()})}}function g(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=16777619*t>>>0;return t}const y="fg_exp_assignments",I="fg_exp_assignments";class f extends a.o{constructor(){super(...arguments),this.experiments={},this.assignments={}}parseAssignmentCookie(e){if(!e)return{};try{const t=decodeURIComponent(e),r=JSON.parse(t);return r&&"object"==typeof r?r:{}}catch{return{}}}readAssignmentCookie(){return this.parseAssignmentCookie(o(I))}writeAssignmentCookie(){try{if("undefined"==typeof document)return;const e=encodeURIComponent(JSON.stringify(this.assignments)),t=31536e3,r="Lax",i="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";document.cookie=`${I}=${e}; Path=/; Max-Age=${t}; SameSite=${r}${i}`}catch{}}loadAssignments(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(y);if(e){const t=JSON.parse(e);if(t&&"object"==typeof t)return t}}}catch{}const e=this.readAssignmentCookie();return Object.keys(e).length>0?e:{}}saveAssignments(){try{"undefined"!=typeof localStorage&&localStorage.setItem(y,JSON.stringify(this.assignments))}catch{}this.writeAssignmentCookie()}injectAssignments(e){this.assignments={...this.assignments,...e}}getAssignments(){return{...this.assignments}}hydrateFromCookies(e){const t=e.get(I),r="string"==typeof t?t:t?.value??null,i=this.parseAssignmentCookie(r??null);Object.keys(i).length>0&&this.injectAssignments(i)}hydrateFromCookieHeader(e){if(!e)return;const t=e.split(/;\s*/),r=`${I}=`,i=t.find(e=>e.startsWith(r));if(!i)return;const s=this.parseAssignmentCookie(i.slice(r.length));Object.keys(s).length>0&&this.injectAssignments(s)}serializeAssignmentCookie(){const e=encodeURIComponent(JSON.stringify(this.assignments));return`${I}=${e}; Path=/; Max-Age=31536000; SameSite=Lax`}clearAssignments(){this.assignments={};try{"undefined"!=typeof localStorage&&localStorage.removeItem(y)}catch{}try{"undefined"!=typeof document&&(document.cookie=`${I}=; Path=/; Max-Age=0; SameSite=Lax`)}catch{}}getOrCreateAnonId(){try{if("undefined"!=typeof localStorage){const e=localStorage.getItem(f.ANON_ID_KEY);if(e)return e;const t="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});return localStorage.setItem(f.ANON_ID_KEY,t),t}}catch{}return"anon_"+g(String(Math.random())).toString(36)}deterministicAssign(e,t,r){const i=g(e+t);let s=0;for(const e of r)s+=e.weight;const n=i%1e4/1e4*s;let a=0;for(const e of r)if(a+=e.weight,n<a)return e.id;return r[r.length-1].id}assignVariant(e,t){this.assignments=this.loadAssignments();const r=this.assignments[e];if(r&&t.some(e=>e.id===r))return;const i=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId(),s=this.deterministicAssign(i,e,t);this.assignments[e]=s,this.saveAssignments(),this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e,userId:i,variantId:s,source:"random",assignmentSource:"sdk_init",timestamp:(new Date).toISOString()}).catch(()=>{})}async verifyExperiments(e){const t={web_id:this.webId,experiments:e.map(e=>({experiment_id:e.id,variants:e.variants,properties:e.properties||{}}))};try{const e=await fetch(`${this.endpoint}/api/v1/experiments/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await e.json();if(r.ok&&Array.isArray(r.data))for(const e of r.data)"error"!==e.action&&(this.experiments[e.experiment_id]={variants:e.variants,properties:e.properties??{},verified:!0},this.assignVariant(e.experiment_id,e.variants))}catch{for(const t of e)this.experiments[t.id]={variants:t.variants,properties:t.properties||{},verified:!1},this.assignVariant(t.id,t.variants)}}async initExperiments(e){this.assignments=this.loadAssignments(),e.length>0&&await this.verifyExperiments(e)}getLocalVariant(e){return this.assignments=this.loadAssignments(),this.assignments[e]??null}async trackLocalConversion(e,t="conversion",r=1){const i=this.getLocalVariant(e);if(!i)return;const s=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e,userId:s,variantId:i,metricName:t,value:r,timestamp:(new Date).toISOString()})}async trackLocalExposure(e){const t=this.getLocalVariant(e);if(!t)return;const r=this.identityManager?.getVisitorId?.()||this.visitorId||this.getOrCreateAnonId();await this.trackExposure(e,r,t)}async track(e){return await this.init(e.eventName,{...e.properties,type:"experiment",subtype:"custom",variant:e.variant,timestamp:(new Date).toISOString()})}async define(e){return await this.init("experiment_definition",{type:"experiment",subtype:"definition",...e,timestamp:(new Date).toISOString()})}async assign(e){return await this.init("experiment_assignment",{type:"experiment",subtype:"assignment",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,source:e.source||"random",timestamp:(new Date).toISOString()})}async trackConversion(e){return await this.init("experiment_conversion",{type:"experiment",subtype:"conversion",experimentId:e.experimentId,userId:e.userId,variantId:e.variantId,metricName:e.metricName,value:e.value,timestamp:(new Date).toISOString()})}async trackExposure(e,t,r){return await this.init("experiment_exposure",{type:"experiment",subtype:"exposure",experimentId:e,userId:t,variantId:r,timestamp:(new Date).toISOString()})}}f.ANON_ID_KEY="fg_anon_id";var v=s(547);class w extends a.o{async track(e){return await this.init("page_view",{type:"page_view",url:e.url,path:e.path,title:e.title||"",referrer:e.referrer||"",userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackScrollDepth(e){return await this.init("scroll_depth",{type:"scroll_depth",path:e.path,scrollDepth:Math.min(100,Math.max(0,e.scrollDepth)),timeAtDepth:e.timeAtDepth,timestamp:(new Date).toISOString()})}async trackTimeOnPage(e){return await this.init("time_on_page",{type:"time_on_page",path:e.path,duration:e.duration,engaged:e.engaged??!1,timestamp:(new Date).toISOString()})}async trackExit(e,t,r){return await this.init("page_exit",{type:"page_exit",path:e,duration:t,scrollDepth:r,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=(0,v.YE)();let i=t.location.pathname,s=Date.now(),n=0;const a=new Set,o=()=>{this.track({url:t.location.href,path:t.location.pathname,title:r.title,referrer:r.referrer,userId:e.userId,sessionId:e.sessionId})},c=()=>{const e=Math.round((Date.now()-s)/1e3);e<=0||this.trackTimeOnPage({path:i,duration:e,engaged:n>10})},u=()=>{t.location.pathname!==i&&(c(),i=t.location.pathname,s=Date.now(),n=0,a.clear(),o())},p=t.history.pushState,d=t.history.replaceState;t.history.pushState=function(...e){const r=p.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r},t.history.replaceState=function(...e){const r=d.apply(this,e);return t.dispatchEvent(new Event("flowgrid:locationchange")),r};const l=()=>u(),h=()=>u();t.addEventListener("popstate",l),t.addEventListener("flowgrid:locationchange",h);const m=()=>{const e=r.documentElement,s=t.scrollY||e.scrollTop,o=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(s/o*100));c>n&&(n=c);for(const e of[25,50,75,100])c>=e&&!a.has(e)&&(a.add(e),this.trackScrollDepth({path:i,scrollDepth:e}))};t.addEventListener("scroll",m,{passive:!0});const g=()=>{"hidden"===r.visibilityState&&c()};return r.addEventListener("visibilitychange",g),t.addEventListener("pagehide",c),o(),(0,v.vs)(()=>t.removeEventListener("popstate",l),()=>t.removeEventListener("flowgrid:locationchange",h),()=>t.removeEventListener("scroll",m),()=>r.removeEventListener("visibilitychange",g),()=>t.removeEventListener("pagehide",c),()=>{t.history.pushState=p,t.history.replaceState=d})}}class S extends a.o{async start(e={}){return await this.init("session_start",{type:"session_start",user:e.user,device:e.device,location:e.location,source:e.source||e.utm?.utmSource,medium:e.medium||e.utm?.utmMedium,campaign:e.campaign||e.utm?.utmCampaign,utm:e.utm,landingPage:e.landingPage||("undefined"!=typeof window?window.location.href:""),referrer:e.referrer||("undefined"!=typeof document?document.referrer:""),...e.properties,timestamp:(new Date).toISOString()})}async update(e,t){return await this.init("session_update",{type:"session_update",sessionId:e,...t,timestamp:(new Date).toISOString()})}async end(e){return await this.init("session_end",{type:"session_end",sessionId:e,timestamp:(new Date).toISOString()})}async heartbeat(e){return await this.init("session_heartbeat",{type:"session_heartbeat",sessionId:e,timestamp:(new Date).toISOString()})}autoTrack(e={},t={}){if(!(0,v.Bd)())return()=>{};const r=(0,v.zk)(),i=(0,v.YE)(),s=t.heartbeatMs??3e4,n="flowgrid:sessionId";let a;try{a=r.sessionStorage.getItem(n)||void 0}catch{}const o=a?Promise.resolve(a):this.start(e).then(e=>{a=e.response.sessionId;try{r.sessionStorage.setItem(n,a)}catch{}return a}).catch(()=>{}),c=r.setInterval(()=>{a&&"visible"===i.visibilityState&&this.heartbeat(a)},s),u=()=>{a&&this.end(a)};return r.addEventListener("pagehide",u),(0,v.vs)(()=>r.clearInterval(c),()=>r.removeEventListener("pagehide",u),()=>{o.then(()=>{a&&this.end(a)})},()=>{try{r.sessionStorage.removeItem(n)}catch{}})}}class _ extends a.o{async track(e){return await this.init("custom_event",{type:"custom_event",eventName:e.eventName,category:e.category||"general",action:e.action,label:e.label,value:e.value,nonInteraction:e.nonInteraction||!1,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackBatch(e){const t=e.events.map(e=>({...e,timestamp:(new Date).toISOString()}));return await this.init("batch_events",{type:"batch_events",events:t,count:t.length,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("click_event",{type:"click_event",...e,timestamp:(new Date).toISOString()})}async trackForm(e){return await this.init("form_event",{type:"form_event",...e,timestamp:(new Date).toISOString()})}async trackSearch(e){return await this.init("search_event",{type:"search_event",query:e.query,category:e.category,resultsCount:e.resultsCount,resultClicked:e.resultClicked,clickedPosition:e.clickedPosition,filters:e.filters,timestamp:(new Date).toISOString()})}async trackError(e){return await this.init("error_event",{type:"error_event",message:e.message,stack:e.stack,errorType:e.type,fatal:e.fatal||!1,context:e.context,userAction:e.userAction,timestamp:(new Date).toISOString()})}}class k extends a.o{async user(e){return await this.init("identify_user",{type:"identify",userId:e.userId,anonymousId:e.anonymousId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async updateTraits(e,t){return await this.init("update_traits",{type:"update_traits",userId:e,traits:t,timestamp:(new Date).toISOString()})}async alias(e){return await this.init("alias_user",{type:"alias",previousId:e.previousId,userId:e.userId,timestamp:(new Date).toISOString()})}async group(e){return await this.init("group_user",{type:"group",userId:e.userId,groupId:e.groupId,traits:e.traits||{},timestamp:(new Date).toISOString()})}async reset(e){return await this.init("reset_identity",{type:"reset",userId:e,timestamp:(new Date).toISOString()})}}class b extends a.o{async define(e){return await this.init("define_funnel",{type:"define_funnel",funnelId:e.funnelId,name:e.name,description:e.description,steps:e.steps,timestamp:(new Date).toISOString()})}async trackStep(e){return await this.init("funnel_step",{type:"funnel_step",funnelId:e.funnelId,step:e.step,stepNumber:e.stepNumber,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackComplete(e,t,r){return await this.init("funnel_complete",{type:"funnel_complete",funnelId:e,userId:t,...r,timestamp:(new Date).toISOString()})}async trackAbandon(e,t,r,i){return await this.init("funnel_abandon",{type:"funnel_abandon",funnelId:e,lastStep:t,userId:r,reason:i,timestamp:(new Date).toISOString()})}async analyze(e,t){return await this.init("analyze_funnel",{type:"query",funnelId:e,filter:t||{range:"last30days"},timestamp:(new Date).toISOString()})}async compare(e,t,r){return await this.init("compare_funnel",{type:"query",funnelId:e,baselineFilter:t,comparisonFilter:r,timestamp:(new Date).toISOString()})}async list(){return await this.init("list_funnels",{type:"query",timestamp:(new Date).toISOString()})}}class T extends a.o{async trackActivity(e){return await this.init("user_activity",{type:"user_activity",userId:e.userId,action:e.action||"active",sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async trackLifecycleChange(e,t,r){return await this.init("lifecycle_change",{type:"lifecycle_change",userId:e,stage:t,previousStage:r,timestamp:(new Date).toISOString()})}}class x extends a.o{async trackTouchpoint(e){return await this.init("attribution_touchpoint",{type:"attribution_touchpoint",userId:e.userId,channel:e.channel,campaign:e.campaign,medium:e.medium,source:e.source,content:e.content,term:e.term,referrer:e.referrer,landingPage:e.landingPage,...e.properties,timestamp:(new Date).toISOString()})}async recordConversion(e){return await this.init("attribution_conversion",{type:"attribution_conversion",userId:e.userId,conversionType:e.conversionType,value:e.value,conversionId:e.conversionId,...e.properties,timestamp:(new Date).toISOString()})}captureFromUrl(e){if(!(0,v.Bd)())return null;const t=(0,v.zk)(),r=(0,v.YE)();if(!t||!r)return null;const i=new URLSearchParams(t.location.search),s={utmSource:i.get("utm_source")??void 0,utmMedium:i.get("utm_medium")??void 0,utmCampaign:i.get("utm_campaign")??void 0,utmTerm:i.get("utm_term")??void 0,utmContent:i.get("utm_content")??void 0},n=r.referrer||void 0;if(!(s.utmSource||s.utmMedium||s.utmCampaign||n))return null;const a={userId:e,channel:s.utmSource||(n?"referral":"direct"),campaign:s.utmCampaign,medium:s.utmMedium,source:s.utmSource,content:s.utmContent,term:s.utmTerm,referrer:n,landingPage:t.location.pathname};return this.trackTouchpoint(a),a}}class C extends a.o{constructor(){super(...arguments),this.lastMovementTime=0,this.lastScrollTime=0}async trackClick(e){return await this.init("heatmap_click",{type:"heatmap_click",pageUrl:e.pageUrl,x:e.x,y:e.y,normalizedX:e.x/e.viewportWidth,normalizedY:e.y/e.viewportHeight,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,elementSelector:e.elementSelector,elementText:e.elementText?.substring(0,50),userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackMovement(e){const t=Date.now();return t-this.lastMovementTime<C.MOVEMENT_THROTTLE_MS?{eventName:"heatmap_movement",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastMovementTime=t,await this.init("heatmap_movement",{type:"heatmap_movement",pageUrl:e.pageUrl,path:e.path,viewport:e.viewport,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackScroll(e){const t=Date.now();return t-this.lastScrollTime<C.SCROLL_THROTTLE_MS?{eventName:"heatmap_scroll",properties:{},response:{recorded:!1,interactionId:""},timestamp:(new Date).toISOString()}:(this.lastScrollTime=t,await this.init("heatmap_scroll",{type:"heatmap_scroll",pageUrl:e.pageUrl,maxScrollDepth:e.maxScrollDepth,pageHeight:e.pageHeight,viewportHeight:e.viewportHeight,timeAtDepths:e.timeAtDepths,sessionId:e.sessionId,timestamp:(new Date).toISOString()}))}async trackRageClick(e,t,r,i){return await this.init("heatmap_rage_click",{type:"heatmap_rage_click",pageUrl:e,x:t,y:r,clickCount:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=(0,v.YE)(),i=r=>{const i=r.target;var s;this.trackClick({pageUrl:t.location.pathname,x:r.clientX,y:r.clientY+t.scrollY,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,elementSelector:(s=i,s?s.id?`#${s.id}`:`${s.tagName.toLowerCase()}${s.className&&"string"==typeof s.className?"."+s.className.trim().split(/\s+/).slice(0,2).join("."):""}`:""),elementText:(i?.textContent||"").trim().slice(0,50),userId:e.userId,sessionId:e.sessionId})};r.addEventListener("click",i,{capture:!0,passive:!0});let s=0,n=!1;const a=()=>{n=!1;const i=r.documentElement;this.trackScroll({pageUrl:t.location.pathname,maxScrollDepth:s,pageHeight:i.scrollHeight,viewportHeight:t.innerHeight,sessionId:e.sessionId})},o=()=>{const e=r.documentElement,i=t.scrollY||e.scrollTop,o=Math.max(1,e.scrollHeight-t.innerHeight),c=Math.min(100,Math.round(i/o*100));c>s&&(s=c),n||(n=!0,t.addEventListener("pagehide",a,{once:!0}))};let c;if(t.addEventListener("scroll",o,{passive:!0}),e.movement){let i=[];const s=Date.now(),n=r=>{if(i.push({x:r.clientX,y:r.clientY,t:Date.now()-s}),i.length>=50){const r=i;i=[],this.trackMovement({pageUrl:t.location.pathname,path:r,viewport:{width:t.innerWidth,height:t.innerHeight},sessionId:e.sessionId})}};r.addEventListener("mousemove",n,{passive:!0}),c=()=>r.removeEventListener("mousemove",n)}return(0,v.vs)(()=>r.removeEventListener("click",i,{capture:!0}),()=>t.removeEventListener("scroll",o),()=>t.removeEventListener("pagehide",a),c)}}C.MOVEMENT_THROTTLE_MS=100,C.SCROLL_THROTTLE_MS=500;class E extends a.o{async trackWebVitals(e){return await this.init("web_vitals",{type:"web_vitals",...e,timestamp:(new Date).toISOString()})}async trackPageLoad(e){return await this.init("page_load",{type:"page_load",...e,timestamp:(new Date).toISOString()})}async trackResource(e){return await this.init("resource_timing",{type:"resource_timing",...e,timestamp:(new Date).toISOString()})}async trackApiCall(e,t,r,i){return await this.init("api_timing",{type:"api_timing",endpoint:e,duration:t,success:r,statusCode:i,timestamp:(new Date).toISOString()})}autoTrack(e={}){if(!(0,v.Bd)())return()=>{};const t=(0,v.zk)(),r=t.location.pathname,i=[];let n=!1;s.e(717).then(s.bind(s,237)).then(t=>{if(n)return;const i=t=>{const i=t.name.toLowerCase(),s={pageUrl:r,userId:e.userId};s[i]=t.value,this.trackWebVitals(s)};t.onLCP?.(i),t.onCLS?.(i),t.onINP?.(i),t.onFCP?.(i),t.onTTFB?.(i),t.onFID?.(i)}).catch(()=>{}),i.push(()=>{n=!0});const a=()=>{const e=t.performance?.getEntriesByType?.("navigation")?.[0];e&&this.trackPageLoad({pageUrl:r,dnsTime:Math.max(0,e.domainLookupEnd-e.domainLookupStart),tcpTime:Math.max(0,e.connectEnd-e.connectStart),ttfb:Math.max(0,e.responseStart-e.requestStart),domContentLoaded:e.domContentLoadedEventEnd,loadTime:e.loadEventEnd,domInteractive:e.domInteractive,transferSize:e.transferSize})};if("complete"===t.document.readyState)a();else{const e=()=>a();t.addEventListener("load",e,{once:!0}),i.push(()=>t.removeEventListener("load",e))}if(e.resources&&"function"==typeof t.PerformanceObserver){const s=e.minDuration??200,n=new t.PerformanceObserver(e=>{for(const t of e.getEntries()){if(t.duration<s)continue;const e=t.initiatorType;this.trackResource({resourceUrl:t.name,resourceType:["script","stylesheet","image","font","fetch","xhr"].includes(e)?e:"other",duration:Math.round(t.duration),transferSize:t.transferSize,pageUrl:r})}});try{n.observe({type:"resource",buffered:!0}),i.push(()=>n.disconnect())}catch{}}return(0,v.vs)(...i)}}function D(){if(!(0,v.Bd)())return!1;try{return"granted"===localStorage.getItem("flowgrid:replayConsent")}catch{return!1}}const q="flowgrid:replaySessionId",O="rrweb@2";class P extends a.o{constructor(){super(...arguments),this.disabled=!1,this.active=null,this.state="idle"}async start(e={}){if(!1===e.enabled||this.disabled)return this.setState("disabled",e),()=>{};if(this.active&&!this.active.stopped)return this.emitStatus(this.active.options),()=>this.stop("manual");if(!(0,v.Bd)())return()=>{};if(!0===e.requireConsent&&!D()&&!a.o.hasConsent("analytics"))return this.setState("disabled",e),()=>{};this.setState("starting",e);const t=e.sampleRate??1;if(t<1&&Math.random()>t)return this.setState("sampled_out",e),()=>{};let r;try{r=await s.e(897).then(s.bind(s,546))}catch(t){return"undefined"!=typeof console&&console.error("[FlowGrid] Session replay failed to load rrweb:",t),this.handleError(this.toError(t),{phase:"import"},e),()=>{}}const i=(0,v.YE)();if(!i)return()=>{};const n=e.sessionId??this.resolveSessionId(),o=this.normalizeOptions(e),c=Date.now(),u={sessionId:n,userId:e.userId??this.boundUserId,startedAtMs:c,startedAt:new Date(c).toISOString(),sequence:0,buffer:[],bufferBytes:0,totalBytes:0,droppedEvents:0,stopped:!1,initialSnapshotCaptured:!1,flushTimer:setInterval(()=>{this.flush("interval")},o.flushIntervalMs),durationGuard:setTimeout(()=>this.stop("max_duration"),o.maxDurationMs),onVisibility:()=>{"hidden"===i.visibilityState&&this.flush("visibility_hidden",{useBeacon:!0})},onPageHide:()=>{this.flush("pagehide",{useBeacon:!0})},options:o};this.active=u;try{u.stopRecording=r.record({emit:e=>this.captureEvent(e),maskAllInputs:o.maskAllInputs,maskTextClass:o.maskTextClass??"fg-mask",blockClass:o.blockClass??"fg-block",ignoreClass:o.ignoreClass??"fg-ignore",checkoutEveryNth:200,checkoutEveryNms:3e4,inlineImages:!1,collectFonts:!1})}catch(e){return this.handleError(this.toError(e),{phase:"record",sessionId:n},o),u.stopped=!0,this.cleanupActive("stop"),this.active=null,()=>{}}return i.addEventListener("visibilitychange",u.onVisibility),window.addEventListener("pagehide",u.onPageHide),this.setState("recording",o),()=>this.stop("manual")}enable(e={}){return this.disabled=!1,this.start({...e,enabled:!0})}disable(){this.disabled=!0,this.stop("manual"),this.setState("disabled",this.active?.options)}stop(e="stop"){const t=this.active;t&&!t.stopped&&(t.stopped=!0,this.cleanupActive(e),this.flush(e,{useBeacon:!0,isFinal:!0}),this.setState("stopped",t.options,e),this.active=null)}async flush(e="manual",t={}){const r=this.active;if(!r||0===r.buffer.length)return;const i=r.buffer,s=i.length,n=r.bufferBytes,a=r.sequence++;r.buffer=[],r.bufferBytes=0;const o=(new Date).toISOString(),c=this.createIdempotencyKey(r.sessionId,a,n),u={sessionId:r.sessionId,userId:r.userId,sequence:a,eventsCount:s,byteSize:n,reason:e,isFinal:!0===t.isFinal,droppedEvents:r.droppedEvents,capturedAt:o,idempotencyKey:c};try{await this.postReplayChunk(r.sessionId,i,{userId:r.userId,sequence:a,useBeacon:t.useBeacon,startedAt:r.startedAt,capturedAt:o,pageUrl:this.getPageUrl(),isFinal:u.isFinal,reason:e,privacy:this.createPrivacyMetadata(r.options,"sampled_in"),droppedEvents:r.droppedEvents,recorderVersion:O},c),r.options.onFlush?.(u),this.emitStatus(r.options,e)}catch(e){this.handleError(this.toError(e),{phase:"flush",sessionId:r.sessionId},r.options)}}identify(e){this.boundUserId=e,this.active&&(this.active.userId=e,this.emitStatus(this.active.options))}getStatus(){return this.createStatus(this.active?.options)}async sendChunk(e,t,r={}){0!==t.length&&await this.postReplayChunk(e,t,r)}async postReplayChunk(e,t,r,i=this.createIdempotencyKey(e,r.sequence??0,this.measureEvents(t))){await this.postRaw("replay_chunk",{type:"replay_chunk",session_id:e,user_id:r.userId,sequence:r.sequence??0,started_at:r.startedAt,captured_at:r.capturedAt??(new Date).toISOString(),events:t,page_url:r.pageUrl??this.getPageUrl(),idempotency_key:i,compression:"none",is_final:!0===r.isFinal,chunk_kind:r.isFinal?"final":"partial",flush_reason:r.reason??"manual",dropped_events:r.droppedEvents??0,recorder_version:r.recorderVersion??O,privacy:r.privacy??this.createPrivacyMetadata(void 0,"sampled_in")},{useBeacon:r.useBeacon})}captureEvent(e){const t=this.active;if(!t||t.stopped)return;let r=0;try{r=JSON.stringify(e).length}catch{return t.droppedEvents++,void t.options.onDrop?.({sessionId:t.sessionId,reason:"serialization_error",droppedEvents:t.droppedEvents})}return t.totalBytes+r>t.options.maxBytes?(t.droppedEvents++,t.options.onDrop?.({sessionId:t.sessionId,reason:"max_bytes",droppedEvents:t.droppedEvents,byteSize:t.totalBytes+r,maxBytes:t.options.maxBytes}),void this.stop("max_bytes")):(t.totalBytes+=r,t.buffer.push(e),t.bufferBytes+=r,t.initialSnapshotCaptured||2!==e.type?void(t.bufferBytes>=t.options.flushBytes&&this.flush("size")):(t.initialSnapshotCaptured=!0,void Promise.resolve().then(()=>{this.flush("manual")})))}cleanupActive(e){const t=this.active;if(!t)return;const r=(0,v.YE)();clearInterval(t.flushTimer),clearTimeout(t.durationGuard),r?.removeEventListener("visibilitychange",t.onVisibility),window.removeEventListener("pagehide",t.onPageHide);try{t.stopRecording?.()}catch(e){this.handleError(this.toError(e),{phase:"stop",sessionId:t.sessionId},t.options)}this.emitStatus(t.options,e)}normalizeOptions(e){return{...e,flushIntervalMs:e.flushIntervalMs??5e3,flushBytes:e.flushBytes??524288,maxDurationMs:e.maxDurationMs??18e5,maxBytes:e.maxBytes??10485760,maskAllInputs:e.maskAllInputs??!0}}createStatus(e,t){const r=this.active;return{state:this.state,sessionId:r?.sessionId,userId:r?.userId??this.boundUserId,startedAt:r?.startedAt,sequence:r?.sequence??0,bufferedEvents:r?.buffer.length??0,bufferedBytes:r?.bufferBytes??0,totalBytes:r?.totalBytes??0,droppedEvents:r?.droppedEvents??0,recorderVersion:O,lastFlushReason:t,lastError:this.lastError}}setState(e,t,r){this.state=e,this.emitStatus(t,r)}emitStatus(e,t){e?.onStatus?.(this.createStatus(e,t))}handleError(e,t,r){this.lastError=e.message,this.state="error",r?.onError?.(e,t),this.emitStatus(r)}createPrivacyMetadata(e,t="sampled_in"){const r=D()||a.o.hasConsent("analytics");return{masking_mode:!1===e?.maskAllInputs?"selective":"all_inputs",blocked_selectors:this.selectorList(e?.blockClass??"fg-block"),redacted_fields:this.selectorList(e?.maskTextClass??"fg-mask"),consent_state:r?"granted":"denied",sampling_state:t}}selectorList(e){return"string"==typeof e?[e]:[e.source]}getPageUrl(){try{return"undefined"!=typeof location?location.href:""}catch{return""}}createIdempotencyKey(e,t,r){return`${this.webId}:${e}:${t}:${r}`}measureEvents(e){try{return JSON.stringify(e).length}catch{return 0}}toError(e){return e instanceof Error?e:new Error(String(e))}resolveSessionId(){try{const e=sessionStorage.getItem(q);if(e)return e;const t=this.generateId();return sessionStorage.setItem(q,t),t}catch{return this.generateId()}}generateId(){const e="undefined"!=typeof crypto?crypto:void 0;return e?.randomUUID?e.randomUUID():`rep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}}class A extends a.o{async view(e){return await this.init("product_view",{type:"ecommerce",subtype:"product_view",product:{productId:e.productId,name:e.name,brand:e.brand,category:e.category,variant:e.variant,price:e.price,currency:e.currency,url:e.url,imageUrl:e.imageUrl,rating:e.rating,reviewCount:e.reviewCount,stockStatus:e.stockStatus,attributes:e.attributes},source:e.source,searchQuery:e.searchQuery,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async impression(e){return await this.init("product_impression",{type:"ecommerce",subtype:"product_impression",list:e.list,productCount:e.list.products.length,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("product_click",{type:"ecommerce",subtype:"product_click",product:e.product,listId:e.listId,position:e.position,userId:e.userId,timestamp:(new Date).toISOString()})}async quickView(e,t){return await this.init("product_quick_view",{type:"ecommerce",subtype:"product_quick_view",product:e,listId:t,timestamp:(new Date).toISOString()})}async interaction(e,t,r){return await this.init("product_interaction",{type:"ecommerce",subtype:"product_interaction",productId:e,action:t,...r,timestamp:(new Date).toISOString()})}}class M extends a.o{async addItem(e){const t=e.product.price*e.quantity-(e.product.discount||0);return await this.init("add_to_cart",{type:"ecommerce",subtype:"add_to_cart",product:e.product,quantity:e.quantity,lineTotal:t,cartId:e.cartId,userId:e.userId,source:e.source,...e.properties,timestamp:(new Date).toISOString()})}async removeItem(e){return await this.init("remove_from_cart",{type:"ecommerce",subtype:"remove_from_cart",product:e.product,quantity:e.quantity,cartId:e.cartId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async updateItem(e){return await this.init("update_cart_item",{type:"ecommerce",subtype:"update_cart_item",product:e.product,previousQuantity:e.previousQuantity,newQuantity:e.newQuantity,quantityChange:e.newQuantity-e.previousQuantity,cartId:e.cartId,timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_cart",{type:"ecommerce",subtype:"view_cart",cartId:e.cart.cartId,cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t){return await this.init("cart_abandoned",{type:"ecommerce",subtype:"cart_abandoned",cart:e,cartValue:e.total,itemCount:e.itemCount,reason:t,timestamp:(new Date).toISOString()})}async applyCoupon(e,t,r,i){return await this.init("apply_coupon",{type:"ecommerce",subtype:"apply_coupon",cartId:e,couponCode:t,success:r,discount:i,timestamp:(new Date).toISOString()})}}class N extends a.o{async begin(e){return await this.init("begin_checkout",{type:"ecommerce",subtype:"begin_checkout",cart:e.cart,cartValue:e.cart.total,itemCount:e.cart.itemCount,userId:e.userId,sessionId:e.sessionId,...e.properties,timestamp:(new Date).toISOString()})}async step(e){return await this.init("checkout_step",{type:"ecommerce",subtype:"checkout_step",step:e.step,stepNumber:e.stepNumber,cart:e.cart,option:e.option,userId:e.userId,timestamp:(new Date).toISOString()})}async addShipping(e){return await this.init("add_shipping_info",{type:"ecommerce",subtype:"shipping_info",cart:e.cart,shipping:e.shipping,shippingMethod:e.shipping.method,shippingCost:e.shipping.cost,userId:e.userId,timestamp:(new Date).toISOString()})}async addPayment(e){return await this.init("add_payment_info",{type:"ecommerce",subtype:"payment_info",cart:e.cart,payment:e.payment,paymentMethod:e.payment.method,userId:e.userId,timestamp:(new Date).toISOString()})}async abandon(e,t,r){return await this.init("checkout_abandoned",{type:"ecommerce",subtype:"checkout_abandoned",cart:e,step:t,cartValue:e.total,reason:r,timestamp:(new Date).toISOString()})}async paymentAttempt(e,t,r,i){return await this.init("payment_attempt",{type:"ecommerce",subtype:"payment_attempt",success:e,cart:t,payment:r,errorCode:i,timestamp:(new Date).toISOString()})}}class B extends a.o{async track(e){const t=e.order;return await this.init("purchase",{type:"ecommerce",subtype:"purchase",order:{orderId:t.orderId,items:t.items,subtotal:t.subtotal,discountTotal:t.discountTotal,shippingTotal:t.shippingTotal,taxTotal:t.taxTotal,total:t.total,currency:t.currency,shipping:t.shipping,payment:t.payment,coupons:t.coupons,affiliation:t.affiliation},revenue:t.total,itemCount:t.items.reduce((e,t)=>e+t.quantity,0),userId:e.userId,sessionId:e.sessionId,attribution:e.attribution,...e.properties,timestamp:(new Date).toISOString()})}async statusChange(e,t,r){return await this.init("order_status_change",{type:"ecommerce",subtype:"order_status_change",orderId:e,newStatus:t,previousStatus:r,timestamp:(new Date).toISOString()})}async shipped(e,t){return await this.init("order_shipped",{type:"ecommerce",subtype:"order_shipped",orderId:e,shipping:t,timestamp:(new Date).toISOString()})}async delivered(e,t){return await this.init("order_delivered",{type:"ecommerce",subtype:"order_delivered",orderId:e,deliveredAt:t||(new Date).toISOString(),timestamp:(new Date).toISOString()})}}class F extends a.o{async track(e){return await this.init("refund",{type:"ecommerce",subtype:"refund",orderId:e.orderId,refundId:e.refundId,items:e.items,amount:e.amount,currency:e.currency,reason:e.reason,isFullRefund:e.isFullRefund,userId:e.userId,initiatedBy:e.initiatedBy,...e.properties,timestamp:(new Date).toISOString()})}async request(e,t,r){return await this.init("refund_requested",{type:"ecommerce",subtype:"refund_requested",orderId:e,items:t,reason:r,timestamp:(new Date).toISOString()})}async approve(e,t){return await this.init("refund_approved",{type:"ecommerce",subtype:"refund_approved",refundId:e,approvedAmount:t,timestamp:(new Date).toISOString()})}async deny(e,t){return await this.init("refund_denied",{type:"ecommerce",subtype:"refund_denied",refundId:e,denialReason:t,timestamp:(new Date).toISOString()})}async complete(e,t){return await this.init("refund_completed",{type:"ecommerce",subtype:"refund_completed",refundId:e,processedAmount:t,timestamp:(new Date).toISOString()})}}class U extends a.o{async view(e){return await this.init("promotion_view",{type:"ecommerce",subtype:"promotion_view",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,page:e.page,userId:e.userId,timestamp:(new Date).toISOString()})}async click(e){return await this.init("promotion_click",{type:"ecommerce",subtype:"promotion_click",promotionId:e.promotionId,name:e.name,creative:e.creative,position:e.position,destinationUrl:e.destinationUrl,userId:e.userId,timestamp:(new Date).toISOString()})}async couponUsed(e){return await this.init("coupon_used",{type:"ecommerce",subtype:"coupon_used",code:e.code,orderId:e.orderId,discountValue:e.discountValue,discountType:e.discountType,orderValueBefore:e.orderValueBefore,orderValueAfter:e.orderValueAfter,savings:e.orderValueBefore-e.orderValueAfter,userId:e.userId,timestamp:(new Date).toISOString()})}async couponAttempt(e,t,r){return await this.init("coupon_attempt",{type:"ecommerce",subtype:"coupon_attempt",code:e,success:t,failureReason:r,timestamp:(new Date).toISOString()})}}class L extends a.o{async add(e){return await this.init("add_to_wishlist",{type:"ecommerce",subtype:"add_to_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,source:e.source,timestamp:(new Date).toISOString()})}async remove(e){return await this.init("remove_from_wishlist",{type:"ecommerce",subtype:"remove_from_wishlist",product:e.product,wishlistId:e.wishlistId,userId:e.userId,reason:e.reason||"user_action",timestamp:(new Date).toISOString()})}async view(e){return await this.init("view_wishlist",{type:"ecommerce",subtype:"view_wishlist",wishlistId:e.wishlistId,itemCount:e.items.length,timestamp:(new Date).toISOString()})}async moveToCart(e,t){return await this.init("wishlist_to_cart",{type:"ecommerce",subtype:"wishlist_to_cart",product:e,wishlistId:t,timestamp:(new Date).toISOString()})}async share(e,t){return await this.init("share_wishlist",{type:"ecommerce",subtype:"share_wishlist",wishlistId:e,method:t,timestamp:(new Date).toISOString()})}}class V extends a.o{async recordAcquisitionCost(e){return await this.init("record_acquisition_cost",{type:"ecommerce",subtype:"acquisition_cost",userId:e.userId,cost:e.cost,channel:e.channel,campaign:e.campaign,timestamp:(new Date).toISOString()})}async updateSegment(e,t){return await this.init("update_customer_segment",{type:"ecommerce",subtype:"update_customer_segment",userId:e,segment:t,timestamp:(new Date).toISOString()})}}class R extends a.o{async track(e){return await this.init("site_search",{type:"ecommerce",subtype:"site_search",query:e.query,resultsCount:e.resultsCount,hasResults:e.resultsCount>0,category:e.category,filters:e.filters,sortBy:e.sortBy,page:e.page||1,userId:e.userId,sessionId:e.sessionId,timestamp:(new Date).toISOString()})}async trackClick(e){return await this.init("search_result_click",{type:"ecommerce",subtype:"search_result_click",query:e.query,product:e.product,position:e.position,page:e.page||1,timestamp:(new Date).toISOString()})}async trackRefinement(e,t,r){return await this.init("search_refinement",{type:"ecommerce",subtype:"search_refinement",originalQuery:e,refinedQuery:t,refinementType:r,timestamp:(new Date).toISOString()})}async trackSuggestion(e,t,r){return await this.init("search_suggestion",{type:"ecommerce",subtype:"search_suggestion",partialQuery:e,selectedSuggestion:t,suggestionPosition:r,timestamp:(new Date).toISOString()})}}class $ extends a.o{async start(e){return await this.init("subscription_start",{type:"ecommerce",subtype:"subscription_start",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,mrr:e.mrr,billingCycle:e.billingCycle,trialDays:e.trialDays,coupon:e.coupon,isTrialing:(e.trialDays||0)>0,...e.properties,timestamp:(new Date).toISOString()})}async change(e){const t=e.newMrr.amount-e.previousMrr.amount;return await this.init("subscription_change",{type:"ecommerce",subtype:"subscription_change",subscriptionId:e.subscriptionId,userId:e.userId,previousPlan:e.previousPlan,newPlan:e.newPlan,previousMrr:e.previousMrr,newMrr:e.newMrr,mrrChange:t,changeType:e.changeType,timestamp:(new Date).toISOString()})}async cancel(e){return await this.init("subscription_cancel",{type:"ecommerce",subtype:"subscription_cancel",subscriptionId:e.subscriptionId,userId:e.userId,plan:e.plan,lostMrr:e.lostMrr,reason:e.reason,feedback:e.feedback,immediate:e.immediate,timestamp:(new Date).toISOString()})}async renew(e,t,r){return await this.init("subscription_renew",{type:"ecommerce",subtype:"subscription_renew",subscriptionId:e,userId:t,mrr:r,timestamp:(new Date).toISOString()})}async trialConverted(e,t,r,i){return await this.init("trial_converted",{type:"ecommerce",subtype:"trial_converted",subscriptionId:e,userId:t,plan:r,mrr:i,timestamp:(new Date).toISOString()})}async trialExpired(e,t){return await this.init("trial_expired",{type:"ecommerce",subtype:"trial_expired",subscriptionId:e,userId:t,timestamp:(new Date).toISOString()})}}class j{constructor(e){this.client=e}signup(e,t,r,i){return this.client.trackSignup(e,t,r,i)}onboardingStep(e,t,r,i,s,n){return this.client.trackOnboardingStep({userId:e,stepId:t,stepName:r,stepOrder:i,totalSteps:s,...n})}onboardingComplete(e,t,r,i=0){return this.client.completeOnboarding(e,t,r,i)}firstAction(e,t,r,i){return this.client.trackFirstAction({userId:e,actionName:t,timeSinceSignup:r,properties:i})}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class z{constructor(e){this.client=e}used(e,t,r="used",i){return this.client.trackUsage({featureId:e,featureName:t,action:r,properties:i})}create(e,t,r,i){return this.client.create({userId:e,action:t,properties:{featureName:r,...i}})}}class H{constructor(e){this.client=e}submitted(e,t,r){return this.client.trackSubmission({promptId:e,promptType:t,properties:r})}responded(e,t,r,i){return this.client.trackResponse({promptId:e,responseTime:t,completed:r,properties:i})}feedback(e,t,r){return this.client.trackFeedback({promptId:e,feedbackType:t,properties:r})}conversation(e,t,r,i){return this.client.trackConversation(e,t,r,i)}event(e,t={}){return this.client.create({eventName:e,properties:t})}}class K{constructor(e){this.client=e}define(e){return this.client.define(e)}init(e){return this.client.initExperiments(e)}variant(e){return this.client.getLocalVariant(e)}assign(e,t,r,i="targeted"){return this.client.assign({experimentId:e,userId:t,variantId:r,source:i})}exposure(e,t,r){return this.client.trackExposure(e,t,r)}exposureAuto(e){return this.client.trackLocalExposure(e)}conversion(e,t,r,i,s=1){return this.client.trackConversion({experimentId:e,userId:t,variantId:r,metricName:i,value:s})}localConversion(e,t="conversion",r=1){return this.client.trackLocalConversion(e,t,r)}hydrateFromCookies(e){this.client.hydrateFromCookies(e)}hydrateFromCookieHeader(e){this.client.hydrateFromCookieHeader(e)}injectAssignments(e){this.client.injectAssignments(e)}getAssignments(){return this.client.getAssignments()}serializeAssignmentCookie(){return this.client.serializeAssignmentCookie()}clearAssignments(){this.client.clearAssignments()}}class Y{constructor(e){this.client=e}view(e,t,r){const i=function(){const e="undefined"!=typeof window&&"undefined"!=typeof document;return{url:e?window.location.href:"",path:e?window.location.pathname:"",title:e?document.title:void 0,referrer:e?document.referrer:void 0}}(),s=e&&/^https?:\/\//i.test(e),n=s?e:i.url,a=s?new URL(e).pathname:e??i.path;return this.client.track({url:n,path:a,title:r?.title??i.title,referrer:r?.referrer??i.referrer,userId:r?.userId,sessionId:r?.sessionId,properties:t})}scroll(e,t,r){return this.client.trackScrollDepth({path:e,scrollDepth:t,timeAtDepth:r})}time(e,t){return this.client.trackTimeOnPage({path:e,duration:t})}exit(e,t,r){return this.client.trackExit(e,t,r)}autoTrack(e){return this.client.autoTrack(e)}}class Q{constructor(e){this.client=e}start(e){return this.client.start(e)}update(e,t){return this.client.update(e,t)}end(e){return this.client.end(e)}heartbeat(e){return this.client.heartbeat(e)}autoTrack(e,t){return this.client.autoTrack(e,t)}}class J{constructor(e){this.client=e}track(e,t,r){return this.client.track({eventName:e,properties:t,userId:r?.userId,sessionId:r?.sessionId})}batch(e){return this.client.trackBatch({events:e})}click(e,t,r){return this.client.trackClick({elementId:e,elementText:t,properties:r})}form(e,t,r){return this.client.trackForm({formId:e,formName:t,properties:r})}search(e,t,r){return this.client.trackSearch({query:e,category:t,properties:r})}error(e,t,r){return this.client.trackError({message:e,type:t,properties:r})}}class G{constructor(e){this.client=e}user(e,t,r){return this.client.user({userId:e,anonymousId:r,traits:t})}updateTraits(e,t){return this.client.updateTraits(e,t)}alias(e,t){return this.client.alias({previousId:e,userId:t})}group(e,t,r){return this.client.group({userId:e,groupId:t,traits:r})}}class W{constructor(e){this.client=e}define(e){return this.client.define(e)}step(e,t,r,i,s){return this.client.trackStep({funnelId:e,step:t,stepNumber:r,userId:i,properties:s})}complete(e,t,r){return this.client.trackComplete(e,t,r)}abandon(e,t,r,i){return this.client.trackAbandon(e,t,r,i)}}class X{constructor(e){this.client=e}active(e,t){return this.client.trackActivity({userId:e,properties:t})}}class Z{constructor(e){this.client=e}touchpoint(e,t,r){return this.client.trackTouchpoint({userId:e,channel:t,properties:r})}conversion(e,t,r){return this.client.recordConversion({userId:e,conversionType:t,properties:r})}captureFromUrl(e){return this.client.captureFromUrl(e)}}class ee{constructor(e){this.client=e}click(e,t,r,i,s){return this.client.trackClick({pageUrl:e,x:t,y:r,viewportWidth:i,viewportHeight:s})}movement(e,t,r){return this.client.trackMovement({pageUrl:e,path:t,viewport:r})}scroll(e,t,r,i){return this.client.trackScroll({pageUrl:e,maxScrollDepth:t,pageHeight:r,viewportHeight:i})}autoTrack(e){return this.client.autoTrack(e)}}class te{constructor(e){this.client=e}webVitals(e,t){return this.client.trackWebVitals({pageUrl:e,...t})}pageLoad(e,t){return this.client.trackPageLoad({pageUrl:e,...t})}resource(e,t,r,i){return this.client.trackResource({pageUrl:e,resourceUrl:t,resourceType:r,duration:i})}autoTrack(e){return this.client.autoTrack(e)}}class re{constructor(e){this.client=e}start(e){return this.client.start(e??{})}enable(e){return this.client.enable(e??{})}disable(){this.client.disable()}stop(e){this.client.stop(e)}flush(e){return this.client.flush(e??"manual")}identify(e){this.client.identify(e)}status(){return this.client.getStatus()}sendChunk(e,t,r){return this.client.sendChunk(e,t,r??{})}}class ie{constructor(e){this.client=e}view(e,t){return this.client.view({...e,properties:t})}impression(e,t,r){return this.client.impression({list:{listId:e,listName:t,products:r}})}click(e,t,r){return this.client.click({product:e,listId:t,position:r})}}class se{constructor(e){this.client=e}add(e,t=1,r){return this.client.addItem({product:e,quantity:t,cartId:r})}remove(e,t=1,r){return this.client.removeItem({product:e,quantity:t,cartId:r})}update(e,t,r,i){return this.client.updateItem({product:e,previousQuantity:t,newQuantity:r,cartId:i})}view(e){return this.client.view({cart:e})}}class ne{constructor(e){this.client=e}begin(e){return this.client.begin({cart:e})}step(e,t,r){return this.client.step({step:e,stepNumber:t,cart:r})}shipping(e,t){return this.client.addShipping({cart:e,shipping:t})}payment(e,t){return this.client.addPayment({cart:e,payment:t})}}class ae{constructor(e){this.client=e}complete(e){return this.client.track({order:e})}}class oe{constructor(e){this.client=e}request(e,t,r){return this.client.request(e,t,r)}approve(e,t){return this.client.approve(e,t)}deny(e,t){return this.client.deny(e,t)}complete(e,t,r,i,s,n=!1){return this.client.track({orderId:e,refundId:t,amount:r,currency:i,reason:s,isFullRefund:n})}}class ce{constructor(e){this.client=e}view(e,t,r,i){return this.client.view({promotionId:e,name:t,creative:r,position:i})}click(e,t,r,i){return this.client.click({promotionId:e,name:t,creative:r,position:i})}coupon(e,t,r,i,s,n){return this.client.couponUsed({code:e,orderId:t,discountValue:r,discountType:i,orderValueBefore:s,orderValueAfter:n})}}class ue{constructor(e){this.client=e}add(e,t){return this.client.add({product:e,wishlistId:t})}remove(e,t){return this.client.remove({product:e,wishlistId:t})}view(e){return this.client.view(e)}moveToCart(e,t){return this.client.moveToCart(e,t)}share(e,t){return this.client.share(e,t)}}class pe{constructor(e){this.client=e}acquisitionCost(e,t,r){return this.client.recordAcquisitionCost({userId:e,cost:t,channel:r})}segment(e,t){return this.client.updateSegment(e,t)}}class de{constructor(e){this.client=e}query(e,t,r){return this.client.track({query:e,resultsCount:t,...r})}click(e,t,r){return this.client.trackClick({query:e,product:t,position:r})}refine(e,t,r){return this.client.trackRefinement(e,t,r)}suggestion(e,t,r){return this.client.trackSuggestion(e,t,r)}}class le{constructor(e){this.client=e}start(e,t,r,i,s){return this.client.start({subscriptionId:e,userId:t,plan:r,mrr:i,billingCycle:s})}change(e,t,r,i,s,n,a){return this.client.change({subscriptionId:e,userId:t,previousPlan:r,newPlan:i,previousMrr:s,newMrr:n,changeType:a})}cancel(e,t,r,i,s=!1){return this.client.cancel({subscriptionId:e,userId:t,plan:r,lostMrr:i,immediate:s})}renew(e,t,r){return this.client.renew(e,t,r)}trialConverted(e,t,r,i){return this.client.trialConverted(e,t,r,i)}trialExpired(e,t){return this.client.trialExpired(e,t)}}let he=null,me=null;function ge(){return he&&me?Promise.resolve():Promise.all([s.e(137).then(s.bind(s,78)),s.e(137).then(s.bind(s,544))]).then(([e,t])=>{he=e,me=t})}const ye={handled:!1},Ie=["productId","name","brand","category","variant","price","currency","quantity","discount","coupon","position","url","imageUrl","rating","reviewCount","stockStatus","attributes"];function fe(e){return{handled:!0,value:e}}function ve(e,t){const r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function we(e,t){const r=e[t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}function Se(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function _e(e,t){const r=e[t];return function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(r)?r:void 0}function ke(e,t){const r=e[t];return null!=r&&!("string"==typeof r&&0===r.length)}function be(e,t){const r={},i=new Set([...t,"domain"]);for(const[t,s]of Object.entries(e))i.has(t)||(r[t]=s);return r}function Te(e){const t=_e(e,"product");if(t)return{...t,currency:t.currency??"USD"};if(!ke(e,"productId")||!ke(e,"name")||!ke(e,"price"))return;const r={currency:"USD"};for(const t of Ie)void 0!==e[t]&&(r[t]=e[t]);return r}class xe{static init(e){if(xe._instance)return"undefined"!=typeof console&&console.warn("[FlowGrid] init() called more than once — returning existing instance."),xe._instance;if(!e?.webId||!e?.apiKey)throw new Error("FlowGrid.init: `webId` and `apiKey` are required.");e.consent&&xe.setConsent(e.consent);const t=new xe(e.webId,e.endpoint??"https://core.flow-grid.xyz",e.apiKey,e.visitorId,e.identityManager,e.transport);xe._instance=t,ge(),e.user?.userId&&t.identifyUser(e.user.userId,e.user.traits);const r=e.autoTrack,i=e.replay,s=!1===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1,engagement:!1,replay:!1}:!0===r||void 0===r?{sessions:!1,pageViews:!1,performance:!1,heatmaps:!1,attribution:!1}:r;return void 0!==i&&(s.replay=i),t._autoTrackStop=t.autoTrack({...s,userId:e.user?.userId??s.userId}),t}static instance(){return xe._instance}static loadEnterprise(){return ge()}static reset(){if(xe._instance?._autoTrackStop)try{xe._instance._autoTrackStop()}catch{}xe._instance=null}constructor(e,t,r,i,s,n){this._autoTrackStop=null,this._raw=new Map,this._wrapped=new Map,this.webId=e,this.endpoint=t,this.apiKey=r,this.visitorId=i,this.identityManager=s??new d(i?{visitorId:i}:void 0),this.config=n}raw(e,t){let r=this._raw.get(e);return r||(r=new t(this.webId,this.endpoint,this.apiKey,this.visitorId,this.identityManager,this.config),this._raw.set(e,r)),r}wrap(e,t,r){let i=this._wrapped.get(e);return i||(i=new r(this.raw(e,t)),this._wrapped.set(e,i)),i}get activation(){return this.wrap("activation",l,j)}get features(){return this.wrap("features",h,z)}get prompts(){return this.wrap("prompts",m,H)}get experiments(){return this.wrap("experiments",f,K)}get pageViews(){return this.wrap("pageViews",w,Y)}get sessions(){return this.wrap("sessions",S,Q)}get events(){return this.wrap("events",_,J)}get identify(){return this.wrap("identify",k,G)}get funnels(){return this.wrap("funnels",b,W)}get retention(){return this.wrap("retention",T,X)}get attribution(){return this.wrap("attribution",x,Z)}get heatmaps(){return this.wrap("heatmaps",C,ee)}get performance(){return this.wrap("performance",E,te)}get replay(){return this.wrap("replay",P,re)}get products(){return this.wrap("products",A,ie)}get cart(){return this.wrap("cart",M,se)}get checkout(){return this.wrap("checkout",N,ne)}get purchases(){return this.wrap("purchases",B,ae)}get refunds(){return this.wrap("refunds",F,oe)}get promotions(){return this.wrap("promotions",U,ce)}get wishlist(){return this.wrap("wishlist",L,ue)}get ltv(){return this.wrap("ltv",V,pe)}get search(){return this.wrap("search",R,de)}get subscriptions(){return this.wrap("subscriptions",$,le)}_requireEnterprise(){const e=he,t=me;if(!e||!t)throw new Error("[FlowGrid] Enterprise features are still loading. await FlowGrid.loadEnterprise() before accessing enterprise namespaces directly.");return{ent:e,entT:t}}get engagement(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("engagement",e.Engagement,t.EngagementTracker)}get cohorts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("cohorts",e.Cohorts,t.CohortTracker)}get churn(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("churn",e.ChurnAnalytics,t.ChurnTracker)}get monetization(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("monetization",e.Monetization,t.MonetizationTracker)}get multiPathFunnels(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("multiPathFunnels",e.MultiPathFunnels,t.MultiPathFunnelTracker)}get support(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("support",e.SupportAnalytics,t.SupportTracker)}get acquisition(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("acquisition",e.AcquisitionAnalytics,t.AcquisitionTracker)}get paths(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("paths",e.PathAnalytics,t.PathTracker)}get alerts(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("alerts",e.AlertsAnalytics,t.AlertTracker)}get security(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("security",e.SecurityAnalytics,t.SecurityTracker)}get forecasting(){const{ent:e,entT:t}=this._requireEnterprise();return this.wrap("forecasting",e.Forecasting,t.ForecastingTracker)}track(e,t={},r={}){const i=this.withTrackContext(t,r),s=this.dispatchTrack(e,i,Boolean(r.domain),r.domain);return s.handled?s.value:this.events.track(e,t,r)}withTrackContext(e,t){return{...e,...void 0!==t.userId&&void 0===e.userId?{userId:t.userId}:{},...void 0!==t.sessionId&&void 0===e.sessionId?{sessionId:t.sessionId}:{}}}requireTrackProperties(e,t,r,i){const s=r.filter(e=>!ke(t,e));if(0===s.length)return!0;if(i)throw new Error(`FlowGrid.track("${e}") missing required properties: ${s.join(", ")}`);return!1}dispatchTrack(e,t,r,i){const s=[];i&&"activation"!==i||s.push(()=>this.dispatchActivationTrack(e,t,r)),i&&"feature"!==i||s.push(()=>this.dispatchFeatureTrack(e,t,r)),i&&"prompt"!==i||s.push(()=>this.dispatchPromptTrack(e,t,r)),i&&"experiment"!==i||s.push(()=>this.dispatchExperimentTrack(e,t,r)),i&&"analytics"!==i&&"funnel"!==i&&"retention"!==i&&"attribution"!==i||s.push(()=>this.dispatchAnalyticsTrack(e,t,r,i)),i&&"ecommerce"!==i||s.push(()=>this.dispatchEcommerceTrack(e,t,r)),i&&"engagement"!==i&&"churn"!==i&&"monetization"!==i&&"support"!==i&&"acquisition"!==i&&"paths"!==i&&"security"!==i&&"multiPathFunnels"!==i||s.push(()=>this.dispatchEnterpriseTrack(e,t,r,i));for(const e of s){const t=e();if(t.handled)return t}return ye}dispatchActivationTrack(e,t,r){switch(e){case"signup_completed":return this.requireTrackProperties(e,t,["userId","method"],r)?fe(this.activation.signup(ve(t,"userId"),ve(t,"method"),ve(t,"source"),be(t,["userId","method","source"]))):ye;case"onboarding_step":return this.requireTrackProperties(e,t,["userId","stepId","stepName","stepOrder","totalSteps"],r)?fe(this.activation.onboardingStep(ve(t,"userId"),ve(t,"stepId"),ve(t,"stepName"),we(t,"stepOrder"),we(t,"totalSteps"),{skipped:Se(t,"skipped"),timeSpent:we(t,"timeSpent"),properties:be(t,["userId","stepId","stepName","stepOrder","totalSteps","skipped","timeSpent"])})):ye;case"onboarding_completed":return this.requireTrackProperties(e,t,["userId","totalTimeSpent","stepsCompleted"],r)?fe(this.activation.onboardingComplete(ve(t,"userId"),we(t,"totalTimeSpent"),we(t,"stepsCompleted"),we(t,"stepsSkipped")??0)):ye;case"first_action":return this.requireTrackProperties(e,t,["userId","actionName","timeSinceSignup"],r)?fe(this.activation.firstAction(ve(t,"userId"),ve(t,"actionName"),we(t,"timeSinceSignup"),be(t,["userId","actionName","timeSinceSignup"]))):ye;default:return r?fe(this.activation.event(e,t)):ye}}dispatchFeatureTrack(e,t,r){const i={feature_viewed:"viewed",feature_used:"used",feature_completed:"completed",feature_abandoned:"abandoned"}[e]??("feature_usage"===e?t.action:void 0);return"feature_usage"===e||i?this.requireTrackProperties(e,t,["featureId","featureName"],r)?fe(this.features.client.trackUsage({...t,action:"string"==typeof i?i:"used"})):ye:r&&this.requireTrackProperties(e,t,["userId","featureName"],!0)?fe(this.features.create(ve(t,"userId"),e,ve(t,"featureName"),be(t,["userId","featureName"]))):ye}dispatchPromptTrack(e,t,r){switch(e){case"prompt_submitted":return this.requireTrackProperties(e,t,["promptId","promptType"],r)?fe(this.prompts.client.trackSubmission(t)):ye;case"prompt_response":return this.requireTrackProperties(e,t,["promptId","responseTime","completed"],r)?fe(this.prompts.client.trackResponse(t)):ye;case"prompt_feedback":return this.requireTrackProperties(e,t,["promptId","feedbackType"],r)?fe(this.prompts.client.trackFeedback(t)):ye;case"prompt_conversation":return this.requireTrackProperties(e,t,["conversationId","userId","turnCount","totalDuration"],r)?fe(this.prompts.conversation(ve(t,"conversationId"),ve(t,"userId"),we(t,"turnCount"),we(t,"totalDuration"))):ye;default:return r||e.startsWith("prompt_")?fe(this.prompts.event(e,t)):ye}}dispatchExperimentTrack(e,t,r){switch(e){case"experiment_assignment":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?fe(this.experiments.client.assign(t)):ye;case"experiment_exposure":return this.requireTrackProperties(e,t,["experimentId","userId","variantId"],r)?fe(this.experiments.exposure(ve(t,"experimentId"),ve(t,"userId"),ve(t,"variantId"))):ye;case"experiment_conversion":return this.requireTrackProperties(e,t,["experimentId","userId","variantId","metricName"],r)?fe(this.experiments.client.trackConversion({...t,value:we(t,"value")??1})):ye;default:return(r||e.startsWith("experiment_"))&&this.requireTrackProperties(e,t,["variant"],r)?fe(this.experiments.client.track({eventName:e,variant:ve(t,"variant"),properties:be(t,["variant"])})):ye}}dispatchAnalyticsTrack(e,t,r,i){switch(e){case"click_event":return this.requireTrackProperties(e,t,["elementId","elementText"],r)?fe(this.events.client.trackClick(t)):ye;case"form_event":return this.requireTrackProperties(e,t,["formId","formName"],r)?fe(this.events.client.trackForm(t)):ye;case"search_event":return this.requireTrackProperties(e,t,["query","category"],r)?fe(this.events.client.trackSearch(t)):ye;case"error_event":return this.requireTrackProperties(e,t,["message","type"],r)?fe(this.events.client.trackError(t)):ye;case"funnel_step":return this.requireTrackProperties(e,t,["funnelId","step","stepNumber"],r)?fe(this.funnels.client.trackStep(t)):ye;case"funnel_complete":return this.requireTrackProperties(e,t,["funnelId"],r)?fe(this.funnels.complete(ve(t,"funnelId"),ve(t,"userId"),be(t,["funnelId","userId"]))):ye;case"funnel_abandon":return this.requireTrackProperties(e,t,["funnelId","lastStep"],r)?fe(this.funnels.abandon(ve(t,"funnelId"),ve(t,"lastStep"),ve(t,"userId"),ve(t,"reason"))):ye;case"user_activity":return i&&"retention"!==i?ye:this.requireTrackProperties(e,t,["userId"],r)?fe(this.retention.client.trackActivity(t)):ye;case"attribution_touchpoint":return this.requireTrackProperties(e,t,["userId","channel"],r)?fe(this.attribution.client.trackTouchpoint(t)):ye;case"attribution_conversion":return this.requireTrackProperties(e,t,["userId","conversionType"],r)?fe(this.attribution.client.recordConversion(t)):ye;default:return ye}}dispatchEcommerceTrack(e,t,r){switch(e){case"product_view":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}return fe(this.products.client.view({...i,...be(t,["product",...Ie])}))}case"product_impression":return this.requireTrackProperties(e,t,["list"],r)?fe(this.products.client.impression(t)):ye;case"product_click":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["listId","position"],r)?fe(this.products.client.click({...t,product:i})):ye}case"add_to_cart":case"remove_from_cart":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}const s={...be(t,["product",...Ie]),product:i,quantity:we(t,"quantity")??1};return fe("add_to_cart"===e?this.cart.client.addItem(s):this.cart.client.removeItem(s))}case"update_cart_item":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["previousQuantity","newQuantity"],r)?fe(this.cart.client.updateItem({...be(t,["product",...Ie]),product:i})):ye}case"view_cart":return this.requireTrackProperties(e,t,["cart"],r)?fe(this.cart.client.view(t)):ye;case"begin_checkout":return this.requireTrackProperties(e,t,["cart"],r)?fe(this.checkout.client.begin(t)):ye;case"checkout_step":return this.requireTrackProperties(e,t,["step","stepNumber","cart"],r)?fe(this.checkout.client.step(t)):ye;case"add_shipping_info":return this.requireTrackProperties(e,t,["cart","shipping"],r)?fe(this.checkout.client.addShipping(t)):ye;case"add_payment_info":return this.requireTrackProperties(e,t,["cart","payment"],r)?fe(this.checkout.client.addPayment(t)):ye;case"purchase":return this.requireTrackProperties(e,t,["order"],r)?fe(this.purchases.client.track(t)):ye;case"refund":return this.requireTrackProperties(e,t,["orderId","refundId","amount","currency"],r)?fe(this.refunds.client.track(t)):ye;case"refund_requested":return this.requireTrackProperties(e,t,["orderId"],r)?fe(this.refunds.client.request(ve(t,"orderId"),t.items,ve(t,"reason"))):ye;case"refund_approved":return this.requireTrackProperties(e,t,["refundId","approvedAmount"],r)?fe(this.refunds.client.approve(ve(t,"refundId"),we(t,"approvedAmount"))):ye;case"refund_denied":return this.requireTrackProperties(e,t,["refundId","reason"],r)?fe(this.refunds.client.deny(ve(t,"refundId"),ve(t,"reason"))):ye;case"refund_completed":return this.requireTrackProperties(e,t,["refundId","processedAmount"],r)?fe(this.refunds.client.complete(ve(t,"refundId"),we(t,"processedAmount"))):ye;case"promotion_view":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?fe(this.promotions.client.view(t)):ye;case"promotion_click":return this.requireTrackProperties(e,t,["promotionId","name","creative","position"],r)?fe(this.promotions.client.click(t)):ye;case"coupon_used":return this.requireTrackProperties(e,t,["code","orderId","discountValue","discountType","orderValueBefore","orderValueAfter"],r)?fe(this.promotions.client.couponUsed(t)):ye;case"add_to_wishlist":case"remove_from_wishlist":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}const s={...be(t,["product",...Ie]),product:i};return fe("add_to_wishlist"===e?this.wishlist.client.add(s):this.wishlist.client.remove(s))}case"view_wishlist":return this.requireTrackProperties(e,t,["wishlist"],r)?fe(this.wishlist.client.view(_e(t,"wishlist"))):ye;case"wishlist_to_cart":{const i=Te(t);if(!i){if(r)throw new Error(`FlowGrid.track("${e}") missing required properties: product or productId, name, price`);return ye}return fe(this.wishlist.client.moveToCart(i,ve(t,"wishlistId")))}case"share_wishlist":return this.requireTrackProperties(e,t,["wishlistId","method"],r)?fe(this.wishlist.client.share(ve(t,"wishlistId"),ve(t,"method"))):ye;case"subscription_start":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr","billingCycle"],r)?fe(this.subscriptions.client.start(t)):ye;case"subscription_change":return this.requireTrackProperties(e,t,["subscriptionId","userId","previousPlan","newPlan","previousMrr","newMrr","changeType"],r)?fe(this.subscriptions.client.change(t)):ye;case"subscription_cancel":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","lostMrr"],r)?fe(this.subscriptions.client.cancel(t)):ye;case"subscription_renew":return this.requireTrackProperties(e,t,["subscriptionId","userId","mrr"],r)?fe(this.subscriptions.client.renew(ve(t,"subscriptionId"),ve(t,"userId"),_e(t,"mrr"))):ye;case"trial_converted":return this.requireTrackProperties(e,t,["subscriptionId","userId","plan","mrr"],r)?fe(this.subscriptions.client.trialConverted(ve(t,"subscriptionId"),ve(t,"userId"),ve(t,"plan"),_e(t,"mrr"))):ye;case"trial_expired":return this.requireTrackProperties(e,t,["subscriptionId","userId"],r)?fe(this.subscriptions.client.trialExpired(ve(t,"subscriptionId"),ve(t,"userId"))):ye;case"record_acquisition_cost":return this.requireTrackProperties(e,t,["userId","cost","channel"],r)?fe(this.ltv.client.recordAcquisitionCost(t)):ye;case"update_customer_segment":return this.requireTrackProperties(e,t,["userId","newSegment"],r)?fe(this.ltv.client.updateSegment(ve(t,"userId"),ve(t,"newSegment"))):ye;case"site_search":return this.requireTrackProperties(e,t,["query","resultsCount"],r)?fe(this.search.client.track(t)):ye;case"search_result_click":{const i=Te(t);return i&&this.requireTrackProperties(e,t,["query","position"],r)?fe(this.search.client.trackClick({...t,product:i})):ye}case"search_refinement":return this.requireTrackProperties(e,t,["originalQuery","refinedQuery","refinementType"],r)?fe(this.search.client.trackRefinement(ve(t,"originalQuery"),ve(t,"refinedQuery"),ve(t,"refinementType"))):ye;case"search_suggestion":return this.requireTrackProperties(e,t,["partialQuery","selectedSuggestion","suggestionPosition"],r)?fe(this.search.client.trackSuggestion(ve(t,"partialQuery"),ve(t,"selectedSuggestion"),we(t,"suggestionPosition"))):ye;default:return ye}}dispatchEnterpriseTrack(e,t,r,i){if(!he||!me)return ye;switch(e){case"engagement.dwell_time":case"engagement_dwell_time":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["featureId","dwellTimeMs"],r)?fe(this.engagement.client.trackDwellTime(t)):ye;case"engagement.session_depth":case"engagement_session_depth":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["sessionId","pagesVisited","featuresUsed","actionsTaken","durationMs"],r)?fe(this.engagement.client.trackSessionDepth(t)):ye;case"engagement.content_consumption":case"engagement_content_consumption":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["contentId","contentType","percentageConsumed","timeSpentMs"],r)?fe(this.engagement.client.trackContentConsumption(t)):ye;case"engagement.user_activity":case"engagement_user_activity":return i&&"engagement"!==i?ye:this.requireTrackProperties(e,t,["userId","activityType","durationMs"],r)?fe(this.engagement.client.trackUserActivity(t)):ye;case"churn.usage_decay":case"churn_usage_decay":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","metric","periods"],r)?fe(this.churn.client.trackUsageDecay(t)):ye;case"churn.nps":case"churn_nps":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","score"],r)?fe(this.churn.client.trackNPS(t)):ye;case"churn.churn_event":case"churn_churn_event":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","churnType"],r)?fe(this.churn.client.trackChurn(t)):ye;case"churn.prevention_action":case"churn_prevention_action":return i&&"churn"!==i?ye:this.requireTrackProperties(e,t,["userId","actionType"],r)?fe(this.churn.client.trackPreventionAction(t)):ye;case"monetization.revenue":case"monetization_revenue":return i&&"monetization"!==i?ye:this.requireTrackProperties(e,t,["userId","amount","currency","type"],r)?fe(this.monetization.client.trackRevenue(t)):ye;case"support.ticket_created":case"support_ticket_created":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","userId","subject","category","priority","channel"],r)?fe(this.support.client.trackTicket(t)):ye;case"support.ticket_updated":case"support_ticket_updated":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","status"],r)?fe(this.support.client.updateTicket(t)):ye;case"support.csat":case"support_csat":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["ticketId","userId","score"],r)?fe(this.support.client.trackCSAT(t)):ye;case"support.feature_complaint":case"support_feature_complaint":return i&&"support"!==i?ye:this.requireTrackProperties(e,t,["userId","featureId","complaintType","severity"],r)?fe(this.support.client.trackFeatureComplaint(t)):ye;case"acquisition.acquired":case"acquisition_acquired":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["userId","source"],r)?fe(this.acquisition.client.trackAcquisition(t)):ye;case"acquisition.lifecycle_transition":case"acquisition_lifecycle_transition":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["userId","fromStage","toStage"],r)?fe(this.acquisition.client.trackLifecycleTransition(t)):ye;case"acquisition.campaign_spend":case"acquisition_campaign_spend":return i&&"acquisition"!==i?ye:this.requireTrackProperties(e,t,["campaignId","amount","date"],r)?fe(this.acquisition.client.trackCampaignSpend(t)):ye;case"paths.transition":case"paths_transition":return i&&"paths"!==i?ye:this.requireTrackProperties(e,t,["userId","fromScreen","toScreen"],r)?fe(this.paths.client.trackTransition(t)):ye;case"paths.feature_sequence":case"paths_feature_sequence":return i&&"paths"!==i?ye:this.requireTrackProperties(e,t,["userId","feature","order"],r)?fe(this.paths.client.trackFeatureSequence(t)):ye;case"security.login_attempt":case"security_login_attempt":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","success"],r)?fe(this.security.client.trackLoginAttempt(t)):ye;case"security.role_change":case"security_role_change":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","changedBy","previousRole","newRole"],r)?fe(this.security.client.trackRoleChange(t)):ye;case"security.permission_change":case"security_permission_change":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","changedBy","permission","action"],r)?fe(this.security.client.trackPermissionChange(t)):ye;case"security.data_access":case"security_data_access":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","resourceType","accessType"],r)?fe(this.security.client.trackDataAccess(t)):ye;case"security.compliance_event":case"security_compliance_event":return i&&"security"!==i?ye:this.requireTrackProperties(e,t,["userId","eventType"],r)?fe(this.security.client.trackComplianceEvent(t)):ye;case"multi_path_funnels.track_step":case"multi_path_funnels_track_step":return i&&"multiPathFunnels"!==i?ye:this.requireTrackProperties(e,t,["funnelId","step","userId"],r)?fe(this.multiPathFunnels.client.trackStep(t)):ye;case"multi_path_funnels.track_micro_conversion":case"multi_path_funnels_track_micro_conversion":return i&&"multiPathFunnels"!==i?ye:this.requireTrackProperties(e,t,["conversionId","userId"],r)?fe(this.multiPathFunnels.client.trackMicroConversion(t)):ye;default:return ye}}experiment(e,t){return this.experiments.exposure(e,t.userId,t.variant)}identifyUser(e,t,r){return this.identify.user(e,t,r)}page(e,t,r){return this.pageViews.view(e,t,r)}autoTrack(e={}){const t=[],r={userId:e.userId};if(!0===e.sessions&&t.push(this.sessions.autoTrack(r.userId?{user:{userId:r.userId}}:{})),!0===e.pageViews&&t.push(this.pageViews.autoTrack(r)),!0===e.performance||!1!==e.performance&&"object"==typeof e.performance){const i="object"==typeof e.performance?e.performance:{};t.push(this.performance.autoTrack({...i,userId:r.userId}))}if(!0===e.heatmaps||!1!==e.heatmaps&&"object"==typeof e.heatmaps){const i="object"==typeof e.heatmaps?e.heatmaps:{};t.push(this.heatmaps.autoTrack({...i,userId:r.userId}))}if(!1!==e.engagement){const i="object"==typeof e.engagement?e.engagement:{};let s=null,n=!1;ge().then(()=>{n||(s=this.engagement.client.autoTrack({...i,userId:r.userId}))}),t.push(()=>{if(n=!0,s)try{s()}catch{}})}if(!0===e.attribution&&r.userId&&this.attribution.captureFromUrl(r.userId),!1!==e.replay){const i="object"==typeof e.replay?e.replay:{};let s=null,n=!1;this.replay.start({userId:r.userId,...i}).then(e=>{if(n)try{e()}catch{}else s=e}),t.push(()=>{if(n=!0,s)try{s()}catch{}})}return()=>{for(const e of t)try{e()}catch{}}}}function Ce(){const e=xe.instance();if(!e)throw new Error("FlowGrid not initialized. Call FlowGrid.init() first.");return e}function Ee(e){return{...e,currency:e.currency??"USD"}}xe._instance=null,xe.setConsent=a.o.setConsent.bind(a.o),xe.hasConsent=a.o.hasConsent.bind(a.o);const De={init:e=>xe.init(e),instance:()=>xe.instance(),reset(){xe.reset()},setConsent(e){xe.setConsent(e)},hasConsent:e=>xe.hasConsent(e),autoTrack:e=>Ce().autoTrack(e),track:(e,t,r)=>Ce().track(e,t,r),page:(e,t,r)=>Ce().page(e,t,r),identify:(e,t,r)=>Ce().identifyUser(e,t,r),experiment:(e,t)=>Ce().experiment(e,t),productView:(e,t)=>Ce().products.view(Ee(e),t),addToCart:(e,t=1,r)=>Ce().cart.add(Ee(e),t,r),purchase:e=>Ce().purchases.complete(function(e){const t=e.currency??"USD",r=e.items.map(e=>({...e,currency:e.currency??t,quantity:e.quantity,lineTotal:e.price*e.quantity})),i=e.subtotal??r.reduce((e,t)=>e+t.lineTotal,0);return{orderId:e.orderId,items:r,subtotal:i,discountTotal:e.discountTotal??0,shippingTotal:e.shippingTotal??0,taxTotal:e.taxTotal??0,total:e.total,currency:t}}(e))};"undefined"!=typeof window&&(window.FlowGrid=De,window.flowgrid=De);const qe=De;return n})());
|
|
2
2
|
//# sourceMappingURL=flowgrid.min.js.map
|