@beworke/pixel 0.1.0-rc.13 → 0.1.0-rc.15
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/CHANGELOG.md +20 -0
- package/dist/browser/index.cjs.js +1 -1
- package/dist/browser/index.cjs.js.map +1 -1
- package/dist/browser/index.esm.js +1 -1
- package/dist/browser/index.esm.js.map +1 -1
- package/dist/browser/pixel.buygoods-checkout.global.js +1 -1
- package/dist/browser/pixel.buygoods-checkout.global.js.map +1 -1
- package/dist/browser/pixel.buygoods-landing.global.js +1 -1
- package/dist/browser/pixel.buygoods-landing.global.js.map +1 -1
- package/dist/browser/pixel.global.js +1 -1
- package/dist/browser/pixel.global.js.map +1 -1
- package/dist/browser/pixel.internal-checkout.global.js +1 -1
- package/dist/browser/pixel.internal-checkout.global.js.map +1 -1
- package/dist/events/index.cjs.js +1 -1
- package/dist/events/index.esm.js +1 -1
- package/dist/examples/html-script/README.md +11 -0
- package/dist/examples/html-script/customer/README.md +29 -0
- package/dist/examples/html-script/customer/example-customer-css.html +383 -0
- package/dist/examples/html-script/customer/example-customer-defaults.html +408 -0
- package/dist/examples/html-script/customer/example-customer-events.html +428 -0
- package/dist/examples/html-script/customer/example-customer-extra-fields.html +385 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/runtime/index.cjs.js +1 -1
- package/dist/runtime/index.cjs.js.map +1 -1
- package/dist/runtime/index.esm.js +1 -1
- package/dist/runtime/index.esm.js.map +1 -1
- package/dist/services/index.cjs.js +1 -1
- package/dist/services/index.cjs.js.map +1 -1
- package/dist/services/index.esm.js +1 -1
- package/dist/services/index.esm.js.map +1 -1
- package/dist/v2/global.global.js +1 -1
- package/dist/v2/global.global.js.map +1 -1
- package/dist/v2/index.cjs.js +1 -1
- package/dist/v2/index.cjs.js.map +1 -1
- package/dist/v2/index.esm.js +1 -1
- package/dist/v2/index.esm.js.map +1 -1
- package/docs/public/configuration/commerce.md +3 -1
- package/package.json +1 -1
package/dist/v2/index.cjs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Pixel v2 — SDK de analytics e conversão */
|
|
2
|
-
"use strict";var Ni=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var Ts=Object.prototype.hasOwnProperty;var Is=(r,e)=>{for(var t in e)Ni(r,t,{get:e[t],enumerable:!0})},As=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xs(e))!Ts.call(r,n)&&n!==t&&Ni(r,n,{get:()=>e[n],enumerable:!(i=Es(e,n))||i.enumerable});return r};var Ds=r=>As(Ni({},"__esModule",{value:!0}),r);var Hu={};Is(Hu,{DEFAULT_PIXEL_CONFIG:()=>Qe,Pixel:()=>qe,PixelConfigurationError:()=>F,SDK_VERSION:()=>Li,createPixel:()=>ls,resolvePixelConfig:()=>Ye,resolveStorageAdapterName:()=>xn});module.exports=Ds(Hu);var Bi=["email","phone","name","firstName","lastName","address","address2","city","state","postalCode","country"],Te={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},te={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...Te}};function Un(r){return r?(Array.isArray(r)?r:[r]).map(t=>String(t).trim()).filter(Boolean):[]}function re(r,e){let t={};for(let i of Bi){let n=[...Un(r?.fields?.[i]),...Un(e?.[i])];n.length>0&&(t[i]=n)}return t}function de(r){switch(r){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var Vi={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Ui={enabled:!1,heartbeat:{enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},engagement:{enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:{activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},penalties:{idle:.2,rageClick:.1},thresholds:{lowMax:29,mediumMax:69}},rateLimit:{enabled:!1,windowMs:1e3,maxSignalsPerWindow:50,criticalBypass:!0},buffer:{enabled:!1,maxSize:200,maxAgeMs:3e4,flushSize:50,dropStrategy:"compress_similar",flushOnHidden:!0},stateMachine:{enabled:!1,historyLimit:50},sessionSummary:{enabled:!1,emitOnHidden:!1,emitOnDestroy:!0,minimumSessionMs:0},trackers:{scroll:{enabled:!1,thresholds:[25,50,75,100],debounceMs:100},click:{enabled:!1,rageClick:{enabled:!0,threshold:3,windowMs:500}},idle:{enabled:!1,thresholdMs:6e4},visibility:{enabled:!1},exitIntent:{enabled:!1},viewport:{enabled:!1,targets:[],rootMargin:"0px",observeMutations:!0,mutationDebounceMs:100,maxObservedElements:500}}};function wr(r,e){return{name:e==="click"?r:`${r}:${e}`,type:"selector",selector:`[data-track="${r}"]`,selectorType:"css",trigger:e}}function me(r){return{enabled:!0,sources:[wr(r,"click")]}}var zi={enabled:!0,manual:{pageView:{enabled:!0},purchase:{enabled:!0},lead:{enabled:!0},addToCart:{enabled:!0},removeFromCart:{enabled:!0},initiateCheckout:{enabled:!0},addPaymentInfo:{enabled:!0},search:{enabled:!0},viewContent:{enabled:!0}},auto:{enabled:!0,detectors:{lead:me("lead"),addToCart:me("add_to_cart"),removeFromCart:me("remove_from_cart"),initiateCheckout:me("initiate_checkout"),purchase:me("purchase"),addPaymentInfo:me("add_payment_info"),search:me("search"),viewContent:{enabled:!0,sources:[wr("view_content","click"),wr("view_content","hover"),wr("view_content","visible")]}}},rules:{enabled:!1,selectors:["[data-track]"],texts:["Comprar","Comprar Agora","Finalizar Compra","Checkout"],urlPatterns:["thank-you","purchase","success","order","checkout"],checkout:{enabled:!1},card:{enabled:!1}}};var qi={enabled:!0,pageView:{enabled:!0,trackInitialPageView:!0,spa:!0,dedupeMs:2e3},visitor:{enabled:!0,persistence:"cookie_localStorage",renew:!1},session:{enabled:!0,ttlMs:108e5,renewOnActivity:!0,renewOnPageView:!0},fingerprint:{enabled:!0,mode:"light",cache:!0},consent:{enabled:!1,required:!1,waitForConsent:!1},dedupe:{enabled:!0,windowMs:2e3},coordination:{enabled:!0,leaderElection:!0,broadcastChannel:!0},ordering:{enabled:!0,preserveOrder:!0},urlContext:{enabled:!1}};var Hi={enabled:!1,debug:!1,concurrency:3,timeoutMs:5e3,continueOnError:!0,destinations:{console:{enabled:!1},memory:{enabled:!1},mock:{enabled:!1},meta:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0},google:{enabled:!1,tagIds:[],autoPageView:!0,loadScript:!0},tiktok:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0}}};var $i={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var Rr="https://micro-service-pixel-production-4826.up.railway.app",T={enabled:!0,sender:{mode:"internal",baseUrl:Rr},persistence:{enabled:!0},replay:{enabled:!0},ordering:{enabled:!0},coordination:{enabled:!0},circuitBreaker:{enabled:!0,failureThreshold:5,resetTimeoutMs:3e4,halfOpenMaxAttempts:2},backpressure:{enabled:!0,maxQueueSize:500,policy:"drop_oldest",sampleRate:.5},deadLetter:{enabled:!0,maxEntries:200},compression:{enabled:!0,strategy:"identity"},retry:{enabled:!0,maxAttempts:4,baseDelayMs:500,maxDelayMs:4e3,multiplier:2},batch:{enabled:!0,batchSize:10,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Qe={app:{source:"custom",target:"custom",platform:"",environment:"production",debug:!1},identity:{pixelId:""},transport:{...T,sender:{...T.sender},persistence:{...T.persistence},replay:{...T.replay},ordering:{...T.ordering},coordination:{...T.coordination},circuitBreaker:{...T.circuitBreaker},backpressure:{...T.backpressure},deadLetter:{...T.deadLetter},compression:{...T.compression},retry:{...T.retry},batch:{...T.batch},timeout:{...T.timeout},offline:{...T.offline},flush:{...T.flush}},storage:{prefix:"__gmk",namespace:"pixel",persistence:{visitor:"localStorage",session:"sessionStorage",attribution:"localStorage"},queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Vi},commerce:{...te,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...te.enrichment}},modules:{core:qi,behavior:Ui,conversion:zi,integrations:Hi,privacy:$i}};var F=class extends Error{constructor(e,t,i){super(e),this.name="PixelConfigurationError",this.code=t,i!==void 0&&(this.cause=i)}};var Ki=128;function Rs(r){for(let e=0;e<r.length;e+=1){let t=r.charCodeAt(e);if(t<=31||t>=127&&t<=159)return!0}return!1}function Wi(r){if(typeof r!="string")throw new F("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");let e=r.trim();if(e.length===0)throw new F("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");if(e.length>Ki)throw new F(`identity.pixelId exceeds the maximum length of ${Ki} characters.`,"INVALID_PIXEL_ID");if(Rs(e))throw new F("identity.pixelId must not contain control characters.","INVALID_PIXEL_ID");return e}var zn=new Set(["__proto__","prototype","constructor"]);function je(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Ie(r){if(Array.isArray(r))return r.map(e=>Ie(e));if(je(r)){let e={};for(let t of Object.keys(r))zn.has(t)||(e[t]=Ie(r[t]));return e}return r}function qn(r,e,t){if(e===void 0)return r;if(Array.isArray(e))return Ie(e);if(typeof e=="function"||!je(e))return e;let i=je(r)?Ie(r):{};for(let n of Object.keys(e)){if(zn.has(n))continue;let o=e[n];if(o===void 0)continue;let s=t?`${t}.${n}`:n;if(s==="transport.sender"){i[n]=Ie(o);continue}i[n]=qn(i[n],o,s)}return i}function Ye(r){if(!je(r))throw new F("Pixel settings must be a plain object.","INVALID_SETTINGS");let e=qn(Ie(Qe),r,""),t=je(r.identity)?r.identity.pixelId:void 0;return e.identity={...e.identity,pixelId:Wi(t)},e}var Ms=/^(password|pass|secret|token|access[_-]?token|refresh[_-]?token|authorization|auth|cookie|set[_-]?cookie|cvv|cvc|pan|card[_-]?number|security[_-]?code|private[_-]?key|client[_-]?secret|api[_-]?key)$/i,$n=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Kn=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,Wn=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,Gn=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,Ps=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function Qn(r){let e=r.indexOf("@");return e<=1?"***":`${r[0]}***${r.slice(e)}`}function jn(r){let e=r.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function Yn(r){let e=r.trim();return e.length<=1?"*":`${e[0]}***`}function _s(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function Gi(r){let e=r.trim();if(!e)return!1;if(Ms.test(e)||$n.test(e)||Kn.test(e)||Wn.test(e)||Gn.test(e))return!0;let t=_s(e);return!!Ps.test(t)}function Hn(r,e){return typeof e!="string"?"[Redacted]":$n.test(r)||/email/i.test(r)?Qn(e):Kn.test(r)||/phone|telefone|tel/i.test(r)?jn(e):Wn.test(r)?Yn(e):(Gn.test(r),"[Redacted]")}function Xn(r){try{return structuredClone(r)}catch{try{return JSON.parse(JSON.stringify(r))}catch{return r}}}function Xe(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;if(r instanceof Map){for(let[,e]of r)e&&typeof e=="object"&&Xe(e);return Object.freeze(r)}if(r instanceof Set){for(let e of r)e&&typeof e=="object"&&Xe(e);return Object.freeze(r)}for(let e of Reflect.ownKeys(r)){let t=r[e];t&&typeof t=="object"&&Xe(t)}return Object.freeze(r)}function Ae(r,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof r=="string")return r.length>512?`${r.slice(0,512)}\u2026[truncated]`:r;if(Array.isArray(r)){let t=r.slice(0,100).map(i=>Ae(i,e+1));return r.length>100&&t.push(`[Truncated:${r.length-100}_more]`),t}if(r instanceof Map){let t={},i=0;for(let[n,o]of r){if(i++>=100){t.__truncated__=!0;break}t[String(n)]=Ae(o,e+1)}return t}if(r instanceof Set)return Ae([...r],e);if(r&&typeof r=="object"){let t={};for(let[i,n]of Object.entries(r))t[i]=Ae(n,e+1);return t}return r}function pe(r,e=new WeakSet){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="bigint")return String(r);if(typeof r=="function"||typeof r=="symbol")return"[Unavailable]";if(typeof r!="object")return String(r);if(e.has(r))return"[Circular]";if(e.add(r),Array.isArray(r))return r.map(i=>pe(i,e));if(r instanceof Map){let i={};for(let[n,o]of r){let s=String(n);i[s]=Gi(s)?Hn(s,o):pe(o,e)}return i}if(r instanceof Set)return[...r].map(i=>pe(i,e));let t={};for(let[i,n]of Object.entries(r)){if(Gi(i)){t[i]=Hn(i,n);continue}t[i]=pe(n,e)}return t}function Qi(r){return pe(r)}function ji(r){let e=Xn(r),t=pe(e),i=Ae(t);return Xe(i)}function Yi(r){let e=[],t=[],i=(u,c,d)=>{e.push({id:u,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${u}: ${d}`:u)};if(r.runtimeInitialized?r.runtimeDestroyed?i("runtime","unknown","Runtime destroyed"):i("runtime","healthy"):i("runtime","unknown","Runtime not initialized"),!r.transport.enabled)i("transport","healthy","Transport disabled by config");else if(!r.transport.state)i("transport","unknown","Transport state unavailable");else{let u=r.transport.state;u.circuitBreakerState==="open"?i("circuitBreaker","unhealthy","Circuit breaker open"):u.circuitBreakerState==="half_open"?i("circuitBreaker","degraded","Circuit breaker half-open"):i("circuitBreaker","healthy"),u.online===!1?i("offline","degraded","Client offline"):u.online===!0?i("offline","healthy"):i("offline","unknown"),typeof u.dlqCount=="number"&&u.dlqCount>0?i("dlq","degraded",`DLQ has ${u.dlqCount} entries`):i("dlq","healthy")}r.integrations.enabled&&r.integrations.active===!1?i("integrations","degraded","Integrations enabled but inactive"):i("integrations","healthy"),r.behaviorViewport?.enabled===!0&&r.behaviorViewport.available===!1&&i("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let n=r.behaviorEngagement;if(n?.enabled===!0&&n.running===!0){let u=n.evaluationIntervalMs,c=n.lastDriftMs;n.hasError?i("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&u>0&&c>u&&i("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=r.behaviorRateLimit;if(o?.enabled===!0){let u=o.accepted+o.dropped;(u>0?o.dropped/u:0)>=.5&&o.dropped>0&&i("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${u} dropped`)}let s=r.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&i("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=r.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&i("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let l="healthy";return e.some(u=>u.status==="unhealthy")?l="unhealthy":e.some(u=>u.status==="degraded")?l="degraded":(e.every(u=>u.status==="unknown")||e.some(u=>u.status==="unknown")&&!r.runtimeInitialized)&&(l="unknown"),{status:l,checks:e,reasons:t}}function Xi(r){let e=r.services,t=r.transport.state,i={sdkVersion:r.sdkVersion,capturedAt:Date.now(),runtime:{initialized:r.runtimeInitialized,destroyed:r.runtimeDestroyed,moduleCount:r.moduleRegistry.length,activeModuleCount:r.moduleRegistry.filter(n=>n.initialized).length,moduleNames:r.moduleRegistry.map(n=>n.name),activeModuleNames:r.moduleRegistry.filter(n=>n.initialized).map(n=>n.name)},modules:r.moduleRegistry.map(n=>({id:n.name,configuredEnabled:n.configuredEnabled,initialized:n.initialized})),core:{enabled:r.moduleRegistry.some(n=>n.name==="core"&&n.configuredEnabled),visitorId:e?.visitorId??null,sessionId:e?.sessionId??null,sessionExpired:e?.sessionExpired??null,fingerprint:e?.fingerprint??null,urlContextEnabled:e?.urlContextEnabled??!1},urlContext:e?.urlContextSnapshot?{enabled:e.urlContextEnabled,available:!0,managedKeys:Object.keys(e.urlContextSnapshot.managed),forwardedKeys:Object.keys(e.urlContextSnapshot.forwarded),source:{...e.urlContextSnapshot.source},queryParamCount:e.urlContextSnapshot.queryParamCount}:{enabled:!1,available:!1,managedKeys:[],forwardedKeys:[],source:{},queryParamCount:0},attribution:{enabled:e?.attributionEnabled??!1,available:e?.attributionIdentifiers!=null,identifierKeys:e?.attributionIdentifiers?Object.keys(e.attributionIdentifiers):[],identifiers:e?.attributionIdentifiers?{...e.attributionIdentifiers}:{}},commerce:{enabled:e?.commerceEnabled??!1,available:e!=null,mode:e?.commerceMode??null,currency:e?.commerceCurrency??null,catalogSize:e?.catalogSize??0,itemCount:e?.itemCount??0,cartValue:e?.cartValue??null,productIds:e?.productIds??[]},behavior:{enabled:r.behaviorEnabled,configuredTrackers:[...r.behaviorTrackers],configuredEngines:[...r.behaviorEngines],heartbeat:r.behaviorHeartbeat?{enabled:r.behaviorHeartbeat.enabled,initialized:r.behaviorHeartbeat.initialized,running:r.behaviorHeartbeat.running,intervalMs:r.behaviorHeartbeat.intervalMs,hiddenIntervalMs:r.behaviorHeartbeat.hiddenIntervalMs,sequence:r.behaviorHeartbeat.sequence,emittedCount:r.behaviorHeartbeat.emittedCount,skippedCount:r.behaviorHeartbeat.skippedCount,lastEmittedAt:r.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:r.behaviorHeartbeat.nextExpectedAt,lastDriftMs:r.behaviorHeartbeat.lastDriftMs}:null,viewport:r.behaviorViewport?{enabled:r.behaviorViewport.enabled,initialized:r.behaviorViewport.initialized,available:r.behaviorViewport.available,targetCount:r.behaviorViewport.targetCount,matchedElementCount:r.behaviorViewport.matchedElementCount,observedElementCount:r.behaviorViewport.observedElementCount,activeElementCount:r.behaviorViewport.activeElementCount,pendingElementCount:r.behaviorViewport.pendingElementCount,enterCount:r.behaviorViewport.enterCount,exitCount:r.behaviorViewport.exitCount,mutationObserverEnabled:r.behaviorViewport.mutationObserverEnabled,maxObservedElements:r.behaviorViewport.maxObservedElements,limitReached:r.behaviorViewport.limitReached,lastEventAt:r.behaviorViewport.lastEventAt}:null,engagement:r.behaviorEngagement?{enabled:r.behaviorEngagement.enabled,initialized:r.behaviorEngagement.initialized,running:r.behaviorEngagement.running,score:r.behaviorEngagement.score,previousScore:r.behaviorEngagement.previousScore,peakScore:r.behaviorEngagement.peakScore,averageScore:r.behaviorEngagement.averageScore,level:r.behaviorEngagement.level,evaluationCount:r.behaviorEngagement.evaluationCount,emittedUpdateCount:r.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:r.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:r.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:r.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:r.behaviorEngagement.evaluationIntervalMs,lastDriftMs:r.behaviorEngagement.lastDriftMs,hasError:r.behaviorEngagement.hasError,signalCounts:{...r.behaviorEngagement.signalCounts}}:null,rateLimit:r.behaviorRateLimit?{...r.behaviorRateLimit}:null,buffer:r.behaviorBuffer?{...r.behaviorBuffer}:null,stateMachine:r.behaviorStateMachine?{...r.behaviorStateMachine}:null,sessionSummary:r.behaviorSessionSummary?{...r.behaviorSessionSummary}:null},conversion:{enabled:r.conversion.enabled,autoEnabled:r.conversion.autoEnabled,manualEnabledFlags:{...r.conversion.manualEnabledFlags},detectorCount:r.conversion.detectorCount,activeDetectors:[...r.conversion.activeDetectors],dedupeKeyCount:r.conversion.dedupeKeyCount},integrations:{enabled:r.integrations.enabled,available:!0,active:r.integrations.active,destinationNames:[...r.integrations.destinationNames],metrics:r.integrations.metrics?{...r.integrations.metrics}:null},transport:t?{enabled:r.transport.enabled,available:!0,online:t.online,senderMode:t.senderMode,queueSize:t.queueSize,sentCount:t.sentCount,ackCount:t.ackCount,inFlight:t.inFlight,retryPending:t.retryPending,circuitBreakerState:t.circuitBreakerState,dlqCount:t.dlqCount,isLeader:t.isLeader,persistenceEnabled:t.persistenceEnabled}:{enabled:r.transport.enabled,available:!1,online:"unknown",senderMode:r.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:Yi(r),warnings:Ls(r),errors:[],config:r.configSafe};return ji(i)}function Ls(r){let e=[];return r.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),r.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),r.transport.enabled&&!r.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var Ze=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return Xi(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),i=e.getDebugServices(),n=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=n.getDebugState(),l=this.deps.getRegisteredModules(),u=new Set(e.getInitializedModuleNames()),c=l.map(P=>({name:P.name,configuredEnabled:P.configuredEnabled,initialized:u.has(P.name)})),d=null;if(i){let P=i.urlContext.isEnabled()?i.urlContext.getSnapshot():null,On=i.commerce.state.getSnapshot(),Fn=i.commerce.catalog.list(),Nn=On.selectedItems??[],Bn=0;for(let ee of Nn){let Ge=typeof ee.price=="number"?ee.price:void 0,Ss=Fn.find(Cs=>Cs.id===ee.productId)?.price;Bn+=(Ge??Ss??0)*(ee.quantity??1)}let vs=i.attribution.getSnapshot(),Vn={};for(let[ee,Ge]of Object.entries(vs))typeof Ge=="string"&&Ge.length>0&&(Vn[ee]=Ge);let bs=t.modules.core.session.ttlMs;d={visitorId:i.visitor.getVisitorId(),sessionId:i.session.getSessionId(),sessionExpired:i.session.isExpired(bs),fingerprint:i.fingerprint.getFingerprint(),urlContextEnabled:i.urlContext.isEnabled(),urlContextSnapshot:P?{managed:{...P.urlContext.managed??{}},forwarded:{...P.urlContext.forwarded??{}},source:{...P.urlContext.source??{}},queryParamCount:Object.keys(P.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Vn,commerceEnabled:i.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:Fn.length,itemCount:On.count,cartValue:Bn,productIds:Nn.map(ee=>ee.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,h=t.modules.behavior.heartbeat,p=t.modules.behavior.engagement,f=m?.viewport,b=[];m?.scroll?.enabled&&b.push("scroll"),m?.click?.enabled&&b.push("click"),m?.visibility?.enabled&&b.push("visibility"),m?.idle?.enabled&&b.push("idle"),m?.exitIntent?.enabled&&b.push("exitIntent"),f?.enabled===!0&&b.push("viewport");let S=[];h?.enabled===!0&&S.push("heartbeat"),p?.enabled===!0&&S.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&S.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&S.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&S.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&S.push("sessionSummary");let O=this.deps.getBehaviorModule(),Oi=O.getHeartbeatSnapshot()??null??(h?{enabled:h.enabled===!0,initialized:!1,running:!1,intervalMs:h.intervalMs??15e3,hiddenIntervalMs:h.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),us=O.getViewportSnapshot()??null??(f?{enabled:f.enabled===!0,initialized:!1,available:!1,targetCount:f.targets?.length??0,matchedElementCount:0,observedElementCount:0,activeElementCount:0,pendingElementCount:0,enterCount:0,exitCount:0,mutationObserverEnabled:!1,maxObservedElements:f.maxObservedElements??500,limitReached:!1,lastEventAt:void 0}:null),cs=O.getEngagementSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,score:0,previousScore:0,peakScore:0,averageScore:0,level:"low",evaluationCount:0,emittedUpdateCount:0,emittedSummaryCount:0,lastEvaluatedAt:void 0,lastEmittedAt:void 0,evaluationIntervalMs:p.evaluationIntervalMs??5e3,lastDriftMs:void 0,hasError:!1,signalCounts:{HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0}}:null),$e=t.modules.behavior.rateLimit,xe=t.modules.behavior.buffer,Ln=t.modules.behavior.stateMachine,Ke=t.modules.behavior.sessionSummary,ds=O.getRateLimitSnapshot()??($e?{enabled:$e.enabled===!0,windowMs:$e.windowMs??1e3,maxSignalsPerWindow:$e.maxSignalsPerWindow??50,criticalBypass:$e.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),ms=O.getBufferSnapshot()??(xe?{enabled:xe.enabled===!0,size:0,maxSize:xe.maxSize??200,flushSize:xe.flushSize??50,maxAgeMs:xe.maxAgeMs??3e4,dropStrategy:xe.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),ps=O.getStateMachineSnapshot()??(Ln?{enabled:Ln.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),hs=O.getSessionSummarySnapshot()??(Ke?{enabled:Ke.enabled===!0,emitOnHidden:Ke.emitOnHidden===!0,emitOnDestroy:Ke.emitOnDestroy!==!1,minimumSessionMs:Ke.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),J=t.modules.conversion.manual,gs={lead:J.lead?.enabled===!0,addToCart:J.addToCart?.enabled===!0,removeFromCart:J.removeFromCart?.enabled===!0,initiateCheckout:J.initiateCheckout?.enabled===!0,addPaymentInfo:J.addPaymentInfo?.enabled===!0,purchase:J.purchase?.enabled===!0,viewContent:J.viewContent?.enabled===!0,search:J.search?.enabled===!0},fs=t.modules.conversion.auto?.detectors??{},ys=Object.values(fs).filter(P=>P&&typeof P=="object"&&P.enabled).length,Fi=s.getDebugState(),kr=a?.delivery,We=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:b,behaviorEngines:S,behaviorHeartbeat:Oi,behaviorViewport:us,behaviorEngagement:cs,behaviorRateLimit:ds,behaviorBuffer:ms,behaviorStateMachine:ps,behaviorSessionSummary:hs,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:gs,detectorCount:ys,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:Fi?.active===!0,destinationNames:[...Fi?.destinationNames??[]],metrics:Fi?.metrics??null},transport:{enabled:t.transport.enabled===!0,state:a?{online:kr?.offline?.isOnline??"unknown",senderMode:We?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:kr?.ackCount??0,inFlight:kr?.inFlight??!1,retryPending:kr?.retry?.pendingCount??0,circuitBreakerState:String(We?.circuitBreaker?.state??"unavailable"),dlqCount:We?.deadLetter?.count??0,isLeader:We?.coordination?.isLeader??!0,persistenceEnabled:We?.storage?.persistenceEnabled??!1}:null},configSafe:Os(t)}}};function Os(r){let e={app:{environment:r.app.environment,debug:r.app.debug,source:r.app.source,target:r.app.target,platform:r.app.platform},identity:{pixelId:r.identity.pixelId?"[Present]":"[Missing]"},transport:{enabled:r.transport.enabled,sender:{mode:r.transport.sender.mode}},modules:{core:{enabled:r.modules.core.enabled},behavior:{enabled:r.modules.behavior.enabled},conversion:{enabled:r.modules.conversion.enabled,auto:{enabled:r.modules.conversion.auto?.enabled}},integrations:{enabled:r.modules.integrations.enabled},privacy:{enabled:r.modules.privacy.enabled}},commerce:{enabled:r.commerce?.enabled,currency:r.commerce?.currency,cartMode:r.commerce?.cart?.mode},attribution:{enabled:r.attribution?.enabled}};return Qi(e)}var Je=class{constructor(e){this.name="diagnostics";this.active=!1;this.snapshotService=e}init(e){this.active||(this.snapshotService.markAlive(),this.active=!0)}destroy(){this.active&&(this.snapshotService.markDestroyed(),this.active=!1)}getSnapshotService(){return this.snapshotService}};var U=class{constructor(){this.listeners=new Map;this.cleared=!1;this.signalSeq=0}publish(e){if(this.cleared)return;let t=this.listeners.get(e.type);if(!(!t||t.size===0))for(let i of[...t])try{i(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}}clear(){this.listeners.clear(),this.cleared=!0}reset(){this.listeners.clear(),this.cleared=!1,this.signalSeq=0}listenerCount(e){if(e)return this.listeners.get(e)?.size??0;let t=0;for(let i of this.listeners.values())t+=i.size;return t}createSignal(e,t,i){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...i?{data:i}:{}}}};var he=class{constructor(){this.nextId=1;this.pending=new Map;this.destroyed=!1}schedule(e,t){if(this.destroyed||typeof setTimeout>"u")return{id:-1};let i=this.nextId++,n={id:i},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(i),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(i,{handle:n,expectedAt:s,timer:a}),n}cancel(e){let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id))}cancelAll(){for(let e of this.pending.values())clearTimeout(e.timer);this.pending.clear()}activeCount(){return this.pending.size}lastDriftMs(){return this.lastDrift}destroy(){this.destroyed||(this.cancelAll(),this.destroyed=!0)}reset(){this.cancelAll(),this.destroyed=!1,this.lastDrift=void 0}isDestroyed(){return this.destroyed}};var et=class{constructor(e){this.config=e}shouldEmit(e){return e.reason==="initial"||e.reason==="manual_evaluation"?!0:this.config.emitOnChange?Math.abs(e.score-e.previousScore)>=this.config.minScoreDelta:!1}};var ge=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var De={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function fe(r){return!Number.isFinite(r)||r<0?0:r>1?1:r}function Zn(r,e){return e<=0?0:fe(r/e)}var tt=class{constructor(e,t){this.config=e,this.levelResolver=t??new ge(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:fe(e.activeDurationMs/De.activeTimeMs),scroll:fe(e.maxScrollPercent/100),click:fe(e.clickCount/De.clicks),viewport:fe(e.viewportEntryCount/De.viewportEntries),visibility:Zn(e.visibleDurationMs,t),heartbeat:fe(e.heartbeatCount/De.heartbeats)}}calculate(e){let{weights:t,penalties:i}=this.config,n=this.computeComponents(e),o=n.activeTime*t.activeTime+n.scroll*t.scroll+n.click*t.click+n.viewport*t.viewport+n.visibility*t.visibility+n.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=i.idle*Zn(e.idleDurationMs,s),l=i.rageClick*fe(e.rageClickCount/De.rageClicks),u=(o-a-l)*100,c=Math.max(0,Math.min(100,Math.round(u))),d=this.levelResolver.resolve(c);return{components:n,weights:t,penalties:{idle:a,rageClick:l},rawScore:u,finalScore:c,level:d}}};var Jn={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},rt=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0;this.signalCounts={...Jn}}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0,this.signalCounts={...Jn}}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type in this.signalCounts&&(this.signalCounts[e.type]+=1),e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}getSignalCounts(){return{...this.signalCounts}}};var it=class{build(e){let{state:t}=e;return{score:e.score,peakScore:e.peakScore,averageScore:e.averageScore,level:e.level,activeDurationMs:t.activeDurationMs,idleDurationMs:t.idleDurationMs,visibleDurationMs:t.visibleDurationMs,hiddenDurationMs:t.hiddenDurationMs,maxScrollPercent:t.maxScrollPercent,clickCount:t.clickCount,rageClickCount:t.rageClickCount,viewportEntryCount:t.viewportEntryCount,heartbeatCount:t.heartbeatCount,startedAt:t.startedAt,endedAt:e.endedAt}}};var Fs=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],nt=class{constructor(e,t){this.id="engagement";this.accumulator=new rt;this.summaryBuilder=new it;this.initialized=!1;this.running=!1;this.destroyed=!1;this.hasError=!1;this.tickHandle=null;this.unsubscribers=[];this.score=0;this.lastEmittedScore=0;this.peakScore=0;this.scoreSum=0;this.evaluationCount=0;this.emittedUpdateCount=0;this.emittedSummaryCount=0;this.level="low";this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new U,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new he,this.ownsScheduler=!0);let i=new ge(this.config.thresholds);this.calculator=new tt(this.config,i),this.emissionPolicy=new et(this.config)}init(){if(this.initialized&&!this.destroyed)return;let e=Date.now();this.destroyed=!1,this.hasError=!1,this.accumulator.reset(e),this.ownsBus&&this.signalBus instanceof U&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof he&&this.scheduler.reset(),this.score=0,this.lastEmittedScore=0,this.peakScore=0,this.scoreSum=0,this.evaluationCount=0,this.emittedUpdateCount=0,this.emittedSummaryCount=0,this.level="low",this.lastEvaluatedAt=void 0,this.lastEmittedAt=void 0,this.tickHandle=null,this.bindSignals(),this.initialized=!0,this.running=!0,this.evaluate("initial"),this.scheduleNext()}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.initialized;this.running=!1,this.destroyed=!0,this.cancelTick(),e&&this.config.emitSummaryOnDestroy&&this.emitSummary(),this.unbindSignals(),this.ownsScheduler&&this.scheduler.destroy(),this.ownsBus&&this.signalBus instanceof U&&this.signalBus.clear(),this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}evaluateNow(){return!this.running||this.destroyed?null:this.evaluate("manual_evaluation")}activeTimerCount(){return this.scheduler.activeCount()}debugPublishSignal(e,t){this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,score:this.score,previousScore:this.lastEmittedScore,peakScore:this.peakScore,averageScore:this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,level:this.level,evaluationCount:this.evaluationCount,emittedUpdateCount:this.emittedUpdateCount,emittedSummaryCount:this.emittedSummaryCount,lastEvaluatedAt:this.lastEvaluatedAt,lastEmittedAt:this.lastEmittedAt,evaluationIntervalMs:this.config.evaluationIntervalMs,lastDriftMs:this.scheduler.lastDriftMs(),hasError:this.hasError,signalCounts:this.accumulator.getSignalCounts()}}bindSignals(){this.unbindSignals();for(let e of Fs)this.unsubscribers.push(this.signalBus.subscribe(e,t=>{this.destroyed||!this.running||this.accumulator.ingest(t)}))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(){this.cancelTick(),!(this.destroyed||!this.running)&&(this.tickHandle=this.scheduler.schedule(()=>this.tick(),this.config.evaluationIntervalMs))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){this.tickHandle=null,!(this.destroyed||!this.running)&&(this.evaluate("interval"),this.scheduleNext())}evaluate(e){let t=Date.now();this.accumulator.flush(t);let i;try{i=this.calculator.calculate(this.accumulator.getState())}catch{return this.hasError=!0,this.context.logger.warn("[Pixel] Engagement score calculation failed (isolated)"),null}return this.evaluationCount+=1,this.score=i.finalScore,this.level=i.level,this.scoreSum+=i.finalScore,i.finalScore>this.peakScore&&(this.peakScore=i.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:i.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(i.finalScore,i.level,e,t),i}emitUpdate(e,t,i,n){let o=this.lastEmittedScore,s=e-o;try{let a=this.context.services.eventBuilder.build({type:"ENGAGEMENT_UPDATE",category:"ENGAGEMENT",score:e,previousScore:o,delta:s,level:t,evaluatedAt:n,reason:i});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=n}catch{this.context.logger.warn("[Pixel] Engagement update emit failed (listener isolated)")}}emitSummary(){if(this.emittedSummaryCount>0)return;let e=Date.now();this.accumulator.flush(e);let t=this.accumulator.getState(),i=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,n=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:i,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...n});this.context.services.dispatcher.dispatch(o),this.emittedSummaryCount+=1}catch{this.emittedSummaryCount+=1,this.context.logger.warn("[Pixel] Engagement summary emit failed (listener isolated)")}}};var Mr=class{constructor(e){this.config=e}canEmit(e,t){if(t.destroyed)return{allow:!1,reason:"destroyed"};if(!t.running)return{allow:!1,reason:"not_running"};let i=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&i?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var Pr=class{constructor(e){this.config=e}build(e,t,i=Date.now()){let n=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!n&&o,idle:n,visible:o,elapsedMs:Math.max(0,i-e.startedAt)};return this.config.includeSnapshot?{...a,...e.lastActivityAt!==void 0?{lastActivityAt:e.lastActivityAt}:{},...e.idleSince!==void 0?{idleSince:e.idleSince}:{},...e.visibleSince!==void 0?{visibleSince:e.visibleSince}:{},...e.hiddenSince!==void 0?{hiddenSince:e.hiddenSince}:{}}:a}};var _r=class{constructor(e,t){this.id="heartbeat";this.scheduler=new he;this.initialized=!1;this.running=!1;this.destroyed=!1;this.tickHandle=null;this.unsubscribers=[];this.sequence=0;this.emittedCount=0;this.skippedCount=0;this.startedAt=0;this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0};this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new U,this.ownsBus=!0),this.policy=new Mr(t.config),this.snapshotBuilder=new Pr(t.config)}init(){this.initialized&&!this.destroyed||(this.destroyed=!1,this.scheduler.reset(),this.sequence=0,this.emittedCount=0,this.skippedCount=0,this.lastEmittedAt=void 0,this.nextExpectedAt=void 0,this.tickHandle=null,this.startedAt=Date.now(),this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0},this.seedEnvironmentState(),this.bindSignals(),this.initialized=!0,this.running=!0,this.config.fireImmediately?this.tick():this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState())))}destroy(){this.destroyed&&!this.initialized||(this.running=!1,this.destroyed=!0,this.cancelTick(),this.scheduler.destroy(),this.unbindSignals(),this.nextExpectedAt=void 0,this.ownsBus&&this.signalBus instanceof U&&this.signalBus.clear(),this.initialized=!1)}isInitialized(){return this.initialized}isRunning(){return this.running}getMetrics(){return{sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,intervalMs:this.config.intervalMs,hiddenIntervalMs:this.config.hiddenIntervalMs,sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}activeTimerCount(){return this.scheduler.activeCount()}seedEnvironmentState(){if(typeof document>"u")return;let e=Date.now(),t=document.visibilityState==="visible";this.activity.visible=t,t?(this.activity.visibleSince=e,this.activity.hiddenSince=void 0):(this.activity.hiddenSince=e,this.activity.visibleSince=void 0)}bindSignals(){if(this.unbindSignals(),this.unsubscribers.push(this.signalBus.subscribe("ACTIVITY",e=>{this.activity.lastActivityAt=e.timestamp,this.activity.idle=!1,this.activity.idleSince=void 0})),this.unsubscribers.push(this.signalBus.subscribe("IDLE",e=>{this.activity.idle=!0,this.activity.idleSince=e.timestamp;let t=e.data?.idleSince;typeof t=="number"&&(this.activity.idleSince=t)})),this.unsubscribers.push(this.signalBus.subscribe("VISIBLE",e=>{this.activity.visible=!0,this.activity.visibleSince=e.timestamp,this.activity.hiddenSince=void 0,this.rescheduleForVisibilityChange()})),this.unsubscribers.push(this.signalBus.subscribe("HIDDEN",e=>{this.activity.visible=!1,this.activity.hiddenSince=e.timestamp,this.rescheduleForVisibilityChange()})),typeof document<"u"){let e=()=>{if(typeof document>"u")return;let t=Date.now();document.visibilityState==="visible"?(this.activity.visible=!0,this.activity.visibleSince=t,this.activity.hiddenSince=void 0):(this.activity.visible=!1,this.activity.hiddenSince=t),this.rescheduleForVisibilityChange()};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",e)})}}rescheduleForVisibilityChange(){!this.running||this.destroyed||this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState()))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(e){this.cancelTick(),!(this.destroyed||!this.running)&&(this.nextExpectedAt=Date.now()+e,this.tickHandle=this.scheduler.schedule(()=>this.tick(),e))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){if(this.tickHandle=null,this.destroyed||!this.running)return;let e=this.readActivityState();this.policy.canEmit(e,{running:this.running,destroyed:this.destroyed}).allow?this.emitHeartbeat(e):this.skippedCount+=1,this.scheduleNext(this.policy.resolveIntervalMs(e))}readActivityState(){return{startedAt:this.startedAt,visible:this.activity.visible,idle:this.activity.idle,lastActivityAt:this.activity.lastActivityAt,idleSince:this.activity.idleSince,visibleSince:this.activity.visibleSince,hiddenSince:this.activity.hiddenSince}}emitHeartbeat(e){this.sequence+=1;let t=Date.now(),i=this.snapshotBuilder.build(e,this.sequence,t);try{let n=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...i});this.context.services.dispatcher.dispatch(n),this.emittedCount+=1,this.lastEmittedAt=t,this.signalBus.publish(this.signalBus.createSignal("HEARTBEAT","HeartbeatEngine",{sequence:this.sequence}))}catch{this.skippedCount+=1,this.context.logger.warn("[Pixel] Heartbeat emit failed (listener isolated)")}}};var ie={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},Zi={idle:.2,rageClick:.1},ot={lowMax:29,mediumMax:69},eo={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:ie,penalties:Zi,thresholds:ot},Ns=["activeTime","scroll","click","viewport","visibility","heartbeat"];function N(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function ne(r){return r<0?0:r>1?1:r}function Bs(r){let e={activeTime:ne(N(r?.activeTime,ie.activeTime)),scroll:ne(N(r?.scroll,ie.scroll)),click:ne(N(r?.click,ie.click)),viewport:ne(N(r?.viewport,ie.viewport)),visibility:ne(N(r?.visibility,ie.visibility)),heartbeat:ne(N(r?.heartbeat,ie.heartbeat))},t=0;for(let i of Ns)t+=e[i];return t<=0?{...ie}:{activeTime:e.activeTime/t,scroll:e.scroll/t,click:e.click/t,viewport:e.viewport/t,visibility:e.visibility/t,heartbeat:e.heartbeat/t}}function Vs(r){return{idle:ne(N(r?.idle,Zi.idle)),rageClick:ne(N(r?.rageClick,Zi.rageClick))}}function Us(r){let e=Math.round(N(r?.lowMax,ot.lowMax)),t=Math.round(N(r?.mediumMax,ot.mediumMax));return e>=0&&e<t&&t<100||(e=ot.lowMax,t=ot.mediumMax),{lowMax:e,mediumMax:t}}function to(r){return zs(r.engagement)}function zs(r){let e=r?.enabled===!0,t=Math.floor(N(r?.evaluationIntervalMs,eo.evaluationIntervalMs));t<1e3&&(t=1e3);let i=Math.floor(N(r?.minScoreDelta,eo.minScoreDelta));return i<0&&(i=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:r?.emitOnChange!==!1,minScoreDelta:i,emitSummaryOnDestroy:r?.emitSummaryOnDestroy!==!1,weights:Bs(r?.weights),penalties:Vs(r?.penalties),thresholds:Us(r?.thresholds)}}var ro={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},Lr=1e3;function io(r){return qs(r.heartbeat)}function qs(r){let e=r?.enabled===!0,t=typeof r?.intervalMs=="number"&&Number.isFinite(r.intervalMs)?Math.floor(r.intervalMs):ro.intervalMs;t<Lr&&(t=Lr);let i=typeof r?.hiddenIntervalMs=="number"&&Number.isFinite(r.hiddenIntervalMs)?Math.floor(r.hiddenIntervalMs):ro.hiddenIntervalMs;i<Lr&&(i=Lr);let n={enabled:e,intervalMs:t,hiddenIntervalMs:i,emitWhenHidden:r?.emitWhenHidden===!0,emitWhenIdle:r?.emitWhenIdle!==!1,includeSnapshot:r?.includeSnapshot!==!1,fireImmediately:r?.fireImmediately===!0};return typeof r?.minActivityWindowMs=="number"&&Number.isFinite(r.minActivityWindowMs)&&r.minActivityWindowMs>=0?{...n,minActivityWindowMs:Math.floor(r.minActivityWindowMs)}:n}var Hs=["drop_oldest","drop_newest","compress_similar"];function ye(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Ji(r,e){return typeof r=="boolean"?r:e}function $s(r){let e=Math.floor(ye(r?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ye(r?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:r?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:Ji(r?.criticalBypass,!0)}}function Ks(r){let e=Math.floor(ye(r?.maxSize,200));e<1&&(e=1);let t=Math.floor(ye(r?.maxAgeMs,3e4));t<0&&(t=0);let i=Math.floor(ye(r?.flushSize,50));i<1&&(i=1),i>e&&(i=e);let n=r?.dropStrategy&&Hs.includes(r.dropStrategy)?r.dropStrategy:"compress_similar";return{enabled:r?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:i,dropStrategy:n,flushOnHidden:Ji(r?.flushOnHidden,!0)}}function Ws(r){let e=Math.floor(ye(r?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:r?.enabled===!0,historyLimit:e}}function Gs(r){let e=Math.floor(ye(r?.minimumSessionMs,0));return e<0&&(e=0),{enabled:r?.enabled===!0,emitOnHidden:r?.emitOnHidden===!0,emitOnDestroy:Ji(r?.emitOnDestroy,!0),minimumSessionMs:e}}function no(r){return{rateLimit:$s(r.rateLimit),buffer:Ks(r.buffer),stateMachine:Ws(r.stateMachine),sessionSummary:Gs(r.sessionSummary)}}var oo=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var Qs=new Set(oo),st=class{constructor(e){this.windowTimestamps=[];this.accepted=0;this.dropped=0;this.bypassed=0;this.config=e}reset(){this.windowTimestamps=[],this.accepted=0,this.dropped=0,this.bypassed=0}evaluate(e,t){return this.config.enabled?this.config.criticalBypass&&Qs.has(e)?(this.bypassed+=1,"bypassed"):(this.prune(t),this.windowTimestamps.length<this.config.maxSignalsPerWindow?(this.windowTimestamps.push(t),this.accepted+=1,"accepted"):(this.dropped+=1,"dropped")):(this.accepted+=1,"accepted")}prune(e){let t=e-this.config.windowMs,i=0;for(let n of this.windowTimestamps)if(n<=t)i+=1;else break;i>0&&this.windowTimestamps.splice(0,i)}getSnapshot(){return{enabled:this.config.enabled,windowMs:this.config.windowMs,maxSignalsPerWindow:this.config.maxSignalsPerWindow,criticalBypass:this.config.criticalBypass,accepted:this.accepted,dropped:this.dropped,bypassed:this.bypassed,windowCount:this.windowTimestamps.length,windowStartedAt:this.windowTimestamps[0]}}};var so=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var ao=new Set(so),at=class{constructor(e){this.entries=[];this.flushCount=0;this.dropCount=0;this.compressedCount=0;this.config=e}reset(){this.entries=[],this.flushCount=0,this.dropCount=0,this.compressedCount=0,this.lastFlushAt=void 0,this.lastFlushReason=void 0}size(){return this.entries.length}add(e,t){if(this.entries.length<this.config.maxSize){this.entries.push({signal:e,bufferedAt:t,count:1});return}switch(this.config.dropStrategy){case"drop_newest":this.dropCount+=1;return;case"drop_oldest":this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1});return;case"compress_similar":default:this.addCompressed(e,t);return}}addCompressed(e,t){if(!ao.has(e.type))for(let n=this.entries.length-1;n>=0;n-=1){let o=this.entries[n];if(o&&o.signal.type===e.type){this.entries[n]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let i=this.findOldestCompressibleIndex();i>=0?this.entries.splice(i,1):this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1})}findOldestCompressibleIndex(){for(let e=0;e<this.entries.length;e+=1){let t=this.entries[e];if(t&&!ao.has(t.signal.type))return e}return-1}shouldFlushBySize(){return this.entries.length>=this.config.flushSize}hasAgedEntries(e){if(this.config.maxAgeMs<=0)return!1;let t=this.entries[0];return t?e-t.bufferedAt>=this.config.maxAgeMs:!1}flush(e,t){let i=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,i}getSnapshot(){return{enabled:this.config.enabled,size:this.entries.length,maxSize:this.config.maxSize,flushSize:this.config.flushSize,maxAgeMs:this.config.maxAgeMs,dropStrategy:this.config.dropStrategy,flushCount:this.flushCount,dropCount:this.dropCount,compressedCount:this.compressedCount,lastFlushAt:this.lastFlushAt,lastFlushReason:this.lastFlushReason}}};var js={NOT_INITIALIZED:["INITIALIZING","DESTROYING"],INITIALIZING:["ACTIVE","DESTROYING"],ACTIVE:["IDLE","HIDDEN","PAUSED","DESTROYING"],IDLE:["ACTIVE","HIDDEN","PAUSED","DESTROYING"],HIDDEN:["ACTIVE","IDLE","PAUSED","DESTROYING"],PAUSED:["ACTIVE","IDLE","HIDDEN","DESTROYING"],DESTROYING:["DESTROYED"],DESTROYED:["INITIALIZING"]},lt=class{constructor(e){this.state="NOT_INITIALIZED";this.generation=0;this.transitionCount=0;this.invalidTransitionCount=0;this.history=[];this.preHiddenState="ACTIVE";this.config=e}getState(){return this.state}getGeneration(){return this.generation}getHistory(){return this.history}beginInit(e){this.generation+=1,this.transition("INITIALIZING","init",e),this.transition("ACTIVE","init_complete",e)}beginDestroy(e){this.transition("DESTROYING","destroy",e)}finishDestroy(e){this.transition("DESTROYED","destroy_complete",e)}pause(e){return this.transition("PAUSED","pause",e)}resume(e){let t=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";return this.transition(t,"resume",e)}applySignal(e,t){switch(e){case"ACTIVITY":this.transition("ACTIVE","signal:ACTIVITY",t);break;case"IDLE":this.transition("IDLE","signal:IDLE",t);break;case"HIDDEN":(this.state==="ACTIVE"||this.state==="IDLE")&&(this.preHiddenState=this.state),this.transition("HIDDEN","signal:HIDDEN",t);break;case"VISIBLE":{if(this.state!=="HIDDEN")break;let i=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(i,"signal:VISIBLE",t);break}default:break}}transition(e,t,i){if(this.state===e)return!0;if(!(js[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:i,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=i,this.transitionCount+=1,this.pushHistory(o),!0}pushHistory(e){this.history.push(e),this.history.length>this.config.historyLimit&&this.history.splice(0,this.history.length-this.config.historyLimit)}getSnapshot(){return{enabled:this.config.enabled,state:this.state,previousState:this.previousState,generation:this.generation,changedAt:this.changedAt,transitionCount:this.transitionCount,invalidTransitionCount:this.invalidTransitionCount,historySize:this.history.length}}};var ut=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}};var Ys=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],ct=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new ut;this.unsubscribers=[];this.initialized=!1;this.running=!1;this.destroyed=!1;this.emittedCount=0;this.hiddenSummaryEmitted=!1;this.context=e,this.config=t.config,this.getEngagement=t.getEngagement,this.rateLimiter=new st(t.config.rateLimit),this.buffer=new at(t.config.buffer),this.stateMachine=new lt(t.config.stateMachine)}init(e){if(this.initialized&&!this.destroyed)return;let t=Date.now();this.signalBus=e,this.destroyed=!1,this.startedAt=t,this.hiddenSummaryEmitted=!1,this.rateLimiter.reset(),this.buffer.reset(),this.accumulator.reset(t),this.stateMachine.beginInit(t),this.bindSignals(),this.initialized=!0,this.running=!0}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.running;this.running=!1,this.destroyed=!0,this.unbindSignals();let t=Date.now();this.safe(()=>this.stateMachine.beginDestroy(t)),this.config.buffer.enabled&&this.safe(()=>this.drainBufferToAccumulator("destroy",t)),e&&this.config.sessionSummary.emitOnDestroy&&this.safe(()=>this.emitSummary("destroy",t)),this.safe(()=>this.stateMachine.finishDestroy(t)),this.signalBus=null,this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}flushNow(){!this.running||this.destroyed||this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",Date.now())}emitSummaryNow(e="hidden"){if(!this.running||this.destroyed)return!1;let t=Date.now();return this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",t),this.emitSummary(e,t)}getRateLimitSnapshot(){return this.rateLimiter.getSnapshot()}getBufferSnapshot(){return this.buffer.getSnapshot()}getStateMachineSnapshot(){return this.stateMachine.getSnapshot()}getSessionSummarySnapshot(){return{enabled:this.config.sessionSummary.enabled,emitOnHidden:this.config.sessionSummary.emitOnHidden,emitOnDestroy:this.config.sessionSummary.emitOnDestroy,minimumSessionMs:this.config.sessionSummary.minimumSessionMs,emittedCount:this.emittedCount,lastEmittedAt:this.lastEmittedAt,startedAt:this.startedAt}}bindSignals(){this.unbindSignals();let e=this.signalBus;if(e)for(let t of Ys)this.unsubscribers.push(e.subscribe(t,i=>this.handleSignal(i)))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}handleSignal(e){if(!(this.destroyed||!this.running))try{let t=e.timestamp;if(this.rateLimiter.evaluate(e.type,t)==="dropped")return;this.config.stateMachine.enabled&&this.stateMachine.applySignal(e.type,t),this.config.buffer.enabled?(this.buffer.add(e,t),this.buffer.shouldFlushBySize()?this.drainBufferToAccumulator("size",t):this.buffer.hasAgedEntries(t)&&this.drainBufferToAccumulator("age",t)):this.config.sessionSummary.enabled&&this.accumulator.ingest(e),e.type==="HIDDEN"?this.onHidden(t):(e.type==="VISIBLE"||e.type==="ACTIVITY")&&(this.hiddenSummaryEmitted=!1)}catch{this.context.logger.warn("[Pixel] Behavior runtime pipeline error (isolated)")}}onHidden(e){this.config.buffer.enabled&&this.config.buffer.flushOnHidden&&this.drainBufferToAccumulator("hidden",e),this.config.sessionSummary.enabled&&this.config.sessionSummary.emitOnHidden&&!this.hiddenSummaryEmitted&&this.emitSummary("hidden",e)&&(this.hiddenSummaryEmitted=!0)}drainBufferToAccumulator(e,t){let i=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let n of i)for(let o=0;o<n.count;o+=1)this.accumulator.ingest(n.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let i=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-i<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let n=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),l={activeDurationMs:n.activeDurationMs,idleDurationMs:n.idleDurationMs,visibleDurationMs:n.visibleDurationMs,hiddenDurationMs:n.hiddenDurationMs,maxScrollPercent:n.maxScrollPercent,clickCount:n.clickCount,rageClickCount:n.rageClickCount,viewportEntryCount:n.viewportEntryCount,viewportVisibleDurationMs:n.viewportVisibleDurationMs,heartbeatCount:n.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:i,endedAt:t,finalState:s};try{let u=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...l,generation:a,reason:e});return this.context.services.dispatcher.dispatch(u),this.emittedCount+=1,this.lastEmittedAt=t,!0}catch{return this.emittedCount+=1,this.lastEmittedAt=t,this.context.logger.warn("[Pixel] Behavior session summary emit failed (listener isolated)"),!0}}safe(e){try{e()}catch{this.context.logger.warn("[Pixel] Behavior runtime coordinator step failed (isolated)")}}};var k=class{constructor(e){this.active=!1;this.managedListeners=[];this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}clearManagedTimeout(e){return e&&clearTimeout(e),null}dispatchEngagement(e){let t=this.context.services.eventBuilder.build(e);this.context.services.dispatcher.dispatch(t)}};var Xs=100,dt=class extends k{constructor(t,i){super(t);this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0};this.throttleTimer=null;this.debounceTimer=null;this.lastScrollY=0;this.lastScrollTime=0;this.velocitySum=0;this.crossedThresholds=new Set;this.lastDispatchedMaxPercent=-1;this.lastDispatchAt=0;this.signalBus=i?.signalBus}onInit(){this.isWindowAvailable()&&(this.resetState(),this.lastScrollY=window.scrollY,this.lastScrollTime=Date.now(),this.addWindowListener("scroll",()=>this.handleScroll(),{passive:!0}))}onDestroy(){this.throttleTimer=this.clearManagedTimeout(this.throttleTimer),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resetState(){this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0},this.lastScrollY=0,this.lastScrollTime=0,this.velocitySum=0,this.crossedThresholds.clear(),this.lastDispatchedMaxPercent=-1,this.lastDispatchAt=0}getMaxScrollPercent(){if(!this.isWindowAvailable()||!this.isDocumentAvailable())return 0;let t=document.documentElement,i=document.body?document.body.scrollHeight:0,n=Math.max(t.scrollHeight,i),o=t.clientHeight;if(n<=o)return 100;let s=n-o,a=window.scrollY||window.pageYOffset;return Math.min(100,Math.round(a/s*100))}canDispatch(t){return Date.now()-this.lastDispatchAt>=t}handleScroll(){if(!this.isWindowAvailable())return;let{debounceMs:t}=this.context.config.modules.behavior.trackers.scroll;this.throttleTimer||(this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.updateScrollState(),this.maybeDispatchOnThresholdCrossing(t),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.maybeDispatchOnScrollEnd(t)},t)},Xs))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),i=window.scrollY||window.pageYOffset,n=this.getMaxScrollPercent();if(n>this.state.maxScrollPercent&&(this.state.maxScrollPercent=n),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(i-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=i,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:i}=this.context.config.modules.behavior.trackers.scroll,n=this.state.maxScrollPercent,o=!1;for(let s of i)n>=s&&!this.crossedThresholds.has(s)&&(this.crossedThresholds.add(s),o=!0);o&&this.canDispatch(t)&&this.emitScrollEvent()}maybeDispatchOnScrollEnd(t){this.state.maxScrollPercent!==this.lastDispatchedMaxPercent&&this.canDispatch(t)&&this.emitScrollEvent()}emitScrollEvent(){this.dispatchEngagement({type:"SCROLL",category:"ENGAGEMENT",maxScrollPercent:this.state.maxScrollPercent,scrollEvents:this.state.scrollEvents,scrollVelocityAvg:this.state.scrollVelocityAvg,lastScrollAt:this.state.lastScrollAt}),this.signalBus?.publish(this.signalBus.createSignal("SCROLL","ScrollTracker",{maxScrollPercent:this.state.maxScrollPercent})),this.lastDispatchedMaxPercent=this.state.maxScrollPercent,this.lastDispatchAt=Date.now()}};function en(r){if(!r)return;let e=r,t=r.classList?.length?Array.from(r.classList):void 0,i,n=e.innerText?.trim()??e.textContent?.trim();n&&(i=n.length>80?`${n.slice(0,80)}\u2026`:n);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:r.tagName?.toLowerCase(),id:r.id||void 0,classes:t,text:i,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function lo(r){if(!r||!(r instanceof Element))return"unknown";let e=r.tagName.toLowerCase(),t=r.id?`#${r.id}`:"",i=r.className&&typeof r.className=="string"?`.${r.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",n=[];return typeof r.getAttributeNames=="function"&&r.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=r.getAttribute(o);s!=null&&n.push(`${o}=${s.slice(0,50)}`)}),[e,t,i,n.join("|")].filter(Boolean).join("")}var mt=class extends k{constructor(t,i){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=i?.signalBus}onInit(){this.isDocumentAvailable()&&(this.resetState(),this.addDocumentListener("click",t=>this.handleClick(t),!0))}onDestroy(){this.clickHistory.clear(),this.rageCooldownUntil.clear()}resetState(){this.state={clickCount:0,rageClickCount:0,lastClickAt:0},this.clickHistory.clear(),this.rageCooldownUntil.clear()}handleClick(t){let i=Date.now(),{rageClick:n}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=i,this.signalBus?.publish(this.signalBus.createSignal("CLICK","ClickTracker",{clickCount:this.state.clickCount}));let o=t.target instanceof Element?t.target:null,s=t.currentTarget instanceof Element?t.currentTarget:null,a=en(o),l=en(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:i,target:a,currentTarget:l,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!n.enabled)return;let u=lo(o),c=this.rageCooldownUntil.get(u)??0;if(i<c)return;let m=(this.clickHistory.get(u)??[]).filter(h=>i-h<n.windowMs);m.push(i),this.clickHistory.set(u,m),m.length>=n.threshold&&(this.state.rageClickCount+=1,this.signalBus?.publish(this.signalBus.createSignal("RAGE_CLICK","ClickTracker",{rageClickCount:this.state.rageClickCount})),this.dispatchEngagement({type:"RAGE_CLICK",category:"ENGAGEMENT",threshold:n.threshold,windowMs:n.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(u),this.rageCooldownUntil.set(u,i+n.windowMs))}};var pt=class extends k{constructor(t,i){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=i?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),i=document.visibilityState==="visible";this.state={isVisible:i,visibleSince:t,hiddenAt:i?null:t},this.publishVisibilitySignal(),this.addDocumentListener("visibilitychange",()=>this.handleVisibilityChange()),this.emitVisibilityEvent()}onDestroy(){}handleVisibilityChange(){if(!this.isDocumentAvailable())return;let t=Date.now();document.visibilityState==="visible"?this.state={isVisible:!0,visibleSince:t,hiddenAt:null}:this.state={isVisible:!1,visibleSince:this.state.visibleSince,hiddenAt:t},this.publishVisibilitySignal(),this.emitVisibilityEvent()}publishVisibilitySignal(){this.signalBus&&(this.state.isVisible?this.signalBus.publish(this.signalBus.createSignal("VISIBLE","VisibilityTracker",{visibleSince:this.state.visibleSince})):this.signalBus.publish(this.signalBus.createSignal("HIDDEN","VisibilityTracker",{hiddenAt:this.state.hiddenAt})))}emitVisibilityEvent(){this.dispatchEngagement({type:"VISIBILITY_CHANGE",category:"ENGAGEMENT",isVisible:this.state.isVisible,visibleSince:this.state.visibleSince,hiddenAt:this.state.hiddenAt})}};var Zs=["mousemove","scroll","keydown","touchstart"],ht=class extends k{constructor(t,i){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=i?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Zs)this.addWindowListener(t,()=>this.onActivity(),{passive:!0})}}onDestroy(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.isIdle=!1,this.idleSince=0}get thresholdMs(){return this.context.config.modules.behavior.trackers.idle.thresholdMs}scheduleIdleCheck(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>this.enterIdle(),this.thresholdMs)}onActivity(){let t=Date.now();if(this.signalBus?.publish(this.signalBus.createSignal("ACTIVITY","IdleTracker",{at:t})),this.isIdle){let i=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:i})}this.scheduleIdleCheck()}enterIdle(){if(this.isIdle)return;let t=Date.now();this.isIdle=!0,this.idleSince=t,this.signalBus?.publish(this.signalBus.createSignal("IDLE","IdleTracker",{idleSince:t,thresholdMs:this.thresholdMs})),this.dispatchEngagement({type:"USER_IDLE",category:"ENGAGEMENT",idleSince:t,thresholdMs:this.thresholdMs})}};var Js=5,gt=class extends k{constructor(t){super(t);this.fired=!1}onInit(){this.isDocumentAvailable()&&(this.fired=!1,this.addDocumentListener("mousemove",t=>this.handleMouseMove(t),{passive:!0}))}onDestroy(){this.fired=!1}handleMouseMove(t){if(this.fired||t.clientY>Js)return;this.fired=!0;let i=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:i,clientY:t.clientY})}};function tn(r){if(!r)return;let e=r.classList?.length?Array.from(r.classList):void 0;return{tagName:r.tagName?r.tagName.toLowerCase():void 0,id:r.id||void 0,classes:e,role:r.getAttribute("role")??void 0,name:r.getAttribute("name")??void 0}}function W(r,e,t){return!Number.isFinite(r)||r<e?e:r>t?t:r}function ea(r){return typeof r=="string"&&r.trim().length>0}function ft(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function uo(r){let e=[],t=new Set,i=[],n=Array.isArray(r.targets)?r.targets:[];for(let a of n){let l=ta(a,t,e);l&&i.push(l)}let o=Math.max(0,ft(r.mutationDebounceMs,100)),s=Math.max(1,ft(r.maxObservedElements,500));return{enabled:r.enabled===!0,targets:i,rootMargin:ea(r.rootMargin)?r.rootMargin:"0px",observeMutations:r.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function ta(r,e,t){let i=typeof r?.key=="string"?r.key.trim():"";if(!i)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(i))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${i}".`}),null;let n=typeof r?.selector=="string"?r.selector.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${i}" ignored: empty selector.`}),null;e.add(i);let o=W(ft(r.enterThreshold,.5),0,1),s=W(ft(r.exitThreshold,0),0,o),a=Math.max(0,ft(r.minVisibleMs,0));return{key:i,selector:n,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:r.trackExit??!0,once:r.once??!1,includeElement:r.includeElement??!1}}function Or(r,e){return`${r}::${e}`}function ra(r,e,t){return{targetKey:r,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var Fr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(Or(e,t))}set(e){this.states.set(Or(e.targetKey,e.elementId),e)}getOrCreate(e,t,i){let n=Or(e,i),o=this.states.get(n);return o||(o=ra(e,t,i),this.states.set(n,o)),o}delete(e,t){let i=Or(e,t),n=this.states.get(i);n&&this.cancelTimer(n),this.states.delete(i)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,i]of this.states)e(i,t)}counts(){let e=0,t=0;for(let i of this.states.values())i.active&&(e+=1),i.pendingTimer!==null&&(t+=1);return{active:e,pending:t}}cancelTimer(e){e.pendingTimer!==null&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}size(){return this.states.size}};var Nr=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let i=this.elementIds.get(e);if(i!==void 0){let s=this.entriesById.get(i);if(s)return s.targets.add(t),{ok:!0,entry:s,isNewElement:!1}}if(this.entriesById.size>=this.maxObservedElements)return{ok:!1,reason:"limit_reached"};this.sequence+=1;let n=`vp_el_${this.sequence}`,o={elementId:n,element:e,targets:new Set([t])};return this.elementIds.set(e,n),this.entriesById.set(n,o),{ok:!0,entry:o,isNewElement:!0}}unregister(e){let t=this.elementIds.get(e);t!==void 0&&(this.elementIds.delete(e),this.entriesById.delete(t))}unregisterById(e){let t=this.entriesById.get(e);t&&this.elementIds.delete(t.element),this.entriesById.delete(e)}getByElement(e){let t=this.elementIds.get(e);return t!==void 0?this.entriesById.get(t):void 0}getById(e){return this.entriesById.get(e)}allObserved(){return Array.from(this.entriesById.values())}isObserved(e){return this.elementIds.has(e)}count(){return this.entriesById.size}isAtCapacity(){return this.entriesById.size>=this.maxObservedElements}disconnect(){this.entriesById.clear()}};function ia(){return typeof IntersectionObserver<"u"}function co(r){let e=new Set([0,1]);for(let t of r)e.add(W(t.enterThreshold,0,1)),e.add(W(t.exitThreshold,0,1));return Array.from(e).sort((t,i)=>t-i)}function mo(r,e){if(!ia())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(r,{root:null,rootMargin:e.rootMargin,threshold:e.thresholds}),error:void 0}}catch(t){return{available:!1,observer:void 0,error:t instanceof Error?t.message:"IntersectionObserver init failed"}}}var yt=class extends k{constructor(t,i){super(t);this.normalized=null;this.registry=null;this.stateStore=null;this.observer=null;this.observerAvailable=!1;this.mutationObserver=null;this.mutationTimer=null;this.initialized=!1;this.limitWarned=!1;this.enterCount=0;this.exitCount=0;this.signalBus=i.signalBus,this.rawConfig=i.config}onInit(){let t=uo(this.rawConfig);this.normalized=t,this.initialized=!0;for(let o of t.warnings)this.context.logger.warn(`[Pixel] ${o.code}: ${o.message}`);if(!t.enabled||t.targets.length===0||!this.isDocumentAvailable())return;this.registry=new Nr(t.maxObservedElements),this.stateStore=new Fr;let i=co(t.targets),n=mo(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:i});if(this.observerAvailable=n.available,!n.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${n.error??"IntersectionObserver unavailable"}`);return}this.observer=n.observer,this.scanAndObserve(t.targets),t.observeMutations&&typeof MutationObserver<"u"&&this.setupMutationObserver(t)}onDestroy(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observer?.disconnect(),this.observer=null,this.observerAvailable=!1,this.stateStore?.clear(),this.stateStore=null,this.registry?.disconnect(),this.registry=null,this.enterCount=0,this.exitCount=0,this.lastEventAt=void 0,this.limitWarned=!1,this.normalized=null,this.initialized=!1}getSnapshot(){let t=this.normalized,i=this.stateStore?.counts()??{active:0,pending:0},n=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:n,observedElementCount:n,activeElementCount:i.active,pendingElementCount:i.pending,enterCount:this.enterCount,exitCount:this.exitCount,mutationObserverEnabled:this.mutationObserver!==null,maxObservedElements:t?.maxObservedElements??0,limitReached:this.limitWarned,lastEventAt:this.lastEventAt}}scanAndObserve(t){for(let i of t)this.observeTarget(i)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let i;try{i=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}i.forEach(n=>this.registerElement(n,t))}registerElement(t,i){if(!this.registry||!this.observer)return;let n=this.registry.tryRegister(t,i);if(!n.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}n.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let i=document.body??document.documentElement;if(i)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(i,{childList:!0,subtree:!0})}catch{this.mutationObserver=null,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_OBSERVER_FAILED: MutationObserver init failed.")}}scheduleMutationRescan(t){this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=setTimeout(()=>{this.mutationTimer=null,this.handleMutationRescan(t)},t.mutationDebounceMs)}handleMutationRescan(t){this.registry&&(this.cleanupDisconnectedElements(),this.scanAndObserve(t.targets))}cleanupDisconnectedElements(){if(!this.registry||!this.stateStore)return;let t=this.registry.allObserved().filter(i=>!i.element.isConnected);for(let i of t){this.observer?.unobserve(i.element);for(let n of i.targets){let o=this.stateStore.get(n.key,i.elementId);o&&this.finalizeRemovedElement(o,n)}this.registry.unregister(i.element)}}finalizeRemovedElement(t,i){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(i.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let i of t){let n=this.registry.getByElement(i.target);if(n)for(let o of n.targets)this.processEntry(i,n.elementId,o)}}processEntry(t,i,n){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(n.key,n.selector,i);if(o.completed)return;let s=W(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,n,t,s);else{let a=t.isIntersecting&&s>=n.enterThreshold;this.handleCandidateEnter(o,n,a)}}handleCandidateEnter(t,i,n){if(this.stateStore){if(!n){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),i.minVisibleMs===0){this.confirmEnter(t,i);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,i)},i.minVisibleMs)}}}confirmEnter(t,i){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,i),i.once&&!i.trackExit&&(t.completed=!0,this.finishTargetCycle(t,i)))}handleActiveElement(t,i,n,o){if(!(!n.isIntersecting||o<=i.exitThreshold))return;let a=n.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,i,a)}completeCycle(t,i,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,n),i.once?(t.completed=!0,this.finishTargetCycle(t,i)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,i){if(this.registry){let n=this.registry.getById(t.elementId);n&&(n.targets.delete(i),n.targets.size===0&&(this.observer?.unobserve(n.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(i.key,t.elementId)}emitEnter(t,i){let n=t.enteredAt??Date.now(),o=W(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=n,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:i.key,elementId:t.elementId,visibilityRatio:o,enteredAt:n})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:n,minVisibleMs:i.minVisibleMs,...i.includeElement?{element:tn(s)}:{}})}emitExit(t,i,n){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),l=W(t.lastRatio,0,1),u=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:i.key,elementId:t.elementId,visibilityRatio:l,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:l,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:n,...i.includeElement?{element:tn(u)}:{}})}};var vt=class{constructor(){this.name="behavior";this.trackers=[];this.heartbeatEngine=null;this.engagementEngine=null;this.viewportTracker=null;this.signalBus=null;this.coordinator=null;this.coordinatorActive=!1;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Behavior module already initialized");return}let{enabled:t,trackers:i}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let n=new U;this.signalBus=n;let o=to(e.config.modules.behavior);if(o.enabled){let d=new nt(e,{config:o,signalBus:n});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=no(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new ct(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(n),this.coordinatorActive=!0);let l=[];i.scroll.enabled&&l.push(new dt(e,{signalBus:n})),i.click.enabled&&l.push(new mt(e,{signalBus:n})),i.visibility.enabled&&l.push(new pt(e,{signalBus:n})),i.idle.enabled&&l.push(new ht(e,{signalBus:n})),i.exitIntent.enabled&&l.push(new gt(e));let u=null;i.viewport.enabled&&(u=new yt(e,{signalBus:n,config:i.viewport}),l.push(u)),this.viewportTracker=u;for(let d of l)d.init();this.trackers=l;let c=io(e.config.modules.behavior);if(c.enabled){let d=new _r(e,{config:c,signalBus:n});d.init(),this.heartbeatEngine=d}else this.heartbeatEngine=null;this.active=!0}destroy(){if(!this.active){this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null,this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null;return}this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null;for(let e=this.trackers.length-1;e>=0;e-=1)this.trackers[e]?.destroy();this.trackers=[],this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null,this.active=!1}destroyCoordinator(){this.coordinatorActive&&this.coordinator&&this.coordinator.destroy(),this.coordinatorActive=!1}getHeartbeatSnapshot(){return this.heartbeatEngine?this.heartbeatEngine.getSnapshot():null}getViewportSnapshot(){return this.viewportTracker?this.viewportTracker.getSnapshot():null}getEngagementSnapshot(){return this.engagementEngine?this.engagementEngine.getSnapshot():null}getRateLimitSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getRateLimitSnapshot()}getBufferSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getBufferSnapshot()}getStateMachineSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getStateMachineSnapshot()}getSessionSummarySnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getSessionSummarySnapshot()}evaluateEngagementNow(){this.engagementEngine?.evaluateNow()}flushBufferNow(){this.coordinator?.flushNow()}emitSessionSummaryNow(e="hidden"){return this.coordinator?.emitSummaryNow(e)??!1}debugPublishSignal(e,t){this.signalBus&&this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}};var C=class{constructor(e){this.active=!1;this.managedListeners=[];this.observer=null;this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.observer?.disconnect(),this.observer=null,this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}observeDom(e){this.isDocumentAvailable()&&(this.observer?.disconnect(),this.observer=new MutationObserver(()=>e()),document.body&&this.observer.observe(document.body,{childList:!0,subtree:!0}))}clearManagedTimeout(e){return e&&clearTimeout(e),null}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}};function B(r,e,t){let i=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${r}:${e}:${i}`}var na=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function Q(r){return typeof Element<"u"&&r instanceof Element}function L(r){return typeof HTMLFormElement<"u"&&r instanceof HTMLFormElement}function bt(r){return typeof HTMLInputElement<"u"&&r instanceof HTMLInputElement}function _(r){if(r==null)return;let e=String(r).trim();return e.length>0?e:void 0}function rn(r){let e=_(r);if(!e)return;let t=e.replace(/[^\d.,-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let i=t.includes(","),n=t.includes(".");i&&n?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):i&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function nn(r){let e=_(r);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function po(r){if(bt(r)&&r.type==="password")return!0;let e=[r.getAttribute("name"),r.getAttribute("id"),r.getAttribute("autocomplete"),r.getAttribute("placeholder"),r.getAttribute("aria-label")].filter(Boolean).join(" ");return na.test(e)}function z(r,e){for(let t of e){if(!t)continue;let i=(t.startsWith("data-"),t),n=_(r.getAttribute(i));if(n)return n}}function G(r){if(!po(r)&&(bt(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement))return _(r.value)}function oa(r){return/^[#.\[:]/.test(r)||/[\s>+~]/.test(r)}function ho(r,e){for(let t of e)if(!(!t||!oa(t)))try{let i=r.matches(t)?r:r.querySelector(t);if(!i)continue;let n=G(i);if(n)return n}catch{}}function q(r,e){for(let i of e){if(!i)continue;let n=r.querySelector(`input[name="${Br(i)}"], textarea[name="${Br(i)}"], select[name="${Br(i)}"], input[id="${Br(i)}"]`);if(n){let o=G(n);if(o)return o}}let t=[];(bt(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&t.push(r),t.push(...Array.from(r.querySelectorAll("input, textarea, select")));for(let i of e){let n=i.toLowerCase();for(let o of t){if(po(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!sa(s,a,n))continue;let l=G(o);if(l)return l}}}function sa(r,e,t){return r===t||e===t?!0:t.length<4?!1:r.includes(t)||e.includes(t)}function Br(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function ke(...r){let e={};for(let t of r)if(t)for(let[i,n]of Object.entries(t))n==null||n===""||e[i]===void 0&&(e[i]=n);return e}function St(r,e){let t=new Set,i=[];for(let n of[...r??[],...e]){let o=n?.trim();!o||t.has(o)||(t.add(o),i.push(o))}return i}var aa=["email","emailaddress","customerEmail","customer_email","e-mail"],la=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],ua=["name","nome","fullName","full_name","fullname","billing_name"],ca=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name"],da=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name"],ma=["address","street","street_address","billing_address","shipping_address","endereco"],pa=["address2","address_2","apt","apartment","suite","complement","complemento"],ha=["city","cidade","billing_city","shipping_city"],ga=["state","estado","region","billing_state","shipping_state"],fa=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip"],ya=["country","pais","billing_country","country_code"],va=["data-email"],ba=["data-phone","data-telefone"],Sa=["data-name","data-nome"],Ca=["data-first-name","data-firstname"],Ea=["data-last-name","data-lastname"],xa=["data-address"],Ta=["data-address2","data-apt"],Ia=["data-city"],Aa=["data-state"],Da=["data-zip","data-postal"],ka=["data-country"],H=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!Q(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=L(i)?this.extractFromScope(i):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return ke(t,n,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return Q(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:ca,autocomplete:"given-name",attrs:Ca}),i=this.pick(e,{mappingKey:"lastName",defaults:da,autocomplete:"family-name",attrs:Ea}),n=this.pick(e,{mappingKey:"name",defaults:ua,autocomplete:"name",attrs:Sa}),o=t&&i?`${t} ${i}`:t??i,s=t&&i?o:n??o;return ke({email:this.pick(e,{mappingKey:"email",defaults:aa,type:"email",autocomplete:"email",attrs:va}),phone:this.pick(e,{mappingKey:"phone",defaults:la,type:"tel",autocomplete:"tel",attrs:ba}),name:_(s),firstName:t,lastName:i,address:this.pick(e,{mappingKey:"address",defaults:ma,autocomplete:["street-address","address-line1"],attrs:xa}),address2:this.pick(e,{mappingKey:"address2",defaults:pa,autocomplete:"address-line2",attrs:Ta}),city:this.pick(e,{mappingKey:"city",defaults:ha,autocomplete:"address-level2",attrs:Ia}),state:this.pick(e,{mappingKey:"state",defaults:ga,autocomplete:"address-level1",attrs:Aa}),postalCode:this.pick(e,{mappingKey:"postalCode",defaults:fa,autocomplete:"postal-code",attrs:Da}),country:this.pick(e,{mappingKey:"country",defaults:ya,autocomplete:["country-name","country"],attrs:ka})})}pick(e,t){let i=t.type?this.readTypedInput(e,t.type):void 0,n=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],o;for(let a of n)if(o=this.readAutocomplete(e,a),o)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return i??o??(t.attrs?z(e,t.attrs):void 0)??ho(e,s)??q(e,s)}fieldsFor(e,t){return St(this.fieldMappings[e],t)}readTypedInput(e,t){let i=`input[type="${t}"]`,n=e.matches(i)?e:e.querySelector(i);return n?G(n):void 0}readAutocomplete(e,t){let i=`input[autocomplete="${t}"], select[autocomplete="${t}"]`,n=e.matches(i)?e:e.querySelector(i);return n?G(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};var wa=["data-product-id","data-product","data-sku","data-item-id","data-id"],Ra=["data-product-name","data-name","data-item-name"],Ma=["data-product-price","data-price","data-value","data-amount"],Pa=["data-quantity","data-qty"],_a=["data-currency"],La=["productId","product_id","product","sku","item_id","id"],Oa=["productName","product_name","item_name","name"],Fa=["price","amount","value","product_price"],Na=["quantity","qty"],Ba=["currency"],Va=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),ve=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!Q(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=L(i)?this.extractFromScope(i):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return ke(t,n,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return Q(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=z(e,this.attrsFor("productId",wa))??q(e,this.fieldsFor("productId",La)),i=z(e,this.attrsFor("productName",Ra))??q(e,this.fieldsFor("productName",Oa)),n=z(e,this.attrsFor("price",Ma))??q(e,this.fieldsFor("price",Fa)),o=z(e,this.attrsFor("quantity",Pa))??q(e,this.fieldsFor("quantity",Na)),s=z(e,this.attrsFor("currency",_a))??q(e,this.fieldsFor("currency",Ba));return ke({productId:_(t),productName:_(i),price:rn(n),quantity:nn(o),currency:_(s)})}attrsFor(e,t){return St(this.attributeMappings[e],t)}fieldsFor(e,t){return St(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(Va)??null}};var go="all",fo="auto",Ua=["input","change","submit","click","auto"],za={email:{attrs:["data-email"],fields:["email","customerEmail","customer_email","e-mail"],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:["name","nome","fullName","full_name"],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:["firstName","first_name","primeiro","primeiro_nome","given-name"],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:["lastName","last_name","sobrenome","family-name"],autocomplete:"family-name"},productId:{attrs:["data-product-id","data-product","data-sku","data-item-id","data-id"],fields:["productId","product_id","product","sku","item_id","id"]},quantity:{attrs:["data-quantity","data-qty"],fields:["quantity","qty"]}},Ct=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?vo(e):null}getConfig(){return this.normalized?{...this.normalized,fields:[...this.normalized.fields]}:null}evaluate(e={}){if(!this.hasConfig||!this.normalized)return this.result({matched:!1,reason:"no_config",fields:[],filledFields:[],missingFields:[],values:{},config:null});let t=this.normalized;if(t.fields.length===0)return this.result({matched:!1,reason:"no_fields",fields:[],filledFields:[],missingFields:[],values:{},config:t});if(!this.isTriggerCompatible(t.trigger,e.trigger))return this.result({matched:!1,reason:"trigger_mismatch",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let i=this.resolveScope(e,t);if(i==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!i)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n={},o=[],s=[];for(let u of t.fields){let c=$a(i,u);c?(n[u]=c,o.push(u)):s.push(u)}let a=this.matchesRequirement(t,o.length,t.fields.length),l="matched";return a||(l=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:l,fields:[...t.fields],filledFields:o,missingFields:s,values:n,config:t})}matchesRequirement(e,t,i){if(e.minRequired!=null){let n=Math.max(0,e.minRequired);return t>=n}return e.mode==="any"?t>=1:t===i&&i>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let i=Q(e.element)?e.element:null;if(t.formSelector){let n=Ha(t.formSelector);return n?L(e.form)?n===e.form||n.contains(e.form)?n:null:i?n===i||n.contains(i)?n:null:n:"missing_form_selector"}if(L(e.form))return e.form;if(i){let n=qa(i);if(n)return n;let o=i.closest("form");if(L(o))return o}return Q(e.container)?e.container:i||null}result(e){return{...e,config:e.config?{...e.config,fields:[...e.config.fields]}:null,fields:[...e.fields],filledFields:[...e.filledFields],missingFields:[...e.missingFields],values:{...e.values}}}};function vo(r){if(r==null)return null;if(Array.isArray(r))return{fields:yo(r),mode:go,trigger:fo};if(typeof r!="object")return null;let e=yo(r.fields??[]),t=r.mode==="any"||r.mode==="all"?r.mode:go,i=Ua.includes(r.trigger)?r.trigger:fo,n={fields:e,mode:t,trigger:i};typeof r.minRequired=="number"&&Number.isFinite(r.minRequired)&&(n.minRequired=r.minRequired);let o=_(r.formSelector);return o&&(n.formSelector=o),typeof r.debounceMs=="number"&&Number.isFinite(r.debounceMs)&&(n.debounceMs=r.debounceMs),typeof r.fireOnce=="boolean"&&(n.fireOnce=r.fireOnce),n}function yo(r){let e=new Set,t=[];for(let i of r){let n=typeof i=="string"?i.trim():"";!n||e.has(n)||(e.add(n),t.push(n))}return t}function qa(r){if(bt(r)||r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement){let e=r.form;return L(e)?e:null}return null}function Ha(r){if(typeof document>"u")return null;try{return document.querySelector(r)}catch{return null}}function $a(r,e){let t=e.trim();if(!t)return;let i=za[t];if(i?.type){let s=Ka(r,i.type);if(s)return s}if(i?.autocomplete){let s=Wa(r,i.autocomplete);if(s)return s}if(i){let s=z(r,i.attrs);if(s)return s;let a=q(r,i.fields);if(a)return a}let n=Ga(t),o=z(r,[`data-${n}`,`data-${t}`]);return o||q(r,[t,n])}function Ka(r,e){let t=`input[type="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?G(i):void 0}catch{return}}function Wa(r,e){let t=`input[autocomplete="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?G(i):void 0}catch{return}}function Ga(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var we=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let i of e){if(!i||typeof i!="object")continue;let n=typeof i.id=="string"?i.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(i,n,t);this.productsById.set(n,o),this.orderedIds.push(n);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,i){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():i,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...o!==void 0?{currency:o}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var Re=class{constructor(e=[],t={}){this.itemsByProductId=new Map;this.allowDynamicItems=t.allowDynamicItems!==!1,this.seed(e??[])}getSelectedItems(){return Array.from(this.itemsByProductId.values()).map(e=>this.cloneItem(e))}hasItem(e){return!!e&&this.itemsByProductId.has(e)}getItem(e){if(!e)return null;let t=this.itemsByProductId.get(e);return t?this.cloneItem(t):null}upsertItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;if(e.selected===!1){this.itemsByProductId.delete(t);return}let i=this.normalizeQuantity(e.quantity);if(i<=0){this.itemsByProductId.delete(t);return}if(!this.itemsByProductId.has(t)&&!this.allowDynamicItems)return;let o=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:o?.metadata?{...o.metadata}:void 0,a={...o,...e,productId:t,quantity:i,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,a)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let i=this.normalizeQuantity(t);if(i<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:i})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let i=this.normalizeQuantity(e.quantity);i<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:i,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var oe=class{calculate(e){let i=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of i)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(i),o=this.resolveCurrency(e,i);return{items:i,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,i=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let o=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*o,i=!0}return i?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let i of t)if(typeof i.currency=="string"&&i.currency.trim())return i.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var se=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=ja(e.defaultCurrency),this.calculateValueFrom=de(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},i=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",o=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",a=y(t.priceId)??y(t.productId)??y(i.productId)??(s?this.lookupIdBySku(y(t.sku)??y(i.sku)):void 0),l=!a&&o?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let u=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(y(t.sku)??y(i.sku)):null,c=a??u?.id,d=o&&c?this.state.getItem(c)??l:null;if(n==="catalog"&&!c&&!u)return{data:{...t}};let m=y(t.productName)??y(i.productName)??u?.name,h=M(t.price)??M(i.price)??(o?M(d?.price):void 0)??u?.price,p=M(t.quantity)??M(i.quantity)??(o?M(d?.quantity):void 0)??u?.quantity??1,f=y(t.currency)??y(i.currency)??(o?y(d?.currency):void 0)??u?.currency??this.defaultCurrency,b=Qa(u,{priceId:y(t.priceId),productId:c,offerId:y(t.offerId),id:y(t.id)}),S={};b.id&&(S.id=b.id),b.priceId&&(S.priceId=b.priceId),b.productId&&(S.productId=b.productId),b.offerId&&(S.offerId=b.offerId),m&&(S.productName=m),h!==void 0&&(S.price=h),f&&(S.currency=f),p!==void 0&&(S.quantity=p);for(let[O,He]of Object.entries(t))He!==void 0&&(O in S||(S[O]=He));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(i=>this.catalog.getById(i.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},i=e.extractedProduct??{},n=y(t.productId)??y(i.productId)??this.lookupIdBySku(y(t.sku)??y(i.sku)),o=n?this.catalog.getById(n):null,s=n??o?.id,a=s?this.state.getItem(s):null,l=M(t.quantity)??M(i.quantity)??M(a?.quantity)??1,u={};s&&(u.productId=s),l!==void 0&&(u.quantity=l);for(let[c,d]of Object.entries(t))d!==void 0&&(c in u||(u[c]=d));return{data:u}}resolveCheckoutLike(e,t){let i={...e.payload??{}},n=M(i.value),o=y(i.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),u=l.map(b=>this.toPixelItem(b)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=n===void 0&&c,m=this.calculator.calculate({items:l,value:d?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),h=n!==void 0?n:c?m.value:void 0,p=o??m.currency??this.defaultCurrency,f={...i};return u.length>0?f.items=u:s===null&&delete f.items,h!==void 0?f.value=h:delete f.value,p&&(f.currency=p),{data:f,items:m.items,...h!==void 0?{value:h}:{},...p?{currency:p}:{}}}resolveViewContent(e){let t={...e.payload??{}},i=e.enrichmentSource??"event_or_cart";if(i==="cart"||i==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:i}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:i},!1),s={...t},a=y(t.contentId)??y(n.data.productId)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].id=="string"?o.data.items[0].id:void 0),l=y(t.contentName)??y(n.data.productName)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].name=="string"?o.data.items[0].name:void 0);return a&&(s.contentId=a),l&&(s.contentName=l),M(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!y(t.currency)&&o.currency&&(s.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(s.items=o.data.items),{data:s,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(i==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!y(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!y(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&M(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!y(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(i=>this.normalizeLooseItem(i));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(i=>this.normalizeLooseItem(i&&typeof i=="object"?i:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(i=>this.enrichItem(i));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="catalog"){let i=this.state.getSelectedItems();return i.length>0?i.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,i=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??i?.id;return{...e,...n?{productId:n}:{},productName:e.productName??i?.name,sku:e.sku??i?.sku,price:e.price??i?.price,quantity:e.quantity??i?.quantity??1,currency:e.currency??i?.currency??this.defaultCurrency,category:e.category??i?.category,variant:e.variant??i?.variant,brand:e.brand??i?.brand,type:e.type??i?.type,metadata:e.metadata??i?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:y(e.productId)??y(e.id),sku:y(e.sku),productName:y(e.productName)??y(e.name),price:M(e.price),quantity:M(e.quantity),currency:y(e.currency),category:y(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function Qa(r,e){let t=r?.metadata??{},i=y(t.priceId),n=y(t.productId),o=y(t.offerId),s=e.priceId??i;if(!s){let a=e.productId??r?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:o??e.offerId??s}}function y(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function M(r){if(!(typeof r!="number"||!Number.isFinite(r)))return r}function ja(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}var Me=class{constructor(e){this.config={...te,...e,catalog:{products:e?.catalog?.products??[]},cart:{...te.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Te,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new we(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new Re(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new se({catalog:this.catalog,state:this.state,calculator:new oe,defaultCurrency:this.config.currency,calculateValueFrom:de(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],i=Te[e];return{enabled:t?.enabled??i.enabled,source:t?.source??i.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,i={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:i,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),i=t.data.items??[],n=i[0],o=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&i.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...i.length>0?{items:i}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return de(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Ya(r){return r.trim().replace(/\s+/g," ")}function bo(r,e){let t=Ya(r);return e?t:t.toLowerCase()}function So(r,e){let t=r.textContent;if(t==null)return!1;let i=e.caseSensitive===!0,n=bo(t,i),o=bo(e.value,i);return o?e.exact===!0?n===o:n.includes(o):!1}function on(r,e){if(!So(r,e))return!1;let t=r.querySelectorAll("*");for(let i=0;i<t.length;i+=1){let n=t[i];if(n&&So(n,e))return!1}return!0}function Eo(r,e){if(typeof document>"u")return[];let t=e??document;if(r.closest)try{let i=[];t instanceof Element&&t.matches(r.closest)&&i.push(t),i.push(...Array.from(t.querySelectorAll(r.closest)));let n=[];for(let o of i)n.push(...Co(o,r));return Array.from(new Set(n))}catch{return[]}return Co(t,r)}function Co(r,e){let t=[],i=Array.from(r.querySelectorAll("*"));r instanceof Element&&i.unshift(r);for(let n of i)on(n,e)&&t.push(n);return t}var Xa={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},$=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let i=Array.isArray(e)?e:[e],n=[];for(let o of i){let s=this.normalizeInput(o,t);s&&n.push(s)}return n}queryAll(e,t="css",i){if(typeof document>"u")return[];let n=i??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,n));return Array.from(new Set(o))}matches(e,t,i="css"){for(let n of this.normalize(t,i))if(this.matchesNormalized(e,n))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let i=e.trim();if(!i)return null;let n=this.parsePrefix(i);return n?this.fromDescriptor({type:n.type,value:n.value}):this.fromDescriptor({type:t,value:i})}fromDescriptor(e){let t=e.value?.trim();return t?{type:e.type,value:t,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest}:null}parsePrefix(e){let t=e.indexOf(":");if(t<=0)return null;let i=e.slice(0,t).toLowerCase(),n=Xa[i];if(!n)return null;let o=e.slice(t+1).trim();return o?{type:n,value:o}:null}queryNormalized(e,t){if(e.type==="text")return Eo({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let i=this.toCssSelector(e);if(!i)return[];try{let n=Array.from(t.querySelectorAll(i));return e.closest?n.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):n}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${i}`,n),[]}}matchesNormalized(e,t){if(t.closest)try{if(e.closest(t.closest)==null)return!1}catch{return this.logger?.debug(`[SelectorResolver] Invalid closest selector ignored: ${t.closest}`),!1}if(t.type==="text")return on(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let i=this.toCssSelector(t);if(!i)return!1;try{return e.matches(i)}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${i}`,n),!1}}toCssSelector(e){if(e.type==="text")return null;let{value:t}=e;if(t.startsWith("[")||t.startsWith(".")||t.startsWith("#"))return t;switch(e.type){case"id":return`#${xo(t)}`;case"class":return`.${xo(t)}`;case"attribute":return`[data-track="${Za(t)}"]`;case"css":return t;default:return t}}};function xo(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function Za(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Vr=class extends C{constructor(t,i,n){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=i,this.options=n;let{source:o}=n;this.formEvaluator=new Ct(o.selectorForm),this.selectorResolver=new $(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=Ja(o),this.origin=n.origin??B("form",n.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:re(s?.customer,s?.mappings?.fields)}),this.productExtractor=new ve({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),l=o.debounceMs,u=a?.debounceMs;this.debounceMs=typeof l=="number"&&l>0?l:typeof u=="number"&&u>0?u:0,this.fireOnce=o.fireOnce===!0||a?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType}:${this.options.source.name})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",i=this.resolveDomEvents(t);for(let n of i)this.addDocumentListener(n,o=>this.handleDomEvent(o,n),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,i){if(this.destroyed||this.fireOnce&&this.hasFired)return;let n=i,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,n))return;let s=this.formEvaluator.evaluate({element:o,trigger:n});if(!s.matched){this.context.logger.debug(`[ConfiguredFormDetector] ${this.options.eventType} skipped: ${s.reason}`);return}let a=this.buildPayload(o);a!==null&&this.scheduleTrack(a)}isEventInScope(t,i){if(this.hasSelector&&!this.matchesSelector(t))return!1;let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let o=document.querySelector(n);if(!o)return!1;if(!t)return i!=="click";if(o!==t&&!o.contains(t))return!1}catch{return!1}return!0}matchesSelector(t){if(!t||!this.options.source.selector)return!1;let i=t;for(;i&&i!==document.body;){if(this.selectorResolver.matches(i,this.options.source.selector,this.selectorType))return!0;i=i.parentElement}return!1}resolveCustomerRoot(t){let i=this.formEvaluator.getConfig()?.formSelector;if(i&&typeof document<"u")try{let n=document.querySelector(i);if(n)return n}catch{}return t}buildPayload(t){let{eventType:i}=this.options;if(i==="LEAD"){let n=this.resolveCustomerRoot(t),o=L(n)?this.customerExtractor.extractFromForm(n):this.customerExtractor.extractFromElement(n);return!o.email&&!o.phone&&!o.name?(this.context.logger.debug("[ConfiguredFormDetector] LEAD skipped: no email/phone/name"),null):{...o.email?{email:o.email}:{},...o.phone?{phone:o.phone}:{},...o.name?{name:o.name}:{}}}if(i==="ADD_TO_CART"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}return{}}scheduleTrack(t){if(this.debounceMs<=0){this.track(t);return}this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,!this.destroyed&&this.track(t)},this.debounceMs)}track(t){this.destroyed||this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,t,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};function Ja(r){return r.selectorType??"css"}var el=new Set(["id","priceId","productId","offerId","priceCode","productName","price","currency","quantity"]),tl=new Set(["id","priceId","productId","priceCode","quantity"]),rl=new Set(["id","priceId","productId","offerId","contentId","priceCode","value","price","currency"]),il=new Set(["email","phone","name"]),nl=new Set(["value","currency"]);function v(r){if(typeof r=="string"&&r.trim()!=="")return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}function Pe(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=r.trim();if(!/^-?\d+(\.\d+)?$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}}function _e(r,e){return Object.keys(r).filter(t=>!e.has(t))}function Ur(r){switch(r){case"ADD_TO_CART":case"REMOVE_FROM_CART":case"VIEW_CONTENT":case"SEARCH":case"LEAD":case"INITIATE_CHECKOUT":return!0;case"ADD_PAYMENT_INFO":case"PURCHASE":return!1;default:return!1}}function To(r,e){switch(r){case"ADD_TO_CART":{let t=_e(e,el),i=v(e.priceId)??v(e.priceCode),n=v(e.productId)??i,o=v(e.offerId),s=v(e.id)??i,a=v(e.productName),l=Pe(e.price),u=v(e.currency),c=Pe(e.quantity);return!n&&!i?{ok:!1,reason:"ADD_TO_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...s?{id:s}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...o?{offerId:o}:{},...a?{productName:a}:{},...l!=null?{price:l}:{},...u?{currency:u}:{},...c!=null?{quantity:c}:{}},...t.length?{unknownKeys:t}:{}}}case"REMOVE_FROM_CART":{let t=_e(e,tl),i=v(e.priceId)??v(e.priceCode),n=v(e.productId)??i,o=v(e.id)??i,s=Pe(e.quantity);return!n&&!i?{ok:!1,reason:"REMOVE_FROM_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...o?{id:o}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...s!=null?{quantity:s}:{}},...t.length?{unknownKeys:t}:{}}}case"VIEW_CONTENT":{let t=_e(e,rl),i=v(e.contentId),n=v(e.productId),o=v(e.priceId)??v(e.priceCode),s=v(e.offerId);if(i&&n&&i!==n&&!o)return{ok:!1,reason:"VIEW_CONTENT contentId/productId conflict",unknownKeys:t};let a=o??i??n??v(e.id);if(!a)return{ok:!1,reason:"VIEW_CONTENT requires priceId, contentId, or productId",unknownKeys:t};let l=Pe(e.value)??Pe(e.price),u=v(e.currency);return{ok:!0,data:{...o?{id:v(e.id)??o,priceId:o}:{},contentId:i??a,productId:n??a,...s?{offerId:s}:{},...l!=null?{value:l}:{},...u?{currency:u}:{}},...t.length?{unknownKeys:t}:{}}}case"SEARCH":{let t=v(e.query);return t?{ok:!0,data:{query:t},unknownKeys:_e(e,new Set(["query"]))}:{ok:!1,reason:"SEARCH requires query"}}case"LEAD":{let t=_e(e,il),i=v(e.email),n=v(e.phone),o=v(e.name);return!i&&!n&&!o?{ok:!1,reason:"LEAD requires email, phone, or name",unknownKeys:t}:{ok:!0,data:{...i?{email:i}:{},...n?{phone:n}:{},...o?{name:o}:{}},...t.length?{unknownKeys:t}:{}}}case"INITIATE_CHECKOUT":{let t=_e(e,nl),i=Pe(e.value),n=v(e.currency);return{ok:!0,data:{...i!=null?{value:i}:{},...n?{currency:n}:{}},...t.length?{unknownKeys:t}:{}}}case"ADD_PAYMENT_INFO":return{ok:!1,reason:"link source does not support ADD_PAYMENT_INFO"};case"PURCHASE":return{ok:!1,reason:"link source does not support PURCHASE in this stage"};default:return{ok:!1,reason:`unsupported event: ${r}`}}}var Le=Object.freeze({});function E(r){if(!r||r==="/")return"/";let e=r.startsWith("/")?r:`/${r}`;return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function ol(r){try{return decodeURIComponent(r)}catch{return r}}function Io(r,e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return!1;if(r===t)return!0;if(!r.startsWith(t))return!1;if(/[^a-zA-Z0-9]$/.test(t))return!0;let i=r.charAt(t.length);return!!(i>="0"&&i<="9"||i==="_"&&/\d/.test(r.slice(t.length+1)))}function sn(r,e){let t=E(r).split("/").filter(Boolean).map(ol),i=E(e).split("/").filter(Boolean);if(t.length!==i.length)return null;let n=Object.create(null),o=new Set;for(let s=0;s<i.length;s+=1){let a=i[s],l=t[s];if(a.startsWith(":")){let u=a.slice(1);if(!u||o.has(u)||u==="__proto__"||u==="constructor"||u==="prototype"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))return null;o.add(u),n[u]=l;continue}if(a!==l)return null}return n}function Ao(r,e,t){return t?r===e:r.toLowerCase()===e.toLowerCase()}function sl(r,e,t){return t?r.startsWith(e):r.toLowerCase().startsWith(e.toLowerCase())}function al(r,e){let t=r.get(e.key),i="caseSensitive"in e&&e.caseSensitive===!0;switch(e.operator){case"exists":return t!==null&&t!=="";case"absent":return t===null||t==="";case"equals":return t===null?!1:Ao(t,e.value,i);case"starts_with":return t===null?!1:sl(t,e.value,i);case"one_of":return t===null?!1:e.value.some(n=>Ao(t,n,i));default:return!1}}function Do(r,e){if(e.protocols?.length){if(!e.protocols.includes(r.protocol))return{matched:!1,pathParams:Le}}else if(r.protocol!=="http:"&&r.protocol!=="https:")return{matched:!1,pathParams:Le};if(e.origins?.length&&!e.origins.some(s=>s===r.origin))return{matched:!1,pathParams:Le};if(e.hostnames?.length){let o=r.hostname.toLowerCase();if(!e.hostnames.some(a=>a.toLowerCase()===o))return{matched:!1,pathParams:Le}}let t=Object.create(null),i,n=e.path;if(n){let o=E(r.pathname);if(n.template){let s=sn(o,n.template);s&&(t=s,i={type:"template",pattern:E(n.template)})}if(!i&&n.exact?.length){let s=n.exact.find(a=>E(a)===o);s!==void 0&&(i={type:"exact",pattern:E(s)})}if(!i&&n.prefixes?.length){let s=n.prefixes.find(a=>{let l=E(a);if(l==="/"||o===l||o.startsWith(`${l}/`)||/[^a-zA-Z0-9/]$/.test(l)&&o.startsWith(l))return!0;let u=l.replace(/^\//,""),c=o.split("/").filter(Boolean)[0]??"";return!!(o.startsWith(l)&&Io(c,u))});s!==void 0&&(i={type:"prefix",pattern:E(s)})}if(!i&&n.segmentPrefixes?.length){let s=o.split("/").filter(Boolean),a=n.segmentPrefixes.find(l=>s.some(u=>Io(u,l)));a!==void 0&&(i={type:"prefix",pattern:`/${a.replace(/^\/+|\/+$/g,"")}`})}if(!i)return{matched:!1,pathParams:Le}}if(e.query?.conditions?.length){let o=e.query.mode??"all",s=e.query.conditions.map(l=>al(r.searchParams,l));if(!(o==="any"?s.some(Boolean):s.every(Boolean)))return{matched:!1,pathParams:Le}}return{matched:!0,pathParams:Object.freeze({...t}),...i?{matchedPath:i}:{}}}function ko(r){if(!r)return null;if(r.type==="prefix"){let e=E(r.pattern);return e==="/"?"/:redacted":`${e}/:redacted`}if(r.type==="exact"){let e=E(r.pattern).split("/").filter(Boolean);return e.length===0?"/":`/${e.map(()=>":redacted").join("/")}`}return r.pattern}function ll(r){return r===void 0||typeof r=="string"&&r.trim()===""}function ul(r){return E(r).split("/").filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}})}function cl(r){return r.replace(/\.html?$/i,"")}function dl(r){if(r==null)return;let e=r.replace(/\s+/g," ").trim();return e===""?void 0:e}function wo(r,e){if(!(r instanceof HTMLElement))return;let t=r.dataset[e];if(t!==void 0)return t.trim()===""?void 0:t}function Ro(r,e){let t=r.getAttribute(e);if(t!==null)return t.trim()===""?void 0:t}function ml(r,e){switch(r.source){case"query":{let t=e.url.searchParams.get(r.key);return t===null?void 0:t}case"pathParam":{let t=e.pathParams[r.key];return t===void 0?void 0:t}case"pathSegment":{let t=ul(e.url.pathname),i=r.index;if(!Number.isInteger(i)||(i<0&&(i=t.length+i),i<0||i>=t.length))return;let n=t[i];return n===void 0?void 0:cl(n)}case"attribute":return Ro(e.target,r.name)??Ro(e.anchor,r.name);case"dataset":return wo(e.target,r.key)??wo(e.anchor,r.key);case"static":return r.value;case"href":return e.url.href;case"origin":return e.url.origin;case"hostname":return e.url.hostname;case"pathname":return E(e.url.pathname);case"text":return dl(e.anchor.textContent);default:return}}function pl(r,e){switch(e){case"trim":return typeof r=="string"?r.trim():void 0;case"lowercase":return typeof r=="string"?r.toLowerCase():void 0;case"uppercase":return typeof r=="string"?r.toUpperCase():void 0;case"number":{if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"){let t=r.trim();if(t===""||!/^-?\d+(\.\d+)?$/.test(t))return;let i=Number(t);return Number.isFinite(i)?i:void 0}return}default:return}}function hl(r,e){let t=Array.isArray(r.from)?r.from:[r.from],i=!1;for(let n of t){let o=ml(n,e);if(ll(o))continue;if(!r.transform)return{value:o,transformFailed:!1};let s=pl(o,r.transform);if(s===void 0){i=!0;continue}if(!(typeof s=="string"&&s.trim()===""))return{value:s,transformFailed:!1}}return{value:void 0,transformFailed:i}}function Mo(r,e){if(!r||Object.keys(r).length===0)return{valid:!0,values:Object.freeze({}),missingRequired:Object.freeze([])};let t=Object.create(null),i=[];for(let[n,o]of Object.entries(r)){if(n==="__proto__"||n==="constructor"||n==="prototype")continue;let{value:s}=hl(o,e);if(s!==void 0){t[n]=s;continue}o.required===!0&&i.push(n)}return{valid:i.length===0,values:Object.freeze(t),missingRequired:Object.freeze(i)}}var gl=50,fl=50,an=50,yl=20,vl=30,bl=10,Sl=50,Cl=128,El=2048,xl=new Set(["__proto__","constructor","prototype"]),Lo=/^[A-Za-z_][A-Za-z0-9_]*$/,Tl=new Set(["trim","lowercase","uppercase","number"]);function g(r){return{ok:!1,reason:r}}function K(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function zr(r){return!xl.has(r)}function w(r){return typeof r=="string"&&r.trim().length>0}function I(r,e=El){return typeof r=="string"&&r.length<=e}function Il(r){return!r||r.length>253||r.includes("/")||r.includes(" ")||r.includes(":")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)}function Po(r){return typeof r!="number"||!Number.isFinite(r)||r<0?void 0:Math.min(r,6e4)}function Al(r){try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username!==""||e.password!==""||e.pathname!=="/"&&e.pathname!==""||e.search!==""||e.hash!==""?null:e.origin}catch{return null}}function _o(r){if(typeof r=="string")return I(r)?r:null;if(!K(r)||!w(r.type)||!w(r.value)||!I(r.value))return null;let e=r.type;return e!=="css"&&e!=="id"&&e!=="class"&&e!=="attribute"&&e!=="text"?null:{type:e,value:r.value,...r.exact===!0?{exact:!0}:{},...r.caseSensitive===!0?{caseSensitive:!0}:{},...typeof r.closest=="string"&&I(r.closest)?{closest:r.closest}:{}}}function Dl(r){if(typeof r=="string")return I(r)?r:null;if(Array.isArray(r)){if(r.length===0)return null;let e=[];for(let t of r){let i=_o(t);if(!i)return null;e.push(i)}return e}return _o(r)}function kl(r){let e=E(r).split("/").filter(Boolean),t=new Set;for(let i of e){if(!i.startsWith(":"))continue;let n=i.slice(1);if(!n)return"path.template has empty param name";if(!Lo.test(n))return`path.template param name is invalid: ${n}`;if(!zr(n))return`path.template param name is reserved: ${n}`;if(t.has(n))return`path.template has duplicate param: ${n}`;t.add(n)}return sn(r.replace(/:[^/]+/g,"x"),r),null}function wl(r){if(!K(r)||!w(r.key)||!I(r.key))return null;let e=r.key.trim();if(!zr(e))return null;let t=r.operator;if(t==="exists"||t==="absent")return{key:e,operator:t};if(t==="equals"||t==="starts_with")return typeof r.value!="string"||!I(r.value)?null:{key:e,operator:t,value:r.value,...r.caseSensitive===!0?{caseSensitive:!0}:{}};if(t==="one_of"){if(!Array.isArray(r.value)||r.value.length===0||r.value.length>Sl)return null;let i=r.value.filter(n=>typeof n=="string"&&I(n));return i.length===0?null:{key:e,operator:"one_of",value:[...i],...r.caseSensitive===!0?{caseSensitive:!0}:{}}}return null}function Rl(r,e){if(!K(r))return null;let t=r.source;if(typeof t!="string")return null;switch(t){case"query":return w(r.key)&&I(r.key)?{source:"query",key:r.key.trim()}:null;case"pathParam":if(!e||!w(r.key)||!I(r.key))return null;{let i=r.key.trim();return!Lo.test(i)||!zr(i)?null:{source:"pathParam",key:i}}case"pathSegment":return typeof r.index!="number"||!Number.isInteger(r.index)||r.index<-32||r.index>64?null:{source:"pathSegment",index:r.index};case"attribute":return w(r.name)&&I(r.name)?{source:"attribute",name:r.name.trim()}:null;case"dataset":return w(r.key)&&I(r.key)?{source:"dataset",key:r.key.trim()}:null;case"static":{let i=r.value;return i===null||typeof i=="boolean"?{source:"static",value:i}:typeof i=="string"?I(i)?{source:"static",value:i}:null:typeof i=="number"&&Number.isFinite(i)?{source:"static",value:i}:null}case"href":case"origin":case"hostname":case"pathname":case"text":return{source:t};default:return null}}function Ml(r,e){if(!K(r)||r.from==null)return null;let t=Array.isArray(r.from)?r.from:[r.from];if(t.length===0||t.length>bl)return null;let i=[];for(let o of t){let s=Rl(o,e);if(!s)return null;i.push(s)}let n=r.transform;return n!==void 0&&(typeof n!="string"||!Tl.has(n))?null:{from:i.length===1?i[0]:i,...r.required===!0?{required:!0}:{},...typeof n=="string"?{transform:n}:{}}}function Pl(r){return!!(r.protocols?.length||r.origins?.length||r.hostnames?.length||r.path?.exact?.length||r.path?.prefixes?.length||r.path?.segmentPrefixes?.length||r.path?.template||r.query?.conditions?.length)}function _l(r){if(!K(r))return g("source must be an object");if(!w(r.name))return g("name is required");if(r.name.trim().length>Cl)return g("name exceeds defensive limit");if(r.type!=="link")return g("type must be link");if(r.trigger!==void 0&&r.trigger!=="click")return g("trigger must be click when provided");if(!K(r.match))return g("match is required");let e=r.match,t={};if(e.protocols!==void 0){if(!Array.isArray(e.protocols)||e.protocols.length===0)return g("protocols must be a non-empty array when provided");let u=[];for(let c of e.protocols){if(c!=="http:"&&c!=="https:")return g("protocols only allow http: and https:");u.includes(c)||u.push(c)}t.protocols=u}if(e.origins!==void 0){if(!Array.isArray(e.origins)||e.origins.length===0)return g("origins must be a non-empty array when provided");if(e.origins.length>gl)return g("origins exceeds defensive limit");let u=[];for(let c of e.origins){if(!w(c)||!I(c))return g("origin entries must be non-empty");let d=Al(c.trim());if(!d)return g("origin must be protocol+host[+port] only (no path/query/hash/userinfo)");u.includes(d)||u.push(d)}t.origins=u}if(e.hostnames!==void 0){if(!Array.isArray(e.hostnames)||e.hostnames.length===0)return g("hostnames must be a non-empty array when provided");if(e.hostnames.length>fl)return g("hostnames exceeds defensive limit");let u=[];for(let c of e.hostnames){if(!w(c))return g("hostname entries must be non-empty");let d=c.trim().toLowerCase();if(!Il(d))return g("hostname is invalid");u.includes(d)||u.push(d)}t.hostnames=u}if(e.path!==void 0){if(!K(e.path))return g("path must be an object when provided");let u={};if(e.path.exact!==void 0){if(!Array.isArray(e.path.exact)||e.path.exact.length===0)return g("path.exact must be non-empty when provided");if(e.path.exact.length>an)return g("path.exact exceeds defensive limit");if(u.exact=e.path.exact.filter(c=>w(c)&&I(c)).map(c=>E(c.trim())),u.exact.length===0)return g("path.exact has no valid entries")}if(e.path.prefixes!==void 0){if(!Array.isArray(e.path.prefixes)||e.path.prefixes.length===0)return g("path.prefixes must be non-empty when provided");if(e.path.prefixes.length>an)return g("path.prefixes exceeds defensive limit");if(u.prefixes=e.path.prefixes.filter(c=>w(c)&&I(c)).map(c=>E(c.trim())),u.prefixes.length===0)return g("path.prefixes has no valid entries")}if(e.path.segmentPrefixes!==void 0){if(!Array.isArray(e.path.segmentPrefixes)||e.path.segmentPrefixes.length===0)return g("path.segmentPrefixes must be non-empty when provided");if(e.path.segmentPrefixes.length>an)return g("path.segmentPrefixes exceeds defensive limit");if(u.segmentPrefixes=e.path.segmentPrefixes.filter(c=>w(c)&&I(c)).map(c=>c.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),u.segmentPrefixes.length===0)return g("path.segmentPrefixes has no valid entries")}if(e.path.template!==void 0){if(!w(e.path.template))return g("path.template must be non-empty when provided");if(!I(e.path.template))return g("path.template exceeds defensive limit");let c=E(e.path.template.trim()),d=kl(c);if(d)return g(d);u.template=c}if(!u.exact&&!u.prefixes&&!u.segmentPrefixes&&!u.template)return g("path must define exact, prefixes, segmentPrefixes, or template");t.path=u}if(e.query!==void 0){if(!K(e.query))return g("query must be an object when provided");if(!Array.isArray(e.query.conditions)||e.query.conditions.length===0)return g("query.conditions must be a non-empty array");if(e.query.conditions.length>yl)return g("query.conditions exceeds defensive limit");if(e.query.mode!==void 0&&e.query.mode!=="all"&&e.query.mode!=="any")return g("query.mode must be all or any");let u=[];for(let c of e.query.conditions){let d=wl(c);if(!d)return g("query condition is invalid");u.push(d)}t.query={...e.query.mode==="all"||e.query.mode==="any"?{mode:e.query.mode}:{},conditions:u}}if(!Pl(t))return g("match must include at least one useful rule");let i=!!t.path?.template,n;if(r.bindings!==void 0){if(!K(r.bindings))return g("bindings must be an object when provided");let u=Object.keys(r.bindings);if(u.length>vl)return g("bindings exceeds defensive limit");n=Object.create(null);let c=new Set;for(let d of u){if(!w(d))return g("binding key must be non-empty");let m=d.trim();if(!zr(m))return g(`binding key is reserved: ${m}`);if(c.has(m))return g(`binding key collision after trim: ${m}`);c.add(m);let h=r.bindings[d],p=Ml(h,i);if(!p)return!i&&K(h)&&JSON.stringify(h).includes('"pathParam"')?g("pathParam requires path.template"):g(`binding ${d} is invalid`);n[m]=p}}let o=Po(r.debounceMs),s=Po(r.cooldownMs),a;if(r.selector!==void 0){let u=Dl(r.selector);if(!u)return g("selector is invalid");a=u}return{ok:!0,source:{name:r.name.trim(),type:"link",match:t,...r.enabled===!1?{enabled:!1}:{},...r.fireOnce===!0?{fireOnce:!0}:{},...o!==void 0?{debounceMs:o}:{},...s!==void 0?{cooldownMs:s}:{},...r.trigger==="click"?{trigger:"click"}:{},...a!==void 0?{selector:a}:{},...r.selectorType==="css"||r.selectorType==="id"||r.selectorType==="class"||r.selectorType==="attribute"||r.selectorType==="text"?{selectorType:r.selectorType}:{},...n?{bindings:n}:{}}}}function qr(r){try{return _l(r)}catch{return g("source normalization failed")}}var Fo=new Set(["http:","https:"]);function Oo(r){return!!(r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true")}function Ll(r){if(typeof HTMLAnchorElement<"u"&&r instanceof HTMLAnchorElement&&r.hasAttribute("href"))return r;let e=r.closest("a[href]");return e instanceof HTMLAnchorElement?e:null}function Ol(r,e){try{let t=new URL(r,e);return Fo.has(t.protocol)?t:null}catch{return null}}var Hr=class extends C{constructor(t,i,n){super(t);this.hasFired=!1;this.destroyed=!1;this.initialized=!1;this.debounceTimer=null;this.lastFireAt=0;this.stats={matches:0,ignoredClicks:0,invalidUrl:0,unsupportedProtocol:0,missingRequired:0,mapperRejected:0,fired:0,fireOnceBlocked:0,debounceBlocked:0,cooldownBlocked:0,lastIgnoredReason:null,lastResolvedKeys:[],lastHostname:null,lastPathname:null};this.factory=i,this.eventType=n.eventType;let o=qr(n.source);o.ok?(this.inactiveReason=null,this.source=o.source):(this.inactiveReason=o.reason,this.source={name:n.source.name?.trim()||"invalid-link",type:"link",match:{path:{exact:["/__invalid_link_source__"]}}},this.context.logger.debug(`[ConfiguredLinkDetector] inactive: ${o.reason}`)),this.selectorType=this.source.selectorType??"css",this.fireOnce=this.source.fireOnce===!0,this.debounceMs=typeof this.source.debounceMs=="number"&&Number.isFinite(this.source.debounceMs)&&this.source.debounceMs>0?this.source.debounceMs:0,this.cooldownMs=typeof this.source.cooldownMs=="number"&&Number.isFinite(this.source.cooldownMs)&&this.source.cooldownMs>0?this.source.cooldownMs:0,this.origin=n.origin??B("link",n.eventType,this.source.name),this.resolver=new $(t.logger)}get name(){return`ConfiguredLink(${this.eventType}:${this.source.name})`}get isActive(){return this.inactiveReason===null&&this.source.enabled!==!1}getDebugSnapshot(){return{sourceName:this.source.name,sourceType:"link",eventType:this.eventType,enabled:this.isActive,initialized:this.initialized,matches:this.stats.matches,ignoredClicks:this.stats.ignoredClicks,invalidUrl:this.stats.invalidUrl,unsupportedProtocol:this.stats.unsupportedProtocol,missingRequired:this.stats.missingRequired,mapperRejected:this.stats.mapperRejected,fired:this.stats.fired,fireOnceBlocked:this.stats.fireOnceBlocked,debounceBlocked:this.stats.debounceBlocked,cooldownBlocked:this.stats.cooldownBlocked,lastIgnoredReason:this.inactiveReason??this.stats.lastIgnoredReason,lastResolvedKeys:[...this.stats.lastResolvedKeys],lastHostname:this.stats.lastHostname,lastPathname:this.stats.lastPathname}}onInit(){this.destroyed=!1,this.hasFired=!1,this.lastFireAt=0,this.initialized=!0,!this.inactiveReason&&this.source.enabled!==!1&&this.isDocumentAvailable()&&Ur(this.eventType)&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){this.destroyed=!0,this.initialized=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}ignore(t){this.stats.ignoredClicks+=1,this.stats.lastIgnoredReason=t}handleClick(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}try{if(typeof t.button=="number"&&t.button!==0){this.ignore("non-primary-button");return}let i=this.resolveClickElements(t);if(!i){this.ignore("no-match");return}let{anchor:n,target:o}=i;if(Oo(o)||Oo(n)){this.ignore("disabled");return}let s=n.getAttribute("href");if(!s||s.trim()===""){this.ignore("missing-href");return}let a=s.trim().toLowerCase();if(a.startsWith("mailto:")||a.startsWith("tel:")||a.startsWith("javascript:")){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let l=typeof document<"u"&&document.baseURI?document.baseURI:"https://localhost/",u=Ol(s,l);if(!u){this.stats.invalidUrl+=1,this.ignore("invalid-url");return}if(!Fo.has(u.protocol)){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let c=Do(u,this.source.match);if(!c.matched){this.ignore("target-mismatch");return}this.stats.matches+=1,this.stats.lastHostname=u.hostname,this.stats.lastPathname=ko(c.matchedPath);let d=Mo(this.source.bindings,{anchor:n,target:o,url:u,pathParams:c.pathParams});if(this.stats.lastResolvedKeys=Object.keys(d.values),!d.valid){this.stats.missingRequired+=1,this.ignore(`missing-required:${d.missingRequired.join(",")}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} missing required bindings`,d.missingRequired);return}let m=To(this.eventType,d.values);if(!m.ok){this.stats.mapperRejected+=1,this.ignore(`mapper:${m.reason}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} mapper rejected: ${m.reason}`);return}m.unknownKeys?.length&&this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} unknown binding keys ignored`,m.unknownKeys),this.scheduleFire(m.data)}catch(i){this.ignore("exception"),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.eventType} ignored:`,i)}}}scheduleFire(t){let i=Date.now();if(this.cooldownMs>0&&i-this.lastFireAt<this.cooldownMs){this.stats.cooldownBlocked+=1;return}if(this.debounceMs>0){this.stats.debounceBlocked+=1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.fire(t)},this.debounceMs);return}this.fire(t)}fire(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}this.factory.trackAuto(this.eventType,t,{origin:this.origin}),this.stats.fired+=1,this.lastFireAt=Date.now(),this.fireOnce&&(this.hasFired=!0)}}resolveClickElements(t){let i=t.target instanceof Element?t.target:null;if(!i)return null;let n=Ll(i);if(!n)return null;if(!this.source.selector)return{anchor:n,target:n};let o=[],s=i;for(;s&&s!==document.documentElement;)o.push(s),s=s.parentElement;o.includes(n)||o.unshift(n);for(let a of o)if(this.resolver.matches(a,this.source.selector,this.selectorType))return{anchor:n,target:a};return null}};var Fl=new Set(["click","submit","hover","visible"]);function Nl(r){let e=r.getAttribute("data-trigger")?.trim()||r.getAttribute("data-track-trigger")?.trim();if(!e)return null;let t=new Set;for(let i of e.toLowerCase().split(/[\s,]+/))Fl.has(i)&&t.add(i);return t}function ln(r,e){let t=Nl(r);return t==null?!0:t.has(e)}var $r=class extends C{constructor(t,i,n){super(t);this.visibleFired=new WeakSet;this.observedElements=new Set;this.intersectionObserver=null;this.hasFired=!1;this.destroyed=!1;this.factory=i,this.config=n,this.selectorType=n.source.selectorType??"css",this.fireOnce=n.source.fireOnce===!0,this.trigger=n.source.trigger??"both",this.visibleThreshold=Bl(n.source.visibleThreshold),this.origin=n.origin??B("selector",n.eventType,n.source.name),this.resolver=new $(t.logger);let o=t.services.commerce.config;this.customerExtractor=new H({fieldMappings:re(o?.customer,o?.mappings?.fields)}),this.productExtractor=new ve({attributeMappings:o?.mappings?.attributes,fieldMappings:o?.mappings?.fields})}get name(){return`ConfiguredSelector(${this.config.eventType}:${this.config.source.name})`}onInit(){this.destroyed=!1,this.hasFired=!1,this.isDocumentAvailable()&&((this.trigger==="click"||this.trigger==="both")&&this.addDocumentListener("click",t=>this.handleEvent(t),!0),(this.trigger==="submit"||this.trigger==="both")&&this.addDocumentListener("submit",t=>this.handleEvent(t),!0),this.trigger==="hover"&&this.addDocumentListener("mouseover",t=>this.handleHover(t),!0),this.trigger==="visible"&&this.startVisibleObserver())}onDestroy(){this.destroyed=!0,this.intersectionObserver?.disconnect(),this.intersectionObserver=null,this.observedElements.clear()}handleHover(t){if(!(t instanceof MouseEvent))return;let i=this.findMatchedElement(t);if(!i)return;let n=t.relatedTarget instanceof Node?t.relatedTarget:null;n&&i.contains(n)||this.dispatchFromElement(i,"hover")}handleEvent(t){if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let i=this.findMatchedElement(t);i&&this.dispatchFromElement(i,t.type==="submit"?"submit":"click")}startVisibleObserver(){if(typeof IntersectionObserver>"u"){this.context.logger.debug("[ConfiguredSelectorDetector] IntersectionObserver unavailable");return}this.intersectionObserver=new IntersectionObserver(t=>{for(let i of t)i.isIntersecting&&(this.visibleThreshold>0&&i.intersectionRatio<this.visibleThreshold||this.handleVisible(i.target))},{threshold:this.visibleThreshold}),this.syncVisibleTargets(),this.observeDom(()=>this.syncVisibleTargets())}syncVisibleTargets(){if(this.destroyed||!this.intersectionObserver)return;let t=this.resolver.queryAll(this.config.source.selector,this.selectorType).filter(n=>ln(n,"visible")),i=new Set(t);for(let n of this.observedElements)i.has(n)||(this.intersectionObserver.unobserve(n),this.observedElements.delete(n));for(let n of t)this.observedElements.has(n)||(this.intersectionObserver.observe(n),this.observedElements.add(n))}handleVisible(t){this.visibleFired.has(t)||this.dispatchFromElement(t,"visible")&&this.visibleFired.add(t)}dispatchFromElement(t,i){if(this.destroyed||this.fireOnce&&this.hasFired||!ln(t,i))return!1;try{let n=this.extractData(t);return n===null?!1:(this.factory.trackAuto(this.config.eventType,n,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0),!0)}catch(n){return this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,n),!1}}findMatchedElement(t){let i=[];t.type==="submit"&&t.target instanceof Element&&i.push(t.target);let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.documentElement;)i.push(n),n=n.parentElement;for(let o of i)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:i}=this.config;if(i==="LEAD"){let n=this.customerExtractor.extractFromElement(t);return!n.email&&!n.phone&&!n.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...n.email?{email:n.email}:{},...n.phone?{phone:n.phone}:{},...n.name?{name:n.name}:{}}}if(i==="ADD_TO_CART"||i==="REMOVE_FROM_CART"){let n=this.productExtractor.extractFromElement(t);return i==="REMOVE_FROM_CART"?{...n.productId?{productId:n.productId}:{},...n.quantity!=null?{quantity:n.quantity}:{}}:{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}if(i==="SEARCH"){let n=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return n.trim()?{query:n.trim()}:null}if(i==="INITIATE_CHECKOUT"||i==="PURCHASE")return{};if(i==="VIEW_CONTENT"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{contentId:n.productId}:{},...n.price!=null?{value:n.price}:{},...n.currency?{currency:n.currency}:{}}}return{}}};function Bl(r){return typeof r!="number"||!Number.isFinite(r)||r<0?0:r>1?1:r}var Vl=["card_number","cardNumber","card-number","cc_number"],Ul=["card_number","cardNumber","cc_number"],zl=["cvv","cvc","security_code"],ql=["cvv","cvc","security_code"];function un(r){return r.type!=="hidden"&&!r.disabled}function cn(r){return r.value.length>0}function Bo(r){return typeof document>"u"?null:r??document}function No(r,e,t){let i=Bo(t);if(!i)return!1;for(let n of r){let o=i===document?document.getElementById(n):i.querySelector(`#${Hl(n)}`);if(o instanceof HTMLInputElement&&un(o)&&cn(o))return!0}for(let n of e){let o=i.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&un(s)&&cn(s))return!0}return!1}function Et(r,e){let t=Bo(e);if(!t)return!1;let i=t.querySelectorAll(`input[autocomplete="${r}"]`);for(let n of i)if(n instanceof HTMLInputElement&&un(n)&&cn(n))return!0;return!1}function Hl(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function Vo(r){return Et("cc-number",r)||No(Vl,Ul,r)||Et("cc-exp",r)||Et("cc-exp-month",r)||Et("cc-exp-year",r)||Et("cc-csc",r)||No(zl,ql,r)}var $l=["input","change","focusin"],xt=class extends C{constructor(t,i,n){super(t);this.checkTimer=null;this.tracked=!1;this.factory=i;let o=n?.source;this.paymentMethod=Kl(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=n?.origin??(o?B("payment","ADD_PAYMENT_INFO",o.name):"auto:card")}get name(){return`CardDetector(${this.origin.includes(":")?this.origin.split(":").pop():"card"})`}onInit(){if(this.tracked=!1,!!this.isDocumentAvailable()){for(let t of $l)this.addDocumentListener(t,()=>this.scheduleCheck(),!0);this.observeDom(()=>this.scheduleCheck()),this.scheduleCheck()}}onDestroy(){this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.tracked=!1}scheduleCheck(){this.fireOnce&&this.tracked||(this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.evaluate()},300))}evaluate(){if(this.fireOnce&&this.tracked||!this.isDocumentAvailable())return;let t=this.resolveFormRoot();this.formSelector&&!t||Vo(t)&&(this.tracked=!0,this.factory.trackAuto("ADD_PAYMENT_INFO",{paymentMethod:this.paymentMethod},{origin:this.origin}))}resolveFormRoot(){if(!this.formSelector||typeof document>"u")return typeof document<"u"?document:null;try{return document.querySelector(this.formSelector)}catch{return null}}};function Kl(r){switch(r){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return r;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var Wl=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],Kr=class extends C{constructor(t,i){super(t);this.name="CheckoutDetector";this.factory=i}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i)return;let n=i.textContent?.toLowerCase()??"",o=i.href?.toLowerCase()??"";(Wl.some(a=>i.matches(a))||n.includes("checkout")&&!n.includes("continue shopping")||n.includes("finalizar")&&n.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let i=t.target instanceof HTMLFormElement?t.target:null;if(!i)return;((i.getAttribute("action")?.toLowerCase()??"").includes("checkout")||i.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var Wr=class extends C{constructor(t,i,n){super(t);this.hasFired=!1;this.factory=i,this.options=n,this.fireOnce=n.source.fireOnce!==!1,this.origin=n.origin??B("lifecycle",n.eventType,n.source.name)}get name(){return`Lifecycle(${this.options.eventType}:${this.options.source.name})`}onInit(){this.hasFired=!1,this.fire()}onDestroy(){this.hasFired=!1}fire(){this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};var Gl={purchase:"PURCHASE",lead:"LEAD",add_to_cart:"ADD_TO_CART",addtocart:"ADD_TO_CART",remove_from_cart:"REMOVE_FROM_CART",removefromcart:"REMOVE_FROM_CART",initiate_checkout:"INITIATE_CHECKOUT",initiatecheckout:"INITIATE_CHECKOUT",checkout:"INITIATE_CHECKOUT",add_payment_info:"ADD_PAYMENT_INFO",addpaymentinfo:"ADD_PAYMENT_INFO",view_content:"VIEW_CONTENT",viewcontent:"VIEW_CONTENT",search:"SEARCH"};function dn(r){let e=r.trim().toLowerCase().replace(/\s+/g,"_");return Gl[e]??null}function Uo(r){return r.startsWith("[")||r.startsWith(".")||r.startsWith("#")?r:`[data-track="${r}"]`}var Gr=class extends C{constructor(t,i,n=[]){super(t);this.name="SelectorDetector";this.factory=i,this.selectors=n.length>0?n:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target:null;for(;i&&i!==document.body;){let n=this.matchElement(i);if(n){this.factory.trackAuto(n.type,n.data,{origin:"auto:selector"});return}i=i.parentElement}}matchElement(t){for(let n of this.selectors){let o=Uo(n);if(!t.matches(o))continue;let s=t.getAttribute("data-track")??t.getAttribute("data-track-event")??t.getAttribute("data-event");if(!s)continue;let a=dn(s);if(!a)continue;let l={},u=t.getAttribute("data-track-value");return u&&a==="PURCHASE"&&Object.assign(l,{value:Number(u)||void 0}),{type:a,data:l}}let i=t.getAttribute("data-track");if(i){let n=dn(i);if(n)return{type:n,data:{}}}return null}};var Ql=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],Qr=class extends C{constructor(t,i,n=[]){super(t);this.name="TextDetector";this.factory=i,this.keywords=n}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i?.textContent)return;let n=i.textContent.trim().toLowerCase();if(n){for(let o of Ql)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&n.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(n.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var j=class{static subscribe(e){return typeof window>"u"||typeof history>"u"?()=>{}:(this.listeners.add(e),this.refCount+=1,this.install(),()=>{this.listeners.delete(e),this.refCount-=1,this.refCount<=0&&(this.uninstall(),this.refCount=0)})}static resetForTests(){this.listeners.clear(),this.refCount=0,this.uninstall()}static install(){this.installed||(this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.notify()},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.notify()},this.installed=!0)}static uninstall(){this.installed&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installed=!1)}static notify(){for(let e of this.listeners)e()}};j.refCount=0,j.listeners=new Set,j.originalPushState=null,j.originalReplaceState=null,j.installed=!1;var Tt=class extends C{constructor(t,i,n=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=i,this.patterns=n.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?B("url",o.eventType,o.sourceName):"auto:url")}get name(){return this.eventType?`UrlDetector(${this.eventType})`:"UrlDetector"}onInit(){this.hasFired=!1,this.isWindowAvailable()&&(this.checkUrl(),this.addWindowListener("popstate",()=>this.checkUrl()),this.unsubscribeHistory=j.subscribe(()=>this.checkUrl()))}onDestroy(){this.unsubscribeHistory?.(),this.unsubscribeHistory=null,this.hasFired=!1}checkUrl(){if(!this.isWindowAvailable()||this.fireOnce&&this.hasFired)return;let t=window.location.href,i=window.location.pathname;for(let n of this.patterns)if(n.test(t)||n.test(i)){let o=this.eventType??(/thank|success|order|obrigado/i.test(n.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var jl=[{configKey:"lead",eventType:"LEAD"},{configKey:"addToCart",eventType:"ADD_TO_CART"},{configKey:"removeFromCart",eventType:"REMOVE_FROM_CART"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT"},{configKey:"purchase",eventType:"PURCHASE"},{configKey:"addPaymentInfo",eventType:"ADD_PAYMENT_INFO"},{configKey:"search",eventType:"SEARCH"},{configKey:"viewContent",eventType:"VIEW_CONTENT"}],Yl=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),jr=class{static create(e,t){let{auto:i,rules:n}=e.config.modules.conversion,o=[],s=e.logger;return i.enabled?(o.push(...this.createSourceDetectors(e,t,i)),n.enabled&&(n.selectors.length>0&&(o.push(new Gr(e,t,n.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),n.texts.length>0&&(o.push(new Qr(e,t,n.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),n.urlPatterns.length>0&&(o.push(new Tt(e,t,n.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),n.checkout.enabled&&(o.push(new Kr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),n.card.enabled&&(o.push(new xt(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (rules)"))),s.debug(`[AutoTrackerFactory] Created ${o.length} detector(s)`),o):(s.debug("[AutoTrackerFactory] Auto detection disabled"),o)}static createSourceDetectors(e,t,i){let n=[],o=new $(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let l of jl){let u=i.detectors[l.configKey];if(!u.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${l.configKey}`);continue}let c=u.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${l.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,l.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,n.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${l.eventType}`))}}return n}static createDetectorForSource(e,t,i,n,o,s){let a=e.logger;switch(n.type){case"form":return Yl.has(i)?new Vr(e,t,{eventType:i,source:n}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${i}`),null);case"selector":{let l=n;return o.hasEntries(l.selector)?new $r(e,t,{eventType:i,source:l}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${n.name}: empty selector`),null)}case"payment":{if(i!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${i}`),null;let l=n;return l.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: cardDetection false`),null):l.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: autoDispatch false`),null):new xt(e,t,{source:l})}case"lifecycle":return new Wr(e,t,{eventType:i,source:n});case"url":{let l=n;return l.patterns?.length?new Tt(e,t,l.patterns,{eventType:i,sourceName:l.name,fireOnce:l.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${n.name}: empty patterns`),null)}case"link":{if(!Ur(i))return a.debug(`[AutoTrackerFactory] Skipped link source for unsupported event: ${i}`),null;let l;try{l=qr(n)}catch(u){return a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: normalization threw`,u),null}return l.ok?new Hr(e,t,{eventType:i,source:l.source}):(a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: ${l.reason}`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${n.type}`),null}}};var Yr=class{constructor(){this.sentKeys=new Set}has(e){return this.sentKeys.has(e)}add(e){this.sentKeys.add(e)}clear(){this.sentKeys.clear()}getKeys(){return Array.from(this.sentKeys)}get size(){return this.sentKeys.size}};function zo(r,e,t,i){let n=mn(t,i),o=typeof e?.productId=="string"?e.productId.trim():"",s=Xl(e?.quantity),a=typeof e?.productName=="string"?e.productName.trim():"";return o?`${r}:product:${o}:qty:${s}:bucket:${n}`:a?`${r}:name:${a}:qty:${s}:bucket:${n}`:`${r}:interaction:${n}`}function qo(r,e=Date.now(),t=500){return zo("ADD_TO_CART",r,e,t)}function Ho(r,e=Date.now(),t=500){return zo("REMOVE_FROM_CART",r,e,t)}function mn(r=Date.now(),e=500){let t=e>0?e:500;return Math.floor(r/t)}function Xl(r){return typeof r=="number"&&Number.isFinite(r)?r:1}var Zl=new Set(["manual","auto:selector","auto:text","auto:checkout","auto:purchase","auto:lead","auto:addToCart","auto:removeFromCart","auto:initiateCheckout","auto:addPaymentInfo","auto:search","auto:viewContent"]);function hn(r){return r==="auto:url"||r.startsWith("auto:url:")}function Jl(r){return hn(r)?!1:Zl.has(r)?!0:r.startsWith("auto:form:")||r.startsWith("auto:selector:")||r.startsWith("auto:lifecycle:")}function eu(r=Date.now()){return Math.floor(r/1e3)}function $o(){return typeof window>"u"?"":window.location.pathname}function gn(r,e,t,i,n=Date.now()){let o=e??{},s=mn(n,500);switch(r){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:hn(t)?`PURCHASE:url:${$o()}`:Jl(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${eu(n)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return qo(o,n,500);case"REMOVE_FROM_CART":return Ho(o,n,500);case"INITIATE_CHECKOUT":return hn(t)?`INITIATE_CHECKOUT:url:${$o()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${i}`;case"VIEW_CONTENT":{let a=o;return a.contentId?`VIEW_CONTENT:content:${a.contentId}`:`VIEW_CONTENT:interaction:${s}`}case"SEARCH":return`SEARCH:query:${o.query}`;default:return`${r}:interaction:${s}`}}var x=class{constructor(e){this.factory=e}};var Xr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var Zr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var Jr=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var ei=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var ti=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var ri=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var ii=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var ni=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var tu={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},ru=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],oi=class{constructor(e,t,i,n){if(this.context=e,this.trackFn=t,this.dedupeSessionId=i,this.commerceState=n?.state??null,n){let o=e.services.commerce.config;this.resolver=new se({catalog:n.catalog,state:n.state,calculator:new oe,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new ti(this),this.lead=new ei(this),this.addToCart=new Zr(this),this.removeFromCart=new ri(this),this.initiateCheckout=new Jr(this),this.addPaymentInfo=new Xr(this),this.viewContent=new ni(this),this.search=new ii(this)}trackAuto(e,t,i){this.dispatch(e,t,i?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let i=t,n=i?.query??i?.searchTerm??"";if(!n.trim())throw new Error("[Conversion] SEARCH requires query");return{query:n.trim()}}case"PURCHASE":{let i=t;if(i?.value!=null&&i.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return i??{}}case"LEAD":{let i=t;if(!i?.email&&!i?.phone&&!i?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return i}case"VIEW_CONTENT":{let i={...t??{}};return delete i.productId,i}default:return t??{}}}buildDedupeKey(e,t,i){return gn(e,t,i,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,i){let n=this.enrichCommerce(e,t),o=this.normalize(e,n);this.syncCommerceState(e,o);let s=gn(e,o,i,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:i})}enrichCommerce(e,t){if(!this.resolver||!iu(e))return t;let i=tu[e];if(!i)return t;let n=this.context.services.commerce;if(!n.isEnrichmentEnabled(i))return t;let o=n.getEnrichmentSource(i);return this.resolver.resolve({eventType:e,payload:t??{},enrichmentSource:o}).data}syncCommerceState(e,t){if(this.commerceState){if(e==="ADD_TO_CART"){this.syncAddToCart(t);return}e==="REMOVE_FROM_CART"&&this.syncRemoveFromCart(t)}}syncAddToCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;let i=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:i,...typeof e.price=="number"&&Number.isFinite(e.price)?{price:e.price}:{},...typeof e.currency=="string"&&e.currency.trim()?{currency:e.currency.trim()}:{}})}syncRemoveFromCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";t&&this.commerceState.removeItem(t)}};function iu(r){return ru.includes(r)}var si=class{constructor(e){this.deduper=new Yr;this.detectors=[];this.active=!1;this.context=e,this.dedupeSessionId=`${e.config.identity.pixelId}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`;let t=e.services.commerce;this.catalog=t.catalog,this.commerceState=t.state,this.factory=new oi(e,(i,n,o)=>{this.dispatch(i,n,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=jr.create(this.context,this.factory);for(let e of this.detectors)e.init();this.active=!0}}destroy(){if(this.active){for(let e=this.detectors.length-1;e>=0;e-=1)this.detectors[e]?.destroy();this.detectors=[],this.deduper.clear(),this.active=!1}}getDedupeKeys(){return this.deduper.getKeys()}getActiveDetectors(){return this.detectors.map(e=>e.name??e.constructor.name)}isActive(){return this.active}dispatch(e,t,i){let n=i??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(n)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${n})`);return}this.deduper.add(n);let o=this.context.services.eventBuilder.build({type:e,category:"CONVERSION",data:t});this.context.logger.debug(`[ConversionEngine] Dispatching ${e}`),this.context.services.dispatcher.dispatch(o)}};var It=class{constructor(){this.name="conversion";this.engine=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Conversion module already initialized");return}if(!e.config.modules.conversion.enabled){e.logger.debug("[Pixel] Conversion module disabled");return}e.logger.debug("[Pixel] Conversion module initialized"),this.engine=new si(e),this.engine.init(),this.active=!0}destroy(){this.active&&(this.engine?.destroy(),this.engine=null,this.active=!1)}purchase(e){this.engine?.factory.purchase.track(e)}lead(e){this.engine?.factory.lead.track(e)}addToCart(e){this.engine?.factory.addToCart.track(e)}removeFromCart(e){this.engine?.factory.removeFromCart.track(e)}initiateCheckout(e){this.engine?.factory.initiateCheckout.track(e)}addPaymentInfo(e){this.engine?.factory.addPaymentInfo.track(e)}viewContent(e){this.engine?.factory.viewContent.track(e)}search(e){this.engine?.factory.search.track(e)}getDebugDedupeKeys(){return this.engine?.getDedupeKeys()??[]}getDebugActiveDetectors(){return this.engine?.getActiveDetectors()??[]}isEngineActive(){return this.engine?.isActive()??!1}};var At=class{constructor(e){this.context=e}init(){this.context.config.modules.core.fingerprint.enabled&&(this.context.logger.debug("[FingerprintEngine] Ensuring fingerprint"),this.context.services.fingerprint.ensureFingerprint())}destroy(){}};var ai=class{constructor(e){this.started=!1;this.originalPushState=null;this.originalReplaceState=null;this.handlePopState=()=>{this.onNavigate("back")};this.handleHashChange=()=>{this.onNavigate("hash")};this.onNavigate=e}start(){this.started||typeof window>"u"||(this.started=!0,this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.onNavigate("pushState")},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.onNavigate("replaceState")},window.addEventListener("popstate",this.handlePopState),window.addEventListener("hashchange",this.handleHashChange))}destroy(){!this.started||typeof window>"u"||(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange),this.originalPushState=null,this.originalReplaceState=null,this.started=!1)}};var li=class{constructor(e){this.lastPath=null;this.lastTimestamp=0;this.dedupeMs=e}shouldDispatch(e,t=Date.now()){return this.lastPath===e&&t-this.lastTimestamp<this.dedupeMs?!1:(this.lastPath=e,this.lastTimestamp=t,!0)}reset(){this.lastPath=null,this.lastTimestamp=0}};var Dt=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new li(e.config.modules.core.pageView.dedupeMs)}init(){let{pageView:e}=this.context.config.modules.core;e.enabled&&(e.trackInitialPageView&&this.trackPageView(),e.spa&&(this.navigationObserver=new ai(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",i=Date.now();if(!this.deduper.shouldDispatch(t,i)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let n=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...n??{}});this.context.logger.debug("[PageViewEngine] Dispatching PAGE_VIEW"),this.context.services.dispatcher.dispatch(o)}destroy(){this.navigationObserver?.destroy(),this.navigationObserver=null,this.deduper.reset()}};var kt=class{constructor(e){this.unsubscribe=null;this.context=e}init(){if(!this.context.config.modules.core.session.enabled)return;this.context.logger.debug("[SessionEngine] Ensuring session");let{ttlMs:e}=this.context.config.modules.core.session;this.applySessionLifecycle(e),this.unsubscribe=this.context.services.dispatcher.subscribe(t=>{t.type==="PAGE_VIEW"&&this.handlePageViewActivity()})}destroy(){this.unsubscribe?.(),this.unsubscribe=null}handlePageViewActivity(){let{ttlMs:e,renewOnActivity:t}=this.context.config.modules.core.session,{session:i}=this.context.services;if(i.isExpired(e)){this.applySessionLifecycle(e);return}t&&(i.touchActivity(),this.context.logger.debug("[SessionEngine] Session activity renewed"))}applySessionLifecycle(e){let t=this.context.services.session.ensureSession(e);if(t.expired&&t.previousSessionId){let i=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(i);let n=this.context.services.eventBuilder.build({type:"SESSION_RENEWED",sessionId:t.sessionId,previousSessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_RENEWED"),this.context.services.dispatcher.dispatch(n)}}};var wt=class{constructor(e){this.started=!1;this.context=e}init(){if(this.started||(this.started=!0,!this.context.config.modules.core.enabled))return;let e=this.context.services.urlContext;e&&(e.init(),this.context.logger.debug("[Pixel] UrlContext engine initialized"))}destroy(){this.started&&(this.context.services.urlContext?.destroy(),this.started=!1)}dispose(){this.destroy()}};var Rt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.visitor.enabled&&(this.context.logger.debug("[VisitorEngine] Ensuring visitor"),this.context.services.visitor.ensureVisitorId())}destroy(){}};var Mt=class{constructor(){this.name="core";this.urlContextEngine=null;this.visitorEngine=null;this.sessionEngine=null;this.fingerprintEngine=null;this.pageViewEngine=null}init(e){e.logger.debug("[Pixel] Core module initialized"),this.urlContextEngine=new wt(e),this.visitorEngine=new Rt(e),this.sessionEngine=new kt(e),this.fingerprintEngine=new At(e),this.pageViewEngine=new Dt(e),this.urlContextEngine.init(),this.visitorEngine.init(),this.sessionEngine.init(),this.fingerprintEngine.init(),this.pageViewEngine.init()}destroy(){this.pageViewEngine?.destroy(),this.fingerprintEngine?.destroy(),this.sessionEngine?.destroy(),this.visitorEngine?.destroy(),this.urlContextEngine?.destroy(),this.pageViewEngine=null,this.fingerprintEngine=null,this.sessionEngine=null,this.visitorEngine=null,this.urlContextEngine=null}};var Pt=class{constructor(){this.adapters=new Map}register(e){if(this.adapters.has(e.name))throw new Error(`[Integration] Destination "${e.name}" is already registered`);this.adapters.set(e.name,e)}remove(e){let t=this.adapters.get(e);return t?(t.destroy?.(),this.adapters.delete(e)):!1}get(e){return this.adapters.get(e)}getAll(){return[...this.adapters.values()]}supports(e){return this.getAll().filter(t=>{try{return t.supports(e)}catch{return!1}})}has(e){return this.adapters.has(e)}size(){return this.adapters.size}clear(){for(let e of this.adapters.values())e.destroy?.();this.adapters.clear()}};function nu(){return{sent:0,failed:0,ignored:0,skipped:0,totalDuration:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0,scriptLoadAttempts:0,scriptLoadSuccess:0,scriptLoadFailure:0,initAttempts:0,initSuccess:0,initFailure:0,lastError:null}}var _t=class{constructor(){this.registeredDestinations=0;this.eventsSent=0;this.eventsFailed=0;this.eventsIgnored=0;this.eventsSkipped=0;this.pageViewReceived=0;this.pageViewSent=0;this.pageViewSkipped=0;this.pageViewDeduped=0;this.pageViewFailed=0;this.scriptLoadAttempts=0;this.scriptLoadSuccess=0;this.scriptLoadFailure=0;this.initAttempts=0;this.initSuccess=0;this.initFailure=0;this.totalDuration=0;this.lastExecutionAt=null;this.lastErrorAt=null;this.lastErrorMessage=null;this.perDestination=new Map;this.perDestinationId=new Map}getDestinationCounters(e){let t=this.perDestination.get(e);return t||(t=nu(),this.perDestination.set(e,t)),t}setRegisteredCount(e){this.registeredDestinations=e}recordPageViewReceived(){this.pageViewReceived+=1}recordScriptLoadAttempt(e){this.scriptLoadAttempts+=1,this.getDestinationCounters(e).scriptLoadAttempts+=1}recordScriptLoadSuccess(e){this.scriptLoadSuccess+=1,this.getDestinationCounters(e).scriptLoadSuccess+=1}recordScriptLoadFailure(e){this.scriptLoadFailure+=1,this.getDestinationCounters(e).scriptLoadFailure+=1}recordInitAttempt(e){this.initAttempts+=1,this.getDestinationCounters(e).initAttempts+=1}recordInitSuccess(e){this.initSuccess+=1,this.getDestinationCounters(e).initSuccess+=1}recordInitFailure(e){this.initFailure+=1,this.getDestinationCounters(e).initFailure+=1}record(e){let t=e.adapter,i=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,i.sent+=1):e.status==="failed"?(this.eventsFailed+=1,i.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",i.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,i.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,i.skipped+=1),i.totalDuration+=e.duration,e.metadata){let n=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);n>0&&(this.pageViewSent+=n,i.pageViewSent+=n),o>0&&(this.pageViewDeduped+=o,i.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,i.pageViewFailed+=s);let a=e.metadata.pixelIds,l=e.metadata.tagIds,u=a??l;if(u&&n>0)for(let c of u.slice(0,n))this.recordDestinationId(t,c,"sent",n/u.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,i.pageViewFailed+=1)}recordDestinationId(e,t,i,n){let o=`${e}:${t}`,s=this.perDestinationId.get(o);s||(s={sent:0,failed:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0},this.perDestinationId.set(o,s)),i==="sent"?(s.sent+=n,s.pageViewSent+=n):(s.failed+=n,s.pageViewFailed+=n)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[i,n]of this.perDestination){let o=n.sent+n.failed;t[i]={sent:n.sent,failed:n.failed,ignored:n.ignored,skipped:n.skipped,averageDuration:o>0?n.totalDuration/o:0,successRate:o>0?n.sent/o:0,pageViewSent:n.pageViewSent,pageViewDeduped:n.pageViewDeduped,pageViewFailed:n.pageViewFailed,scriptLoadAttempts:n.scriptLoadAttempts,scriptLoadSuccess:n.scriptLoadSuccess,scriptLoadFailure:n.scriptLoadFailure,initAttempts:n.initAttempts,initSuccess:n.initSuccess,initFailure:n.initFailure,lastError:n.lastError}}return{registeredDestinations:this.registeredDestinations,activeDestinations:this.registeredDestinations,eventsSent:this.eventsSent,eventsFailed:this.eventsFailed,eventsIgnored:this.eventsIgnored,eventsSkipped:this.eventsSkipped,pageViewReceived:this.pageViewReceived,pageViewSent:this.pageViewSent,pageViewSkipped:this.pageViewSkipped,pageViewDeduped:this.pageViewDeduped,pageViewFailed:this.pageViewFailed,scriptLoadAttempts:this.scriptLoadAttempts,scriptLoadSuccess:this.scriptLoadSuccess,scriptLoadFailure:this.scriptLoadFailure,initAttempts:this.initAttempts,initSuccess:this.initSuccess,initFailure:this.initFailure,averageDuration:e>0?this.totalDuration/e:0,successRate:e>0?this.eventsSent/e:0,lastExecutionAt:this.lastExecutionAt,lastErrorAt:this.lastErrorAt,lastErrorMessage:this.lastErrorMessage,perDestination:t,perDestinationId:Object.fromEntries(this.perDestinationId)}}reset(){this.registeredDestinations=0,this.eventsSent=0,this.eventsFailed=0,this.eventsIgnored=0,this.eventsSkipped=0,this.pageViewReceived=0,this.pageViewSent=0,this.pageViewSkipped=0,this.pageViewDeduped=0,this.pageViewFailed=0,this.scriptLoadAttempts=0,this.scriptLoadSuccess=0,this.scriptLoadFailure=0,this.initAttempts=0,this.initSuccess=0,this.initFailure=0,this.totalDuration=0,this.lastExecutionAt=null,this.lastErrorAt=null,this.lastErrorMessage=null,this.perDestination.clear(),this.perDestinationId.clear()}};var Lt=class r{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new r(this.logger,e)}debug(e,...t){this.logger.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.logger.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.logger.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.logger.error(`[${this.scope}] ${e}`,...t)}};var Ot=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,i){let n=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${n}`),{status:"failed",adapter:e.name,duration:i,timestamp:Date.now(),error:n}}shouldContinue(){return this.continueOnError}};var Ft=class{constructor(e){this.logger=e.logger,this.errorHandler=e.errorHandler,this.hooks=e.hooks??{},this.timeoutMs=e.timeoutMs,this.debug=e.debug??!1}async execute(e,t){let i=Date.now(),n=new AbortController,o=setTimeout(()=>n.abort(),this.timeoutMs),s={event:t,signal:n.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),l={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-i,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,l),l.status==="success"?await this.hooks.onSuccess?.(e,t,l):l.status==="failed"||l.status==="retry"?await this.hooks.onFailure?.(e,t,l):(l.status==="ignored"||l.status==="skipped")&&await this.hooks.onIgnored?.(e,t,l),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${l.status} in ${l.duration}ms`),l}catch(a){let l=this.errorHandler.toFailedResult(e,a,Date.now()-i);return await this.hooks.onFailure?.(e,t,l),await this.hooks.afterExecute?.(e,t,l),l}finally{clearTimeout(o)}}};var Nt=class{constructor(e){this.lastResults=[];this.registry=e.registry,this.executor=e.executor,this.metrics=e.metrics,this.logger=e.logger;let t=e.concurrency??3;this.concurrency=t<=0?1:t}async dispatch(e){let t=this.registry.supports(e);if(t.length===0)return this.lastResults=[],[];let i=[];for(let n=0;n<t.length;n+=this.concurrency){let o=t.slice(n,n+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let l=s[a],u=o[a];if(l.status==="fulfilled")i.push(l.value),this.metrics.record(l.value);else{let c={status:"failed",adapter:u.name,duration:0,timestamp:Date.now(),error:l.reason instanceof Error?l.reason.message:String(l.reason)};i.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${u.name}`,l.reason)}}}return this.lastResults=i,i}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var Bt=class r{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new r([{name:"identity",process(e){return e}}])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,i}getLastSteps(){return this.lastSteps}};var Vt=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var ae=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),R=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??ae}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,i){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...i}}};var Ut=class extends R{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:ae});this.sent=0;this.log=t.log??((i,n)=>{console.log(i,n)})}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});let n={type:t.event.type,timestamp:t.event.timestamp,category:"category"in t.event?t.event.category:void 0};return this.log(`[Console] ${t.event.type}`,n),this.sent+=1,this.createResult("success",Date.now()-i,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var zt=class extends R{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:ae});this.records=[]}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});let n=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:n}),this.createResult("success",Date.now()-i,{metadata:{recordCount:this.records.length}})}getRecords(){return[...this.records]}clear(){this.records.length=0}destroy(){this.clear()}transform(t){return{destination:"memory",eventType:t.type,timestamp:t.timestamp,path:"path"in t?t.path:void 0,data:"data"in t?t.data:void 0}}};var qt=class extends R{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??ae});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let i=Date.now();if(this.executions+=1,this.delayMs>0&&await this.wait(this.delayMs,t.signal),t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-i,{ignored:!0});if(this.failOnTypes.has(t.event.type))throw new Error(`[Mock] Simulated failure for ${t.event.type}`);return this.createResult("success",Date.now()-i,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,i){return new Promise((n,o)=>{let s=setTimeout(()=>{l(),n()},t),a=()=>{l(),o(new DOMException("The operation was aborted.","AbortError"))},l=()=>{clearTimeout(s),i.removeEventListener("abort",a)};if(i.aborted){l(),o(new DOMException("The operation was aborted.","AbortError"));return}i.addEventListener("abort",a)})}};var Ko=new Set;function le(r,e,t,i,n){return`${r}:${e}:${t}:${i}:${n}`}function ue(r){return Ko.has(r)?!0:(Ko.add(r),!1)}var Oe=new Map;function be(r){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=Oe.get(r.src);if(e)return e.refCount+=1,e.promise;let t=r.timeoutMs??1e4,i=new Promise((n,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=r.src,r.id&&(s.id=r.id),r.attributes)for(let[u,c]of Object.entries(r.attributes))s.setAttribute(u,c);let a=setTimeout(()=>{l(),o(new Error(`[ScriptLoader] Timeout loading ${r.src}`))},t),l=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{l();let u=Oe.get(r.src);u&&(u.loaded=!0),n()},s.onerror=()=>{l(),Oe.delete(r.src),o(new Error(`[ScriptLoader] Failed to load ${r.src}`))},document.head.appendChild(s)});return Oe.set(r.src,{promise:i,refCount:1,loaded:!1}),i}function Se(r){let e=Oe.get(r);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&Oe.delete(r))}var ui="https://connect.facebook.net/en_US/fbevents.js";function ou(){return typeof window<"u"?window:null}function su(){let r=ou();if(!r)throw new Error("[MetaScriptLoader] window unavailable");if(r.fbq)return r.fbq;let e=function(...t){let i=e;i.callMethod?i.callMethod(...t):(i.queue=i.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],r.fbq=e,r._fbq||(r._fbq=e),e}var Ht=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[MetaScriptLoader] Browser APIs unavailable");let t=su();return this.loaded&&t.loaded||(await be({src:ui,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){Se(ui)}};var $t=class extends R{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Ht;this.initialized=!1;this.fbq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("MetaBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("meta"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("meta"),this.debug&&this.logger.debug("script_load_start");try{this.fbq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("meta"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("meta"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.fbq&&(this.fbq=window.fbq??null);let i=this.fbq;if(!i)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let n=!1;for(let o of this.pixelIds)try{i("init",o)}catch(s){n=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-i,{error:m instanceof Error?m.message:String(m)})}let a=this.fbq??(typeof window<"u"?window.fbq??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"fbq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let h=le("meta",m,"PAGE_VIEW",l,u);if(ue(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${m}`);continue}try{if(typeof a=="function")try{a("trackSingle",m,"PageView")}catch{a("track","PageView")}c+=1,this.debug&&this.logger.debug(`pageview_sent id=${m}`)}catch(p){this.logger.error(`destination_execute_failure id=${m}`,p)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var fn="https://www.googletagmanager.com/gtag/js";function au(){return typeof window<"u"?window:null}function lu(){let r=au();if(!r)throw new Error("[GoogleScriptLoader] window unavailable");return r.dataLayer=r.dataLayer||[],r.gtag||(r.gtag=function(...t){r.dataLayer?.push(t)}),r.gtag}var Kt=class{constructor(){this.loadedSrc=null}async load(e,t=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[GoogleScriptLoader] Browser APIs unavailable");let i=lu(),n=`${fn}?id=${encodeURIComponent(e)}`;return await be({src:n,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=n,i("js",new Date),i}release(){this.loadedSrc&&(Se(this.loadedSrc),this.loadedSrc=null)}};var Wt=class extends R{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Kt;this.initialized=!1;this.gtag=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("GoogleBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.tagIds=[...new Set(t.config.tagIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.tagIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.tagIds.length===0)return;this.metrics?.recordInitAttempt("google"),this.debug&&this.logger.debug("destination_init_start");let i=this.tagIds[0];if(this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("google"),this.debug&&this.logger.debug("script_load_start");try{this.gtag=await this.scriptLoader.load(i,t),this.metrics?.recordScriptLoadSuccess("google"),this.debug&&this.logger.debug("script_load_success")}catch(s){throw this.metrics?.recordScriptLoadFailure("google"),this.logger.error("script_load_failure",s),s}}else typeof window<"u"&&window.gtag&&(this.gtag=window.gtag??null);let n=this.gtag;if(!n)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{n("config",s,{send_page_view:!1})}catch(a){o=!0,this.metrics?.recordInitFailure("google"),this.logger.error(`destination_init_failure id=${s}`,a)}this.initialized=!0,o||this.metrics?.recordInitSuccess("google"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-i,{error:p instanceof Error?p.message:String(p)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"gtag unavailable"});let l=n.path??"/",u=n.url??(typeof window<"u"?window.location?.href:void 0)??l,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,h=0;for(let p of this.tagIds){let f=le("google",p,"PAGE_VIEW",l,d);if(ue(f)){h+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a("event","page_view",{send_to:p,page_location:u,page_path:l,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(b){this.logger.error(`destination_execute_failure id=${p}`,b)}}return m===0&&h>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:m,deduped:h}}):this.createResult("success",Date.now()-i,{metadata:{sent:m,deduped:h,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var ci="https://analytics.tiktok.com/i18n/pixel/events.js";function Wo(){return typeof window<"u"?window:null}function uu(){let r=Wo();if(!r)throw new Error("[TikTokScriptLoader] window unavailable");if(r.ttq)return r.ttq;let e={load(){},page(){},track(){}};return r.TiktokAnalyticsObject="ttq",r.ttq=e,e}var Gt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[TikTokScriptLoader] Browser APIs unavailable");let t=uu();return this.loaded?t:(await be({src:ci,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,Wo()?.ttq??t)}release(){Se(ci)}};var Qt=class extends R{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Gt;this.initialized=!1;this.ttq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("TikTokBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("tiktok"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("tiktok"),this.debug&&this.logger.debug("script_load_start");try{this.ttq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("tiktok"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("tiktok"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.ttq&&(this.ttq=window.ttq??null);let i=this.ttq;if(!i)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let n=!1;for(let o of this.pixelIds)try{i.load(o)}catch(s){n=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-i,{error:h instanceof Error?h.message:String(h)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"ttq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let h of this.pixelIds){let p=le("tiktok",h,"PAGE_VIEW",l,u);if(ue(p)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a.instance(h).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(f){this.logger.error(`destination_execute_failure id=${h}`,f)}}else{let h=this.pixelIds[0]??"global",p=le("tiktok",h,"PAGE_VIEW",l,u);if(ue(p))d=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),c=1,this.debug&&this.logger.debug("pageview_sent global")}catch(f){this.logger.error("destination_execute_failure global",f)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var jt=class{constructor(e,t,i,n=[]){this.memoryDestination=null;this.active=!1;this.registry=new Pt,this.metrics=new _t,this.logger=new Lt(e),this.pipeline=Bt.identity(),this.debug=t.moduleConfig.debug;let o=new Ot(this.logger,t.moduleConfig.continueOnError),s=new Ft({logger:this.logger,errorHandler:o,hooks:i,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Nt({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,l=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new Ut({log:l?(u,c)=>this.logger.debug(u,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new zt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new qt),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new $t({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new Wt({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new Qt({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l}));for(let u of n)this.registry.register(u);this.metrics.setRegisteredCount(this.registry.size())}init(){this.active||(this.active=!0,this.debug&&this.logger.debug("IntegrationEngine initialized (browser destinations)"))}destroy(){this.active&&(this.registry.clear(),this.metrics.reset(),this.dispatcher.clearLastResults(),this.memoryDestination=null,this.active=!1,this.debug&&this.logger.debug("IntegrationEngine destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);if(!t){this.debug&&this.logger.debug(`Event dropped by destination pipeline: ${e.type}`);return}this.dispatcher.dispatch(t)}async handleEventAsync(e){if(!this.active)return[];e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);return t?this.dispatcher.dispatch(t):[]}registerDestination(e){this.registry.register(e),this.metrics.setRegisteredCount(this.registry.size())}removeDestination(e){let t=this.registry.remove(e);return this.metrics.setRegisteredCount(this.registry.size()),t}getRegistry(){return this.registry}getMemoryRecords(){return this.memoryDestination?.getRecords()??[]}getDebugState(){return{active:this.active,destinationNames:this.registry.getAll().map(e=>e.name),metrics:this.metrics.getSnapshot(),lastResults:this.dispatcher.getLastResults()}}};var Yt=class{constructor(){this.name="integrations";this.engine=null;this.subscriber=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Integrations module already initialized");return}if(!e.config.modules.integrations.enabled){e.logger.debug("[Pixel] Integrations module disabled");return}let t=e.config.modules.integrations;this.engine=new jt(e.logger,{moduleConfig:{...t,debug:t.debug||e.config.app.debug===!0},getSessionId:()=>e.services.session.getSessionId()??`anon_${e.config.identity.pixelId||"pixel"}`}),this.engine.init(),this.subscriber=new Vt(e.services.dispatcher,i=>this.engine?.handleEvent(i)),this.subscriber.subscribe(),this.active=!0,e.logger.debug("[Pixel] Integrations module initialized")}destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}registerDestination(e){this.engine?.registerDestination(e)}removeDestination(e){return this.engine?.removeDestination(e)??!1}getMemoryRecords(){return this.engine?.getMemoryRecords()??[]}handleEventAsync(e){return this.engine?.handleEventAsync(e)??Promise.resolve([])}};var Xt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var di=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var mi=class{constructor(){this.buffer=[];this.oldestAt=null}add(e){e.length!==0&&(this.buffer.length===0&&(this.oldestAt=Date.now()),this.buffer.push(...e))}takeBatch(e){if(this.buffer.length===0)return[];let t=e??this.buffer.length,i=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),i}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1:!e.enabled||this.buffer.length>=e.batchSize||this.oldestAt!==null&&Date.now()-this.oldestAt>=e.maxWaitMs}getState(){return{bufferSize:this.buffer.length,oldestEventAt:this.oldestAt,pendingBatches:this.buffer.length}}};var Fe=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function yn(r){return!r.enabled||r.strategy==="identity"?new Fe:new Fe}function Go(r,e,t){return{enabled:r.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Zt=class{constructor(e,t){this.channel=null;this.isLeader=!1;this.leaderTabId=null;this.tabCount=1;this.heartbeatTimer=null;this.onLeaderChange=null;this.storageListener=null;this.transport="none";this.config=e,this.tabId=`tab_${t}_${crypto.randomUUID().slice(0,8)}`,this.channelName=e.channelName??`pixel_transport_coordination_${t}`,this.storageKey=`${this.channelName}:leader`}init(e){if(!this.config.enabled||typeof window>"u"){this.isLeader=!0,this.leaderTabId=this.tabId;return}this.onLeaderChange=e??null,typeof BroadcastChannel<"u"?(this.transport="broadcastChannel",this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=t=>this.handleMessage(t.data)):(this.transport="storageEvents",this.storageListener=t=>{if(!(t.key!==this.storageKey||!t.newValue))try{this.handleMessage(JSON.parse(t.newValue))}catch{}},window.addEventListener("storage",this.storageListener)),this.claimLeadership(),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),2e3)}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.isLeader&&this.releaseLeadership(),this.channel&&(this.channel.close(),this.channel=null),this.storageListener&&typeof window<"u"&&(window.removeEventListener("storage",this.storageListener),this.storageListener=null),this.onLeaderChange=null}canSend(){return this.config.enabled?this.isLeader:!0}shouldPersistOnly(){return this.config.enabled&&!this.isLeader}isTabLeader(){return this.isLeader}getDebugState(){return{enabled:this.config.enabled,tabId:this.tabId,isLeader:this.isLeader,leaderTabId:this.leaderTabId,tabCount:this.tabCount,transport:this.transport}}claimLeadership(){let e={type:"leader_claim",tabId:this.tabId,at:Date.now()};this.broadcast(e),this.leaderTabId||this.setLeader(this.tabId)}releaseLeadership(){let e={type:"leader_release",tabId:this.tabId};this.broadcast(e),this.isLeader&&this.setLeader(null)}sendHeartbeat(){this.isLeader&&this.broadcast({type:"heartbeat",tabId:this.tabId,at:Date.now()})}handleMessage(e){switch(e.type){case"leader_claim":(!this.leaderTabId||e.at<Date.now())&&this.setLeader(e.tabId);break;case"leader_release":this.leaderTabId===e.tabId&&(this.setLeader(null),this.isLeader||this.claimLeadership());break;case"heartbeat":this.tabCount=Math.max(this.tabCount,1),this.leaderTabId===e.tabId&&(this.leaderTabId=e.tabId);break;default:break}}setLeader(e){let t=this.isLeader;this.leaderTabId=e,this.isLeader=e===this.tabId,t!==this.isLeader&&this.onLeaderChange?.(this.isLeader)}broadcast(e){if(this.channel){this.channel.postMessage(e);return}if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}};var Jt=class{constructor(e){this.entries=[];this.config=e}move(e,t,i=0,n){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:i,lastError:n};return this.entries.push(o),this.entries.length>this.config.maxEntries&&(this.entries=this.entries.slice(-this.config.maxEntries)),o}replayEntry(e){let t=this.entries.findIndex(n=>n.id===e);if(t<0)return null;let[i]=this.entries.splice(t,1);return i?.events??null}replayAll(){let e=this.entries.flatMap(t=>[...t.events]);return this.entries=[],e}clear(){this.entries=[]}getEntries(){return[...this.entries]}getCount(){return this.entries.length}getDebugState(){return{enabled:this.config.enabled,count:this.entries.length,maxEntries:this.config.maxEntries,entries:this.getEntries()}}};var pi=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=null;this.maxWaitTimer=null;this.batchManager=e.batchManager,this.flushManager=e.flushManager,this.retryEngine=e.retryEngine,this.offlineDetector=e.offlineDetector,this.sender=e.sender,this.config=e.config,this.logger=e.logger,this.abortPending=e.abortPending??null,this.onPermanentFailure=e.onPermanentFailure??null}init(){this.active||(this.offlineDetector.init(()=>{this.logger.debug("[TransportDelivery] Online \u2014 resuming"),this.flush()},()=>{this.logger.debug("[TransportDelivery] Offline \u2014 paused")}),this.flushManager.init(()=>this.flush()),this.active=!0)}destroy(){this.active&&(this.abortPending?.(),this.retryEngine.cancelAll(),this.flushManager.destroy(),this.offlineDetector.destroy(),this.clearMaxWaitTimer(),this.batchManager.clear(),this.active=!1,this.inFlight=!1)}ingest(e){!this.active||e.length===0||(this.batchManager.add(e),this.batchManager.shouldFlush(this.config.batch)?this.flush():this.scheduleMaxWaitFlush())}flush(){!this.active||!this.offlineDetector.isOnline()||(this.clearMaxWaitTimer(),this.processBatch())}getDebugState(){return{batch:this.batchManager.getState(),retry:this.retryEngine.getState(),offline:this.offlineDetector.getState(),flush:this.flushManager.getState(),timeoutMs:this.config.timeoutMs,inFlight:this.inFlight,ackCount:this.ackCount}}getOfflineDetector(){return this.offlineDetector}async processBatch(){if(this.inFlight||!this.offlineDetector.isOnline())return;let e=this.batchManager.takeBatch(this.config.batch.enabled?this.config.batch.batchSize:1);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e,{deliveryMode:this.config.batch.enabled&&e.length>1?"batch":"single"});if(!t.ack)throw new Error("[TransportDelivery] Send not acknowledged");this.ackCount+=t.eventCount},`delivery-${Date.now()}`)}catch(t){this.logger.error("[TransportDelivery] Delivery failed after retries",t),this.onPermanentFailure?this.onPermanentFailure(e,t):this.batchManager.add(e)}finally{this.inFlight=!1,this.batchManager.size()>0&&this.offlineDetector.isOnline()&&this.flush()}}}scheduleMaxWaitFlush(){if(!this.config.batch.enabled||this.maxWaitTimer!==null||this.config.batch.maxWaitMs<=0){this.config.batch.maxWaitMs<=0&&this.flush();return}this.maxWaitTimer=setTimeout(()=>{this.maxWaitTimer=null,this.flush()},this.config.batch.maxWaitMs)}clearMaxWaitTimer(){this.maxWaitTimer!==null&&(clearTimeout(this.maxWaitTimer),this.maxWaitTimer=null)}};var hi=class{constructor(e){this.onFlush=null;this.intervalId=null;this.flushCount=0;this.lastFlushAt=null;this.listeners=[];this.config=e}init(e){this.onFlush=e,this.config.flushIntervalMs>0&&(this.intervalId=setInterval(()=>this.flush(),this.config.flushIntervalMs)),this.config.prepareUnloadHooks&&this.registerUnloadHooks()}flush(){this.onFlush&&(this.flushCount+=1,this.lastFlushAt=Date.now(),this.onFlush())}destroy(){this.config.flushOnDestroy&&this.flush(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.removeListeners(),this.onFlush=null}getState(){return{flushCount:this.flushCount,lastFlushAt:this.lastFlushAt,intervalActive:this.intervalId!==null}}registerUnloadHooks(){if(typeof window>"u")return;let e=()=>this.flush();for(let t of["pagehide","beforeunload"])window.addEventListener(t,e),this.listeners.push({target:"window",type:t,handler:e});typeof document<"u"&&(document.addEventListener("visibilitychange",e),this.listeners.push({target:"document",type:"visibilitychange",handler:e}))}removeListeners(){for(let e of this.listeners)e.target==="window"&&typeof window<"u"?window.removeEventListener(e.type,e.handler):e.target==="document"&&typeof document<"u"&&document.removeEventListener(e.type,e.handler);this.listeners.length=0}};var gi=class{constructor(){this.online=!0;this.paused=!1;this.simulatedOffline=!1;this.onOnline=null;this.onOffline=null;this.listeners=[]}init(e,t){if(this.onOnline=e,this.onOffline=t,typeof window>"u")return;this.online=typeof navigator>"u"?!0:navigator.onLine;let i=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},n=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",i),window.addEventListener("offline",n),this.listeners.push({type:"online",handler:i},{type:"offline",handler:n})}isOnline(){return this.online&&!this.simulatedOffline}isPaused(){return this.paused||this.simulatedOffline}destroy(){if(typeof window<"u")for(let e of this.listeners)window.removeEventListener(e.type,e.handler);this.listeners.length=0,this.onOnline=null,this.onOffline=null}simulateOffline(e){this.simulatedOffline=e,e?(this.paused=!0,this.onOffline?.()):(this.paused=!1,this.online=!0,this.onOnline?.())}getState(){return{isOnline:this.isOnline(),paused:this.isPaused(),simulatedOffline:this.simulatedOffline}}};var er=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,i){return this.enabled&&(this.globalSequence+=1,this.sessionSequence+=1),t&&(this.lastCorrelationId=t),{id:crypto.randomUUID(),event:e,sequence:this.globalSequence,sessionSequence:this.sessionSequence,correlationId:t??this.lastCorrelationId??void 0,transactionGroup:i,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,i)=>t.sequence!==i.sequence?t.sequence-i.sequence:t.enqueuedAt-i.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),i=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,i);let n=[...e].reverse().find(o=>o.correlationId);n?.correlationId&&(this.lastCorrelationId=n.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var fi=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var yi=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var vi=class{constructor(){this.name="validate"}process(e){return!e.type||typeof e.type!="string"||typeof e.timestamp!="number"||Number.isNaN(e.timestamp)?null:e}};var bi=class r{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new r([new vi,new yi,new fi(e)])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,{event:i,steps:t}}getLastSteps(){return this.lastSteps}};var Si=class{constructor(e,t,i){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=i}async init(){await this.storage.init();let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}destroy(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.flushPersist(),this.storage.destroy(),this.records=[],this.loaded=!1}enqueue(e){this.ensureLoaded();let t=this.backpressure.evaluateEnqueue(this.records.length);if(!t.accepted||(t.policy==="drop_oldest"&&this.records.length>0&&this.records.shift(),t.policy==="drop_newest"&&t.dropped>0))return;let i=this.ordering.assign(e),n=this.backpressure.applyPolicy(this.records,i);this.records=n.items,this.schedulePersist()}dequeue(){this.ensureLoaded();let e=this.records.shift();return this.schedulePersist(),e?.event}peek(){return this.ensureLoaded(),this.records[0]?.event}size(){return this.ensureLoaded(),this.records.length}clear(){this.records=[],this.schedulePersist()}remove(e){this.ensureLoaded();let t=this.records.length;this.records=this.records.filter(n=>!e(n.event));let i=t-this.records.length;return i>0&&this.schedulePersist(),i}isEmpty(){return this.size()===0}getAll(){return this.ensureLoaded(),this.records.map(e=>e.event)}getRecords(){return this.ensureLoaded(),[...this.records]}importRecords(e){this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.schedulePersist()}exportRecords(){return this.getRecords()}getStorageAdapterName(){return this.storage.getAdapterName()}async reload(){let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}ensureLoaded(){this.loaded||(this.loaded=!0)}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersist()},0)}async flushPersist(){await this.storage.save(this.records)}};var Ci=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.shift()}peek(){return this.items[0]}size(){return this.items.length}clear(){this.items.length=0}remove(e){let t=this.items.length,i=this.items.filter(n=>!e(n));return this.items.length=0,this.items.push(...i),t-i.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var Ce=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var tr=class{constructor(e){this.storageKey=e}init(){}destroy(){}load(){if(typeof window>"u"||!window.localStorage)return[];try{let e=window.localStorage.getItem(this.storageKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}save(e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}getAdapterName(){return"LocalStorageQueueStorage"}isAvailable(){if(typeof window>"u")return!1;try{let e=`${this.storageKey}__probe`;return window.localStorage.setItem(e,"1"),window.localStorage.removeItem(e),!0}catch{return!1}}};var Ne="queue_records",rr=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let i=indexedDB.open(this.dbName,1);i.onupgradeneeded=()=>{let n=i.result;n.objectStoreNames.contains(Ne)||n.createObjectStore(Ne,{keyPath:"id"})},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error??new Error("IndexedDB open failed"))}))}destroy(){this.db?.close(),this.db=null}async load(){return this.db?new Promise((e,t)=>{let o=this.db.transaction(Ne,"readonly").objectStore(Ne).getAll();o.onsuccess=()=>{let s=o.result;e(Array.isArray(s)?s:[])},o.onerror=()=>t(o.error??new Error("IndexedDB load failed"))}):[]}async save(e){this.db&&await new Promise((t,i)=>{let n=this.db.transaction(Ne,"readwrite"),o=n.objectStore(Ne),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},n.oncomplete=()=>t(),n.onerror=()=>i(n.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function cu(r){let e=r.prefix??"__gmk",t=r.namespace||"pixel",i=r.pixelId||"default";return`${e}:${t}:${i}:transport-queue`}function du(r){let e=r.namespace||"pixel",t=r.pixelId||"default";return`${e}_${t}_transport_queue`}function mu(r,e){let t=cu(e);switch(r){case"localStorage":return new tr(t);case"indexedDB":return new rr(du(e));case"memory":default:return new Ce}}function pu(r){let e=["indexedDB","localStorage","memory"];if(!r||r==="memory")return e;let t=e.filter(i=>i!==r);return[r,...t]}function Qo(r){if(typeof window>"u")return new Ce;let e=pu(r.preferred);for(let t of e){let i=mu(t,r);if(i.isAvailable())return i}return new Ce}function vn(r){return Qo({preferred:r.storage.queue?.persistence,namespace:r.storage.namespace,prefix:r.storage.prefix,pixelId:r.identity.pixelId})}var ir=class{constructor(e,t){this.lastTrigger=null;this.lastReplayAt=null;this.totalReplayed=0;this.onReplay=null;this.config=e,this.queue=t}setReplayHandler(e){this.onReplay=e}async replay(e){if(!this.config.enabled)return 0;await this.queue.reload();let t=this.queue.size();return this.lastTrigger=e,this.lastReplayAt=Date.now(),this.totalReplayed+=t,t>0&&this.onReplay?.(),t}getPendingEvents(){return this.queue.getAll()}getDebugState(){return{enabled:this.config.enabled,lastTrigger:this.lastTrigger,lastReplayAt:this.lastReplayAt,totalReplayed:this.totalReplayed,pendingCount:this.queue.size()}}};var nr=class{constructor(e){this.totalDropped=0;this.totalRejected=0;this.totalSampled=0;this.config=e}evaluateEnqueue(e){if(!this.config.enabled||this.config.policy==="none")return{accepted:!0,dropped:0,policy:this.config.policy};if(e<this.config.maxQueueSize)return{accepted:!0,dropped:0,policy:this.config.policy};switch(this.config.policy){case"reject_new":return this.totalRejected+=1,{accepted:!1,dropped:0,policy:this.config.policy,reason:"queue_full_reject_new"};case"sample":{let t=this.config.sampleRate??.5,i=Math.random()<t;return i||(this.totalSampled+=1),{accepted:i,dropped:i?0:1,policy:this.config.policy,reason:i?void 0:"sampled_out"}}case"drop_oldest":case"drop_newest":return{accepted:!0,dropped:1,policy:this.config.policy};default:return{accepted:!0,dropped:0,policy:"none"}}}applyPolicy(e,t){let i=this.evaluateEnqueue(e.length);return i.accepted?e.length<this.config.maxQueueSize?{items:[...e,t],dropped:0}:this.config.policy==="drop_oldest"?(this.totalDropped+=1,{items:[...e.slice(1),t],dropped:1}):this.config.policy==="drop_newest"?(this.totalDropped+=1,{items:e,dropped:1}):{items:[...e,t],dropped:0}:{items:e,dropped:i.dropped}}getDebugState(e){return{enabled:this.config.enabled,currentSize:e,maxQueueSize:this.config.maxQueueSize,policy:this.config.policy,totalDropped:this.totalDropped,totalRejected:this.totalRejected,totalSampled:this.totalSampled}}};var or=class{constructor(e){this.state="closed";this.consecutiveFailures=0;this.totalFailures=0;this.totalSuccesses=0;this.totalBlocked=0;this.halfOpenAttempts=0;this.lastFailureAt=null;this.lastSuccessAt=null;this.openedAt=null;this.config=e}canExecute(){return!this.config.enabled||this.state==="closed"?!0:this.state==="open"?this.openedAt!==null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs?(this.state="half_open",this.halfOpenAttempts=0,!0):(this.totalBlocked+=1,!1):this.halfOpenAttempts<this.config.halfOpenMaxAttempts}recordSuccess(){this.config.enabled&&(this.totalSuccesses+=1,this.lastSuccessAt=Date.now(),this.consecutiveFailures=0,this.halfOpenAttempts=0,this.state="closed",this.openedAt=null)}recordFailure(){if(this.config.enabled){if(this.totalFailures+=1,this.lastFailureAt=Date.now(),this.consecutiveFailures+=1,this.state==="half_open"){this.halfOpenAttempts+=1,this.halfOpenAttempts>=this.config.halfOpenMaxAttempts&&this.open();return}this.consecutiveFailures>=this.config.failureThreshold&&this.open()}}forceOpen(){this.open()}forceClose(){this.state="closed",this.consecutiveFailures=0,this.halfOpenAttempts=0,this.openedAt=null}getMetrics(){return{state:this.state,consecutiveFailures:this.consecutiveFailures,totalFailures:this.totalFailures,totalSuccesses:this.totalSuccesses,totalBlocked:this.totalBlocked,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,openedAt:this.openedAt}}open(){this.state="open",this.openedAt=Date.now()}};var sr=class{constructor(e,t){this.circuitBreaker=e,this.inner=t}async send(e,t){if(!this.circuitBreaker.canExecute())throw new Error("[CircuitBreakerSender] Circuit is open \u2014 send blocked");try{let i=await this.inner.send(e,t);return i.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),i}catch(i){throw this.circuitBreaker.recordFailure(),i}}getCircuitBreaker(){return this.circuitBreaker}};function jo(r,e){let t=e.baseDelayMs*e.multiplier**(r-1);return Math.min(t,e.maxDelayMs)}var Ei=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let i=t??`retry-${++this.idCounter}`;return new Promise((n,o)=>{let s=!1,a={id:i,task:e,attempt:0,status:"pending",nextRetryAt:null,timer:null,abort:()=>{s=!0,a.timer&&clearTimeout(a.timer),a.status="cancelled",a.timer=null,this.entries.delete(i),n()}};this.entries.set(i,a);let l=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(i),n()}catch(u){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(i),o(u);return}let c=jo(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+c,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${c}ms`),a.timer=setTimeout(()=>{a.timer=null,l()},c)}}};l()})}cancel(e){this.entries.get(e)?.abort()}cancelAll(){for(let e of this.entries.values())e.abort();this.entries.clear()}getState(){return{pendingCount:this.entries.size,attempts:Array.from(this.entries.values()).map(e=>({id:e.id,attempt:e.attempt,nextRetryAt:e.nextRetryAt,status:e.status}))}}};function ce(r){return r?Object.values(r).some(e=>typeof e=="string"&&e.trim().length>0):!1}function bn(r){return{...r}}function hu(r){return{source:String(r.app.source??""),target:String(r.app.target??""),platform:String(r.app.platform??""),environment:String(r.app.environment??"")}}function Yo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function gu(r){if("category"in r&&r.category){if(r.category==="ENGAGEMENT")return"ENGAGEMENT";if(r.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function fu(r,e){let t;if("data"in r&&r.data&&typeof r.data=="object")t={...r.data};else{let{type:i,timestamp:n,category:o,path:s,url:a,hostname:l,language:u,timezone:c,identifiers:d,queryParams:m,urlContext:h,customer:p,...f}=r;t=Object.keys(f).length>0?f:void 0}return ce(e)?{...t??{},customer:{...e}}:t}function yu(r){let e={fbp:r?.fbp??"",fbc:r?.fbc??"",ga:r?.ga??"",gcl_au:r?.gclAu??""};return r?{...e,fbclid:r.fbclid??"",gclid:r.gclid??"",gbraid:r.gbraid??"",wbraid:r.wbraid??"",gid:r.gid??"",ttclid:r.ttclid??"",ttp:r.ttp??"",msclkid:r.msclkid??"",li_fat_id:r.liFatId??"",epik:r.epik??"",customClickIds:r.customClickIds??{},landingUrl:r.landingUrl??"",referrer:r.referrer??"",firstCollectedAt:r.firstCollectedAt??0,lastCollectedAt:r.lastCollectedAt??0}:e}var xi=class{constructor(e){this.context=e}buildApiEvent(e,t){let i=this.context.config,n=this.context.services,o=n.browserMetadata.getMetadata(),s=n.visitor.getVisitorId()??n.visitor.ensureVisitorId(),a=n.session.getSessionId()??`session_${i.identity.pixelId||"anonymous"}_${Date.now()}`,l=n.fingerprint.getFingerprint()??n.fingerprint.ensureFingerprint(),u="identifiers"in e&&e.identifiers?e.identifiers:n.attribution?.getSnapshot(),c="customer"in e&&e.customer?e.customer:n.customerIdentity?.getSnapshot()??null;return{id:t??Yo(),session_id:a,visitor_id:s,pixel_code:i.identity.pixelId,type:e.type,category:gu(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:yu(u),page:{url:e.url??o.url??"",title:typeof document<"u"?document.title:"",referrer:typeof document<"u"?document.referrer:"",path:e.path??o.path??"",hostname:e.hostname??o.hostname??""},device:{id:l,type:"desktop",os:{name:"Unknown",version:""},browser:{name:"Unknown",version:""},engine:{name:"Unknown",version:""},userAgent:o.userAgent??"",language:e.language??o.language??"",screen:{width:o.screenWidth??0,height:o.screenHeight??0,pixel_ratio:1}},...ce(c)?{customer:{...c}}:{},data:fu(e,c),..."queryParams"in e&&e.queryParams&&Object.keys(e.queryParams).length>0?{query_params:{...e.queryParams}}:{},..."urlContext"in e&&e.urlContext?{url_context:{...e.urlContext.managed?{managed:{...e.urlContext.managed}}:{},...e.urlContext.forwarded?{forwarded:{...e.urlContext.forwarded}}:{},...e.urlContext.source?{source:{...e.urlContext.source}}:{}}}:{},app:hu(i),meta:{version:"2.0.0",pixel_source:"pixel-v2",source:String(i.app.source??""),target:String(i.app.target??""),platform:String(i.app.platform??""),environment:i.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:i.identity.projectId??"",pageId:i.identity.pageId??""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),i=e.map(n=>this.buildApiEvent(n));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:Yo(),sent_at:Date.now(),app:t.app,meta:t.meta,events:i}}};async function Xo(r,e={}){let{timeoutMs:t=1e4,signal:i,...n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);i&&(i.aborted?o.abort():i.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(r,{...n,signal:o.signal})}finally{clearTimeout(s)}}var Be=class{constructor(e,t,i,n){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=i,this.logger=n}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(t?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let i=t?.deliveryMode??(e.length>1?"batch":"single");if(i==="single"&&e.length>1)return this.sendIndividually(e,t);if(i==="batch"&&!this.config.batchEndpoint){if(this.config.batchFallback==="single")return this.sendIndividually(e,t);throw new Error("[HttpSender] Batch endpoint is not configured.")}let n=i==="batch"&&e.length>1,o=n?this.config.batchEndpoint:this.config.eventEndpoint,s=JSON.stringify(n?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),a=this.compression.compress(s);this.lastCompression={originalSize:a.originalSize,compressedSize:a.compressedSize};try{let l=await Xo(o,{method:"POST",headers:{...this.config.headers,"Content-Type":"application/json","Content-Encoding":a.encoding},body:a.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),u=await l.json().catch(()=>({})),c=l.ok;if(this.lastAck=c,c&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:Zo(o),status:l.status,ack:c,eventCount:e.length,body:u}),!c)throw new Error(`[HttpSender] HTTP ${l.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(l){let u=l instanceof Error?l.message:String(l);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:Zo(o),status:0,ack:!1,eventCount:e.length,error:u}),l}}getState(){return{sentCount:this.sentCount,logs:this.responseLogs.map(e=>`[HttpSender] ${e.status} ack=${e.ack} events=${e.eventCount}${e.error?` err=${e.error}`:""}`),lastAck:this.lastAck,responses:[...this.responseLogs],compression:this.lastCompression,mode:this.config.mode}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}async sendIndividually(e,t){let i=0;for(let n of e){let o=await this.send([n],{...t,deliveryMode:"single"});if(!o.ack)throw new Error("[HttpSender] Individual send not acknowledged.");i+=o.eventCount}return{ack:!0,eventCount:i}}};function Zo(r){try{return new URL(r).origin}catch{return"[Present]"}}var Ve=class r{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.sentCount=0;this.lastAck=null;this.logger=e,this.options={capture:t.capture??!0,response:t.response??"success",delayMs:Jo(t.delayMs),failUntilAttempt:t.failUntilAttempt,simulateTimeout:t.simulateTimeout}}static fromConfig(e,t){return new r(e,t)}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(vu(t?.signal),this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw this.lastAck=!1,new Error(`[TestSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw this.lastAck=!1,new DOMException("The operation was aborted.","AbortError");if(await this.waitWithAbort(t?.signal),this.options.response==="failure")throw this.lastAck=!1,new Error("[TestSender] Simulated failure response");return this.options.capture&&this.sentBatches.push([...e]),this.sentCount+=e.length,this.lastAck=!0,this.logger.debug(`[TestSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentCount}getLogs(){return this.sentBatches.map(e=>`[TestSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck,mode:"test",capturedBatches:this.getSentBatches(),attempts:this.sendAttempts}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.sentCount=0,this.lastAck=null}configure(e){e.capture!==void 0&&(this.options.capture=e.capture),e.response!==void 0&&(this.options.response=e.response),e.delayMs!==void 0&&(this.options.delayMs=Jo(e.delayMs)),"failUntilAttempt"in e&&(this.options.failUntilAttempt=e.failUntilAttempt),e.simulateTimeout!==void 0&&(this.options.simulateTimeout=e.simulateTimeout)}waitWithAbort(e){let t=this.options.delayMs??0;return t===0?Promise.resolve():new Promise((i,n)=>{let o=setTimeout(()=>{a(),i()},t),s=()=>{a(),n(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted)return s();e?.addEventListener("abort",s,{once:!0})})}};function Jo(r){return Math.max(0,r??0)}function vu(r){if(r?.aborted)throw new DOMException("The operation was aborted.","AbortError")}var bu="/pixels/public/event",Su="/pixels/public/event/batch";function es(r,e){let t=Sn(r.baseUrl?.trim()||Rr,"transport.sender.baseUrl").replace(/\/+$/,"");return{mode:"internal",eventEndpoint:`${t}${bu}`,batchEndpoint:`${t}${Su}`,batchFallback:"error",headers:{},timeoutMs:e}}function ts(r,e,t){let i=Sn(r.endpoints.event,"transport.sender.endpoints.event"),n=r.endpoints.batch?Sn(r.endpoints.batch,"transport.sender.endpoints.batch"):void 0,o=r.batchFallback??"single";if(e.enabled&&!n&&o==="error")throw new Error('[Transport] Batch is enabled but transport.sender.endpoints.batch is missing. Provide endpoints.batch, disable batch, or use batchFallback: "single".');return{mode:"external",eventEndpoint:i,batchEndpoint:n,batchFallback:o,headers:Cu(r.headers),timeoutMs:t}}function Sn(r,e){let t=r.trim();if(!t)throw new Error(`[Transport] ${e} must not be empty.`);let i;try{i=new URL(t)}catch{throw new Error(`[Transport] ${e} must be an absolute HTTP(S) URL.`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`[Transport] ${e} must use HTTP or HTTPS.`);return t}function Cu(r){if(!r)return{};let e={};for(let[t,i]of Object.entries(r)){let n=t.toLowerCase();n==="content-type"||n==="content-encoding"||(e[t]=i)}return e}function rs(r){let{senderConfig:e}=r;if(e.mode==="test"){let n=Ve.fromConfig(r.logger,e);return{sender:n,mode:"test",testSender:n,httpSender:null}}let t=e.mode==="internal"?es(e,r.timeoutMs):ts(e,r.batchConfig,r.timeoutMs),i=new Be(t,r.payloadBuilder,r.compression,r.logger);return{sender:i,mode:e.mode,testSender:null,httpSender:i}}var Ti=class{constructor(e,t){this.abortController=null;this.inner=e,this.timeoutMs=t.timeoutMs}async send(e,t){this.abortController?.abort(),this.abortController=new AbortController;let i=this.abortController,n=[i.signal,t?.signal].filter(Boolean),o=Eu(n),s=setTimeout(()=>i.abort(),this.timeoutMs);try{return await this.inner.send(e,{...t,signal:o})}finally{clearTimeout(s),this.abortController===i&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function Eu(r){if(r.length===0)return;if(r.length===1)return r[0];let e=new AbortController;for(let t of r){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Ii=class{constructor(e,t,i){this.active=!1;this.context=e;let n=e.config.transport;if(this.orderingManager=new er({enabled:n.ordering.enabled}),this.backpressureManager=new nr({enabled:n.backpressure.enabled,maxQueueSize:n.backpressure.maxQueueSize,policy:n.backpressure.policy,sampleRate:n.backpressure.sampleRate}),this.deadLetterManager=new Jt({enabled:n.deadLetter.enabled,maxEntries:n.deadLetter.maxEntries}),this.circuitBreaker=new or({enabled:n.circuitBreaker.enabled,failureThreshold:n.circuitBreaker.failureThreshold,resetTimeoutMs:n.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:n.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Zt({enabled:n.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(n.persistence.enabled){let p=vn(e.config);this.persistentQueue=new Si(p,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new Ci;this.pipeline=bi.createDefault(this.queue);let o=yn(n.compression),s=new xi(e),a=i?null:rs({senderConfig:n.sender,batchConfig:n.batch,timeoutMs:n.timeout.timeoutMs,payloadBuilder:s,compression:o,logger:e.logger});this.senderMode=i?"injected":a.mode,this.testSender=i instanceof Ve?i:a?.testSender??null,this.httpSender=i instanceof Be?i:a?.httpSender??null;let l=i??a.sender;n.circuitBreaker.enabled&&(l=new sr(this.circuitBreaker,l));let u=null;n.timeout.enabled&&(u=new Ti(l,{timeoutMs:n.timeout.timeoutMs}),l=u),this.timedSender=u,this.sender=l,this.persistentQueue?(this.replayManager=new ir({enabled:n.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null;let c=new mi,d=new hi({flushIntervalMs:n.flush.enabled?n.flush.flushIntervalMs:0,flushOnDestroy:n.flush.flushOnDestroy,prepareUnloadHooks:n.flush.enabled&&n.flush.prepareUnloadHooks}),m=new Ei({maxAttempts:n.retry.enabled?n.retry.maxAttempts:1,baseDelayMs:n.retry.baseDelayMs,maxDelayMs:n.retry.maxDelayMs,multiplier:n.retry.multiplier},e.logger),h=new gi;this.delivery=new pi({batchManager:c,flushManager:d,retryEngine:m,offlineDetector:h,sender:this.sender,config:{batch:{...n.batch},timeoutMs:n.timeout.timeoutMs},logger:e.logger,abortPending:()=>u?.abortPending(),onPermanentFailure:n.deadLetter.enabled?(p,f)=>{this.deadLetterManager.move(p,"max_retries_exceeded",n.retry.enabled?n.retry.maxAttempts:1,f instanceof Error?f.message:String(f))}:void 0})}async init(){this.active||(this.persistentQueue&&await this.persistentQueue.init(),this.coordinationManager.init(e=>{e&&(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}),this.delivery?.init(),this.replayManager&&await this.replayManager.replay("init"),this.active=!0,this.context.logger.debug("[TransportEngine] Initialized"))}destroy(){this.active&&(this.timedSender?.abortPending(),this.delivery?.destroy(),this.coordinationManager.destroy(),this.persistentQueue?this.persistentQueue.destroy():this.queue.clear(),this.testSender?.clear(),this.httpSender?.clear(),this.active=!1,this.context.logger.debug("[TransportEngine] Destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;if(!this.pipeline.process(e).event){this.context.logger.debug("[TransportEngine] Event dropped by pipeline");return}this.coordinationManager.shouldPersistOnly()||this.forwardQueuedEvents()}manualFlush(){this.delivery?.flush()}simulateOffline(e){this.delivery?.getOfflineDetector().simulateOffline(e),e||(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}configureTestSender(e){this.testSender?.configure(e)}async simulateReload(){await this.replayManager?.replay("reload"),this.forwardQueuedEvents()}async simulateRestart(){await this.replayManager?.replay("restart"),this.forwardQueuedEvents()}forceCircuitOpen(){this.circuitBreaker.forceOpen()}forceCircuitClose(){this.circuitBreaker.forceClose()}async manualReplay(){let e=await this.replayManager?.replay("manual")??0;return this.forwardQueuedEvents(),e}replayDeadLetter(){let e=this.deadLetterManager.replayAll();if(e.length>0){for(let t of e)this.queue.enqueue(t);this.forwardQueuedEvents()}return e}clearDeadLetter(){this.deadLetterManager.clear()}exportQueue(){return this.persistentQueue?JSON.stringify(this.persistentQueue.exportRecords(),null,2):JSON.stringify(this.queue.getAll(),null,2)}importQueue(e){let t=JSON.parse(e);if(this.persistentQueue&&Array.isArray(t)&&t[0]?.event)return this.persistentQueue.importRecords(t),t.length;if(Array.isArray(t)){this.queue.clear();for(let i of t)this.queue.enqueue(i);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.testSender?.getState()??null;return{queueSize:this.queue.size(),queueContents:this.queue.getAll(),pipelineSteps:this.pipeline.getLastSteps(),senderLogs:e?.logs??[],sentCount:e?.sentCount??0,delivery:this.delivery?.getDebugState()??null,sender:e,advanced:{storage:{adapter:this.persistentQueue?.getStorageAdapterName()??"MemoryQueue",persistenceEnabled:this.persistentQueue!==null,recordCount:this.persistentQueue?.getRecords().length??this.queue.size()},replay:this.replayManager?.getDebugState()??{enabled:!1,lastTrigger:null,lastReplayAt:null,totalReplayed:0,pendingCount:0},ordering:this.orderingManager.getDebugState(this.queue.size()),coordination:this.coordinationManager.getDebugState(),circuitBreaker:this.circuitBreaker.getMetrics(),backpressure:this.backpressureManager.getDebugState(this.queue.size()),deadLetter:this.deadLetterManager.getDebugState(),compression:Go(this.context.config.transport.compression,yn(this.context.config.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let t=this.queue.dequeue();t&&e.push(t)}e.length!==0&&this.delivery.ingest(e)}};var ar=class{constructor(){this.name="transport";this.engine=null;this.subscriber=null;this.active=!1}async init(e){if(this.active){e.logger.debug("[Pixel] Transport module already initialized");return}if(!e.config.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Ii(e),await this.engine.init(),this.subscriber=new di(e.services.dispatcher,t=>this.engine?.handleEvent(t)),this.subscriber.subscribe(),this.active=!0}async destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}manualFlush(){this.engine?.manualFlush()}simulateOffline(e){this.engine?.simulateOffline(e)}configureTestSender(e){this.engine?.configureTestSender(e)}simulateReload(){return this.engine?.simulateReload()??Promise.resolve()}simulateRestart(){return this.engine?.simulateRestart()??Promise.resolve()}forceCircuitOpen(){this.engine?.forceCircuitOpen()}forceCircuitClose(){this.engine?.forceCircuitClose()}manualReplay(){return this.engine?.manualReplay()??Promise.resolve(0)}replayDeadLetter(){return this.engine?.replayDeadLetter()??[]}clearDeadLetter(){this.engine?.clearDeadLetter()}exportQueue(){return this.engine?.exportQueue()??"[]"}importQueue(e){return this.engine?.importQueue(e)??0}};var lr=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var ur=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[i,n]of Object.entries(e)){if(typeof n!="string")continue;let o=n.trim();o&&(t[i]=o)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return ce(this.snapshot)?bn(this.snapshot):null}clear(){this.snapshot={}}};var xu=200,cr=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new H}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},xu)}};var dr=class{constructor(e,t,i,n){this.metadataService=e,this.attribution=t??null,this.urlContext=i??null,this.customerIdentity=n??null}build(e){let t=this.metadataService.getMetadata(),i=this.attribution?.getSnapshot(),n=i!==void 0&&Object.keys(i).some(d=>{let m=i[d];return m!=null&&m!==""}),o=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=o!==null&&Object.keys(o.queryParams).length>0,a=o!==null&&(o.urlContext.managed&&Object.keys(o.urlContext.managed).length>0||o.urlContext.forwarded&&Object.keys(o.urlContext.forwarded).length>0||o.urlContext.source&&Object.keys(o.urlContext.source).length>0),l=this.customerIdentity?.getSnapshot()??null,c=e.customer??l;return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...n?{identifiers:i}:{},...s?{queryParams:{...o.queryParams}}:{},...a?{urlContext:{...o.urlContext.managed?{managed:{...o.urlContext.managed}}:{},...o.urlContext.forwarded?{forwarded:{...o.urlContext.forwarded}}:{},...o.urlContext.source?{source:{...o.urlContext.source}}:{}}}:{},...ce(c)?{customer:{...c}}:{}}}};var mr=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var pr={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},Cn="attribution";var Tu=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],hr=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),i={},n={};for(let o of Tu){let s=t.get(o);s&&(o==="li_fat_id"?i.liFatId=s:i[o]=s)}for(let o of e){let s=t.get(o);s&&(n[o]=s)}return Object.keys(n).length>0&&(i.customClickIds=n),i}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var gr=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},i={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,o]of Object.entries(i)){let s=e[n];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[i,...n]=t.trim().split("=");return i&&(e[i]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var fr=class{constructor(e={}){this.clickIdParser=new hr;this.cookieCollector=new gr;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},i={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(i.customClickIds=n),typeof i.fbclid=="string"&&i.fbclid){let o=this.clickIdParser.synthesizeFbc(i.fbclid,typeof i.fbc=="string"?i.fbc:void 0);o&&(i.fbc=o)}if(typeof window<"u")try{i.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(i.referrer=document.referrer)}catch{}return i}merge(e,t){let i={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){i.customClickIds={...e.customClickIds??{},...s};continue}i[o]=s}let n=Date.now();return e.firstCollectedAt||(i.firstCollectedAt=n),i.lastCollectedAt=n,i}};var yr=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??Cn}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var vr=class{constructor(e,t=pr){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new yr(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new fr({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var Ai=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var Di=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let i=0;i<t.length;i+=1){let n=t[i];if(n)try{n(e)}catch(o){this.logger?.warn(Iu(o,e.type,i))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function Iu(r,e,t){let i=r instanceof Error?r.name:typeof r=="object"&&r!==null&&"name"in r?String(r.name):"Error",n=r instanceof Error?r.message:typeof r=="string"?r:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:i,message:n,timestamp:Date.now()}}var Au="fingerprint";function Du(r){let e=0;for(let n=0;n<r.length;n++)e=(e<<5)-e+r.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),i=0;for(let n=r.length-1;n>=0;n--)i=(i<<5)-i+r.charCodeAt(n),i|=0;return`fp_${t}${Math.abs(i).toString(16).padStart(8,"0")}`}function ku(r){let e=r.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Du(t.join("|"))}var ki=class{constructor(e,t,i){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Au,this.metadataService=i}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=ku(this.metadataService);return this.storage.set(this.storageKey,t),t}};var Ee=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let i=0;i<this.storage.length;i++){let n=this.storage.key(i);n&&e(n)&&t.push(n)}for(let i of t)this.storage.removeItem(i);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var Y=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function wu(r){return"removeKeysMatching"in r&&typeof r.removeKeysMatching=="function"}var br=class{constructor(e,t,i){this.adapter=e,this.namespace=t,this.prefix=i}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(wu(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function En(r){let e=r??"memory";if(typeof window>"u")return new Y;switch(e){case"memory":return new Y;case"localStorage":return new Ee(window.localStorage);case"sessionStorage":return new Ee(window.sessionStorage);case"cookie_localStorage":return new Ee(window.localStorage);case"cookie":return new Y;case"indexedDB":return new Y;default:return new Y}}function xn(r){switch(r??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function Ru(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function wi(){return`ses_${Ru()}`}var Mu="session",Ri=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Mu}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),i=Date.now();if(!t){let n=wi();return this.writeSessionData({sessionId:n,lastActivityAt:i,createdAt:i}),{sessionId:n,expired:!1,created:!0}}if(i-t.lastActivityAt>e){let n=t.sessionId,o=wi();return this.writeSessionData({sessionId:o,lastActivityAt:i,createdAt:i}),{sessionId:o,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=wi();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Pu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function is(){return`vst_${Pu()}`}var _u="visitor",Mi=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??_u}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=is();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Tn=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],In=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],An=["[data-no-url-context]","[download]"],ns="[data-no-sid]";function X(r){return r.trim().toLowerCase()}function Sr(r){try{return decodeURIComponent(r)}catch{return r}}function Cr(r,e){let t=new Set;if(e!==!1)for(let i of Tn)t.add(X(i));for(let i of r??[])typeof i=="string"&&i.trim()&&t.add(X(i));return t}function Dn(r,e){let t=[];e!==!1&&t.push(...In);for(let i of r??[])typeof i=="string"&&i.trim()&&t.push(i.trim().toLowerCase());return Array.from(new Set(t.map(i=>i.toLowerCase())))}function kn(r,e,t){let i=[];e!==!1&&i.push(...An),t&&i.push(ns);for(let n of r??[])typeof n=="string"&&n.trim()&&i.push(n.trim());return Array.from(new Set(i))}function Pi(r,e){return e.has(X(r))}function os(r,e){let i=r.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return i===n||i.endsWith(`.${n}`)}function wn(r,e,t){if(!r)return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local");for(let i of t)if(os(r,i))return!1;return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local"?!1:os(r,i))}function Rn(r="sid"){let e=(r||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),i=Math.random().toString(36).slice(2,10);return`${e}_${t}_${i}`}function A(){return typeof window<"u"&&typeof document<"u"}function Mn(r){if(A())try{History.prototype.replaceState.call(history,history.state,document.title,r)}catch{}}function Z(r){let e={};if(!r||r==="?")return e;let t=r.startsWith("?")?r.slice(1):r;if(!t)return e;for(let i of t.split("&")){if(!i)continue;let n=i.indexOf("="),o=Sr((n>=0?i.slice(0,n):i).replace(/\+/g," ")).trim();if(!o)continue;let s=n>=0?Sr(i.slice(n+1).replace(/\+/g," ")):"";e[o]=s}return e}function Er(r){let e=[];for(let[t,i]of Object.entries(r))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(i??"")}`);return e.length>0?`?${e.join("&")}`:""}function D(r){return Object.freeze({...r})}function Pn(r,e){let t=r.trim(),i=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${i}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${i}${n}`:t.startsWith("#")?`${i}${n}`:`${t.split(/[?#]/)[0]??t}${i}${n}`}var xr=class{collect(e){if(!e||e.enabled===!1)return{};if(!A())return{};let t=Z(window.location.search),i=Cr(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",o=new Set((e.allowlist??[]).map(X).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))Pi(a,i)||n==="allowlist"&&!o.has(X(a))||l!==""&&(s[a]=l);return s}};var Tr=class{constructor(e){this.store=e}resolve(e){let t={},i={},n={},o={},s=A()?Z(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let u=a.mode??"read_write",c=u==="read_only"||u==="read_write",d=u==="write_only"||u==="read_write",m=null,h=null;if(c){let p=s[l];p&&p.length>0&&(m=p,h="url")}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(p);f&&(m=f,h="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.storageKey?.trim()||l,f=this.store.getStorage(p);f&&(m=f,h="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Rn(a.generator.prefix??l),h="generated"),!(!m||!h)&&(t[l]=m,i[l]=h,a.decorateLinks!==!1&&(n[l]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&A()&&s[l]!==m&&(o[l]=m))}return Object.keys(o).length>0&&A()&&this.writeToUrl(o),{values:t,sources:i,decorateParams:n}}applyExternalValue(e,t){let i=t.trim();i&&(e.persistence?.enabled!==!1&&this.persist(e,i),(e.writeStrategy??"replaceState")==="replaceState"&&A()&&this.writeToUrl({[e.param]:i}))}persist(e,t){let i=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(i==="storage"||i==="localStorage_cookie")&&this.store.setStorage(n,t),(i==="cookie"||i==="localStorage_cookie")&&o?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:o?.path??"/",domain:o?.domain??"auto",sameSite:o?.sameSite??"Lax",secure:o?.secure??!0,maxAgeMs:o?.maxAgeMs})}writeToUrl(e){let i={...Z(window.location.search),...e},n=Er(i),o=window.location.hash??"",s=window.location.pathname+n+o;Mn(s)}};var Ir=class{resolve(e){let{queryParams:t,managedValues:i,config:n}=e;if(!n||n.enabled===!1)return{};let o=Cr(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(X).filter(Boolean)),l={};for(let[u,c]of Object.entries(t))c&&(Pi(u,o)||u in i||s==="allowlist"&&!a.has(X(u))||(l[u]=c));return l}};var Lu=["mailto:","tel:","javascript:","data:","blob:"],Ue=class{constructor(e,t,i){this.clickHandler=null;this.started=!1;if(Ou(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=Dn(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=kn(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let n=e,o=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...n}),this.config=o,this.excludedDomains=Dn(o.excludedDomains,o.mergeDefaultExcludedDomains),this.excludeSelectors=kn(o.excludeSelectors,o.mergeDefaultExcludeSelectors,i===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!A()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!A()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let i=Fu(t.target);i&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let i=e.trim(),n=i.toLowerCase();for(let p of Lu)if(n.startsWith(p))return p==="mailto:"&&this.config.decorateMailto===!0||p==="tel:"&&this.config.decorateTel===!0,null;if(i.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let p=A()?window.location.href:`https://${t??"example.com"}/`;o=new URL(i,p)}catch{return null}if(!wn(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=Z(o.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,u={...s},c=!1;for(let[p,f]of Object.entries(this.forwardedParams))p in u&&a&&!l||(u[p]!==f&&(c=!0),u[p]=f);for(let[p,f]of Object.entries(this.managedParams))u[p]!==f&&(c=!0),u[p]=f;let d=Z(i.includes("?")?i.slice(i.indexOf("?")).split("#")[0]??"":""),m=Nu(i)>Object.keys(d).length;if(!c&&!m)return i;let h=Er(u);return o.search=h.startsWith("?")?h.slice(1):h,Pn(i,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let i of t)i instanceof HTMLAnchorElement&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let i=this.decorateHref(t);i!=null&&i!==t&&e.setAttribute("href",i)}};function Ou(r){return typeof r=="object"&&r!==null&&"config"in r&&typeof r.config=="object"&&r.config!==null}function Fu(r){return r instanceof Element?r.closest("a[href]"):null}function Nu(r){let e=r.indexOf("?");if(e<0)return 0;let t=r.indexOf("#",e),i=t>=0?r.slice(e+1,t):r.slice(e+1);return i?i.split("&").filter(Boolean).length:0}var Ar=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!A())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let i of t){let n=i.indexOf("=");if((n>=0?i.slice(0,n):i).trim()!==e)continue;let s=n>=0?i.slice(n+1).trim():"";return Sr(s)}}catch{return null}return null}setCookie(e){if(!A())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let i=Bu(e.domain);i&&t.push(`domain=${i}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let n=e.sameSite??"Lax";t.push(`SameSite=${n}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Bu(r){if(!r||r==="auto"){if(!A())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return r}var as={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},Uu={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},zu={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},qu={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function _i(r){if(!r||r.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=r.managedParams!==void 0?r.managedParams.map(ss):[ss(as)];return{enabled:!0,queryParams:{...Uu,...r.queryParams,...r.queryParams?.allowlist?{allowlist:[...r.queryParams.allowlist]}:{},...r.queryParams?.denylist?{denylist:[...r.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...zu,...r.forwardParams,...r.forwardParams?.allowlist?{allowlist:[...r.forwardParams.allowlist]}:{},...r.forwardParams?.denylist?{denylist:[...r.forwardParams.denylist]}:{}},linkDecoration:{...qu,...r.linkDecoration,...r.linkDecoration?.allowedDomains&&r.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...r.linkDecoration.allowedDomains]}:{},...r.linkDecoration?.excludedDomains?{excludedDomains:[...r.linkDecoration.excludedDomains]}:{},...r.linkDecoration?.excludeSelectors?{excludeSelectors:[...r.linkDecoration.excludeSelectors]}:{}}}}function ss(r){return{...r,...r.generator?{generator:{...r.generator}}:{},...r.persistence?{persistence:{...r.persistence,...r.persistence.cookie?{cookie:{...r.persistence.cookie}}:{}}}:{}}}var ze=class{constructor(e,t){this.collector=new xr;this.forwardResolver=new Ir;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=_n();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=_i(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=_n();return}this.store=new Ar(this.storage),this.managedResolver=new Tr(this.store);let t=this.collector.collect(e.queryParams),i=this.managedResolver.resolve(e.managedParams),n=Object.keys(i.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:n,managedValues:i.values,config:e.forwardParams}),s={...i.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(i.values).length>0?{managed:D(i.values)}:{},...Object.keys(o).length>0?{forwarded:D(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:D(n),urlContext:Object.freeze(a)};let l=D(o);this.decorateManaged={...i.decorateParams};let u=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new Ue({forwardedParams:l,managedParams:D(this.decorateManaged),config:e.linkDecoration,includeSidExclude:u}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let i=e.trim(),n=t.trim();if(!i||!n)return!1;let o=this.managedConfigs.find(d=>d.param===i);if(!o)return!1;if(this.snapshot.urlContext.managed?.[i]===n)return!0;this.managedResolver.applyExternalValue(o,n);let a={...this.snapshot.urlContext.managed??{},[i]:n},l={...this.snapshot.urlContext.source??{},[i]:"manual"},u=_i(this.rawConfig),c=this.collector.collect(u.queryParams);if(this.snapshot={queryParams:D(c),urlContext:Object.freeze({managed:D(a),...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...l})})},o.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[i]:n},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&u.enabled)){let d=this.managedConfigs.some(m=>m.param==="sid"&&m.decorateLinks!==!1);this.decorator=new Ue({forwardedParams:D(this.snapshot.urlContext.forwarded??{}),managedParams:D(this.decorateManaged),config:u.linkDecoration,includeSidExclude:d}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=_n()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:D(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:D(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function _n(){return{queryParams:D({}),urlContext:Object.freeze({})}}var Dr=class{constructor(e){this.initialized=!1;this.customerObserver=null;this.initializedModules=[];this.context=null;this.config=e,this.registry=new lr,this.fallbackLogger=new mr(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init(),this.startCustomerObserver();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let i=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${i.name}`);try{await i.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${i.name}"`,n)}}this.customerObserver?.destroy(),this.customerObserver=null,this.context?.services.customerIdentity?.clear(),this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:i,persistence:n}=this.config.storage,o=this.createStorageService(t,i,n?.visitor),s=this.createStorageService(t,i,n?.session),a=this.createStorageService(t,i,n?.attribution),l=this.createStorageService(t,i,n?.attribution??"localStorage"),u=this.createStorageService(t,i,"memory"),c=new Ai,d=new vr(l,this.config.attribution??pr),m=this.createStorageService(t,i,n?.attribution??"localStorage"),h=new ze(this.config.modules.core.urlContext,m),p=new ur,f=new dr(c,d,h,p),b=new Mi(o,this.config),S=new Ri(s,this.config),O=new ki(a,this.config,c),He=new Di(e),Oi=new Me(this.config.commerce);return{storage:u,visitor:b,session:S,fingerprint:O,dispatcher:He,browserMetadata:c,eventBuilder:f,attribution:d,commerce:Oi,urlContext:h,customerIdentity:p}}startCustomerObserver(){let e=this.context?.services.customerIdentity;e&&(this.customerObserver=new cr(e,new H({fieldMappings:re(this.config.commerce.customer,this.config.commerce.mappings?.fields)})),this.customerObserver.start())}createStorageService(e,t,i){return new br(En(i),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Li="0.1.0-rc.13";var qe=class{constructor(e){let t=Ye(e);this.config=t,this.runtime=new Dr(t),this.conversionModule=new It,this.transportModule=new ar,this.integrationsModule=new Yt,this.behaviorModule=new vt,this.snapshotService=new Ze({getSdkVersion:()=>Li,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:t.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:t.transport.enabled===!0},{name:"integrations",configuredEnabled:t.modules.integrations.enabled===!0},{name:"core",configuredEnabled:t.modules.core.enabled===!0},{name:"behavior",configuredEnabled:t.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:t.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new Je(this.snapshotService),this.runtime.register(new Xt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new Mt),this.runtime.register(this.behaviorModule),this.runtime.register(this.conversionModule),this.runtime.register(this.diagnosticsModule)}init(){return this.snapshotService.markAlive(),this.runtime.init()}destroy(){return this.runtime.destroy().then(()=>{this.snapshotService.markDestroyed()})}isInitialized(){return this.runtime.isInitialized()}getDebugSnapshot(){return this.snapshotService.getSnapshot()}setManagedUrlParam(e,t){let i=this.runtime.getDebugServices();return i?.urlContext?i.urlContext.setManagedParam(e,t):!1}purchase(e){this.conversionModule.purchase(e)}lead(e){this.conversionModule.lead(e)}addToCart(e){this.conversionModule.addToCart(e)}removeFromCart(e){this.conversionModule.removeFromCart(e)}initiateCheckout(e){this.conversionModule.initiateCheckout(e)}addPaymentInfo(e){this.conversionModule.addPaymentInfo(e)}viewContent(e){this.conversionModule.viewContent(e)}search(e){this.conversionModule.search(e)}getDebugDedupeKeys(){return this.conversionModule.getDebugDedupeKeys()}getDebugActiveDetectors(){return this.conversionModule.getDebugActiveDetectors()}getDebugTransportState(){return this.transportModule.getDebugState()}flushTransport(){this.transportModule.manualFlush?.()}simulateTransportOffline(e){this.transportModule.simulateOffline?.(e)}configureTransportTestSender(e){this.transportModule.configureTestSender?.(e)}simulateTransportReload(){return this.transportModule.simulateReload()}simulateTransportRestart(){return this.transportModule.simulateRestart()}forceTransportCircuitOpen(){this.transportModule.forceCircuitOpen()}forceTransportCircuitClose(){this.transportModule.forceCircuitClose()}manualTransportReplay(){return this.transportModule.manualReplay()}replayTransportDeadLetter(){return this.transportModule.replayDeadLetter()}clearTransportDeadLetter(){this.transportModule.clearDeadLetter()}exportTransportQueue(){return this.transportModule.exportQueue()}importTransportQueue(e){return this.transportModule.importQueue(e)}getDebugIntegrationState(){return this.integrationsModule.getDebugState()}getDebugIntegrationMemoryRecords(){return this.integrationsModule.getMemoryRecords()}getDebugAttributionSnapshot(){return this.runtime.getDebugServices()?.attribution.getSnapshot()??null}collectAttribution(){return this.runtime.getDebugServices()?.attribution.collect()??null}clearAttribution(){this.runtime.getDebugServices()?.attribution.clear()}getDebugServices(){return this.runtime.getDebugServices()}evaluateEngagement(){this.behaviorModule.evaluateEngagementNow()}debugPublishBehaviorSignal(e,t){this.behaviorModule.debugPublishSignal(e,t)}flushBehaviorBuffer(){this.behaviorModule.flushBufferNow()}emitBehaviorSessionSummary(e){return this.behaviorModule.emitSessionSummaryNow(e)}};async function ls(r){let e=new qe(r);try{return await e.init(),e}catch(t){try{await e.destroy()}catch{}throw t}}0&&(module.exports={DEFAULT_PIXEL_CONFIG,Pixel,PixelConfigurationError,SDK_VERSION,createPixel,resolvePixelConfig,resolveStorageAdapterName});
|
|
2
|
+
"use strict";var qi=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var Bs=Object.getOwnPropertyNames;var Vs=Object.prototype.hasOwnProperty;var Us=(r,e)=>{for(var t in e)qi(r,t,{get:e[t],enumerable:!0})},zs=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Bs(e))!Vs.call(r,n)&&n!==t&&qi(r,n,{get:()=>e[n],enumerable:!(i=Ns(e,n))||i.enumerable});return r};var Hs=r=>zs(qi({},"__esModule",{value:!0}),r);var Yu={};Us(Yu,{DEFAULT_PIXEL_CONFIG:()=>je,Pixel:()=>qe,PixelConfigurationError:()=>F,SDK_VERSION:()=>Ui,createPixel:()=>xs,resolvePixelConfig:()=>Xe,resolveStorageAdapterName:()=>kn});module.exports=Hs(Yu);var $i=["email","phone","name","firstName","lastName","address","address2","city","state","postalCode","country"],Te={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},te={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...Te}};function Wn(r){return r?(Array.isArray(r)?r:[r]).map(t=>String(t).trim()).filter(Boolean):[]}function re(r,e){let t={};for(let i of $i){let n=[...Wn(r?.fields?.[i]),...Wn(e?.[i])];n.length>0&&(t[i]=n)}return t}function de(r){switch(r){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var Ki={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Wi={enabled:!1,heartbeat:{enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},engagement:{enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:{activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},penalties:{idle:.2,rageClick:.1},thresholds:{lowMax:29,mediumMax:69}},rateLimit:{enabled:!1,windowMs:1e3,maxSignalsPerWindow:50,criticalBypass:!0},buffer:{enabled:!1,maxSize:200,maxAgeMs:3e4,flushSize:50,dropStrategy:"compress_similar",flushOnHidden:!0},stateMachine:{enabled:!1,historyLimit:50},sessionSummary:{enabled:!1,emitOnHidden:!1,emitOnDestroy:!0,minimumSessionMs:0},trackers:{scroll:{enabled:!1,thresholds:[25,50,75,100],debounceMs:100},click:{enabled:!1,rageClick:{enabled:!0,threshold:3,windowMs:500}},idle:{enabled:!1,thresholdMs:6e4},visibility:{enabled:!1},exitIntent:{enabled:!1},viewport:{enabled:!1,targets:[],rootMargin:"0px",observeMutations:!0,mutationDebounceMs:100,maxObservedElements:500}}};function kr(r,e){return{name:e==="click"?r:`${r}:${e}`,type:"selector",selector:`[data-track="${r}"]`,selectorType:"css",trigger:e}}function me(r){return{enabled:!0,sources:[kr(r,"click")]}}var Gi={enabled:!0,manual:{pageView:{enabled:!0},purchase:{enabled:!0},lead:{enabled:!0},addToCart:{enabled:!0},removeFromCart:{enabled:!0},initiateCheckout:{enabled:!0},addPaymentInfo:{enabled:!0},search:{enabled:!0},viewContent:{enabled:!0}},auto:{enabled:!0,detectors:{lead:me("lead"),addToCart:me("add_to_cart"),removeFromCart:me("remove_from_cart"),initiateCheckout:me("initiate_checkout"),purchase:me("purchase"),addPaymentInfo:me("add_payment_info"),search:me("search"),viewContent:{enabled:!0,sources:[kr("view_content","click"),kr("view_content","hover"),kr("view_content","visible")]}}},rules:{enabled:!1,selectors:["[data-track]"],texts:["Comprar","Comprar Agora","Finalizar Compra","Checkout"],urlPatterns:["thank-you","purchase","success","order","checkout"],checkout:{enabled:!1},card:{enabled:!1}}};var Qi={enabled:!0,pageView:{enabled:!0,trackInitialPageView:!0,spa:!0,dedupeMs:2e3},visitor:{enabled:!0,persistence:"cookie_localStorage",renew:!1},session:{enabled:!0,ttlMs:108e5,renewOnActivity:!0,renewOnPageView:!0},fingerprint:{enabled:!0,mode:"light",cache:!0},consent:{enabled:!1,required:!1,waitForConsent:!1},dedupe:{enabled:!0,windowMs:2e3},coordination:{enabled:!0,leaderElection:!0,broadcastChannel:!0},ordering:{enabled:!0,preserveOrder:!0},urlContext:{enabled:!1}};var ji={enabled:!1,debug:!1,concurrency:3,timeoutMs:5e3,continueOnError:!0,destinations:{console:{enabled:!1},memory:{enabled:!1},mock:{enabled:!1},meta:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0},google:{enabled:!1,tagIds:[],autoPageView:!0,loadScript:!0},tiktok:{enabled:!1,pixelIds:[],autoPageView:!0,loadScript:!0}}};var Yi={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var Rr="https://micro-service-pixel-production-4826.up.railway.app",T={enabled:!0,sender:{mode:"internal",baseUrl:Rr},persistence:{enabled:!0},replay:{enabled:!0},ordering:{enabled:!0},coordination:{enabled:!0},circuitBreaker:{enabled:!0,failureThreshold:5,resetTimeoutMs:3e4,halfOpenMaxAttempts:2},backpressure:{enabled:!0,maxQueueSize:500,policy:"drop_oldest",sampleRate:.5},deadLetter:{enabled:!0,maxEntries:200},compression:{enabled:!0,strategy:"identity"},retry:{enabled:!0,maxAttempts:4,baseDelayMs:500,maxDelayMs:4e3,multiplier:2},batch:{enabled:!0,batchSize:10,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var je={app:{source:"custom",target:"custom",platform:"",environment:"production",debug:!1},identity:{pixelId:""},transport:{...T,sender:{...T.sender},persistence:{...T.persistence},replay:{...T.replay},ordering:{...T.ordering},coordination:{...T.coordination},circuitBreaker:{...T.circuitBreaker},backpressure:{...T.backpressure},deadLetter:{...T.deadLetter},compression:{...T.compression},retry:{...T.retry},batch:{...T.batch},timeout:{...T.timeout},offline:{...T.offline},flush:{...T.flush}},storage:{prefix:"__gmk",namespace:"pixel",persistence:{visitor:"localStorage",session:"sessionStorage",attribution:"localStorage"},queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{...Ki},commerce:{...te,catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...te.enrichment}},modules:{core:Qi,behavior:Wi,conversion:Gi,integrations:ji,privacy:Yi}};var F=class extends Error{constructor(e,t,i){super(e),this.name="PixelConfigurationError",this.code=t,i!==void 0&&(this.cause=i)}};var Xi=128;function Ks(r){for(let e=0;e<r.length;e+=1){let t=r.charCodeAt(e);if(t<=31||t>=127&&t<=159)return!0}return!1}function Zi(r){if(typeof r!="string")throw new F("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");let e=r.trim();if(e.length===0)throw new F("identity.pixelId must be a non-empty string.","INVALID_PIXEL_ID");if(e.length>Xi)throw new F(`identity.pixelId exceeds the maximum length of ${Xi} characters.`,"INVALID_PIXEL_ID");if(Ks(e))throw new F("identity.pixelId must not contain control characters.","INVALID_PIXEL_ID");return e}var Gn=new Set(["__proto__","prototype","constructor"]);function Ye(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Ie(r){if(Array.isArray(r))return r.map(e=>Ie(e));if(Ye(r)){let e={};for(let t of Object.keys(r))Gn.has(t)||(e[t]=Ie(r[t]));return e}return r}function Qn(r,e,t){if(e===void 0)return r;if(Array.isArray(e))return Ie(e);if(typeof e=="function"||!Ye(e))return e;let i=Ye(r)?Ie(r):{};for(let n of Object.keys(e)){if(Gn.has(n))continue;let o=e[n];if(o===void 0)continue;let s=t?`${t}.${n}`:n;if(s==="transport.sender"){i[n]=Ie(o);continue}i[n]=Qn(i[n],o,s)}return i}function Xe(r){if(!Ye(r))throw new F("Pixel settings must be a plain object.","INVALID_SETTINGS");let e=Qn(Ie(je),r,""),t=Ye(r.identity)?r.identity.pixelId:void 0;return e.identity={...e.identity,pixelId:Zi(t)},e}var Ws=/^(password|pass|secret|token|access[_-]?token|refresh[_-]?token|authorization|auth|cookie|set[_-]?cookie|cvv|cvc|pan|card[_-]?number|security[_-]?code|private[_-]?key|client[_-]?secret|api[_-]?key)$/i,Yn=/^(e[_-]?mail|user[_-]?email|customer[_-]?email|emailAddress)$/i,Xn=/^(phone|telefone|mobile|cell|tel|user[_-]?phone|phoneNumber)$/i,Zn=/^(name|full[_-]?name|first[_-]?name|last[_-]?name|customer[_-]?name|display[_-]?name)$/i,Jn=/^(address|addr|street|billing[_-]?address|shipping[_-]?address)$/i,Gs=/(password|passwd|secret|token|authorization|cookie|cvv|cvc|cardnumber|privatekey|apikey|clientsecret|accesstoken|refreshtoken)/i;function eo(r){let e=r.indexOf("@");return e<=1?"***":`${r[0]}***${r.slice(e)}`}function to(r){let e=r.replace(/\D/g,"");return e.length<4?"***":`***${e.slice(-4)}`}function ro(r){let e=r.trim();return e.length<=1?"*":`${e[0]}***`}function Qs(r){return r.trim().toLowerCase().replace(/[-_\s]/g,"")}function Ji(r){let e=r.trim();if(!e)return!1;if(Ws.test(e)||Yn.test(e)||Xn.test(e)||Zn.test(e)||Jn.test(e))return!0;let t=Qs(e);return!!Gs.test(t)}function jn(r,e){return typeof e!="string"?"[Redacted]":Yn.test(r)||/email/i.test(r)?eo(e):Xn.test(r)||/phone|telefone|tel/i.test(r)?to(e):Zn.test(r)?ro(e):(Jn.test(r),"[Redacted]")}function io(r){try{return structuredClone(r)}catch{try{return JSON.parse(JSON.stringify(r))}catch{return r}}}function Ze(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;if(r instanceof Map){for(let[,e]of r)e&&typeof e=="object"&&Ze(e);return Object.freeze(r)}if(r instanceof Set){for(let e of r)e&&typeof e=="object"&&Ze(e);return Object.freeze(r)}for(let e of Reflect.ownKeys(r)){let t=r[e];t&&typeof t=="object"&&Ze(t)}return Object.freeze(r)}function Ae(r,e=0){if(e>8)return"[Truncated:max_depth]";if(typeof r=="string")return r.length>512?`${r.slice(0,512)}\u2026[truncated]`:r;if(Array.isArray(r)){let t=r.slice(0,100).map(i=>Ae(i,e+1));return r.length>100&&t.push(`[Truncated:${r.length-100}_more]`),t}if(r instanceof Map){let t={},i=0;for(let[n,o]of r){if(i++>=100){t.__truncated__=!0;break}t[String(n)]=Ae(o,e+1)}return t}if(r instanceof Set)return Ae([...r],e);if(r&&typeof r=="object"){let t={};for(let[i,n]of Object.entries(r))t[i]=Ae(n,e+1);return t}return r}function pe(r,e=new WeakSet){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="bigint")return String(r);if(typeof r=="function"||typeof r=="symbol")return"[Unavailable]";if(typeof r!="object")return String(r);if(e.has(r))return"[Circular]";if(e.add(r),Array.isArray(r))return r.map(i=>pe(i,e));if(r instanceof Map){let i={};for(let[n,o]of r){let s=String(n);i[s]=Ji(s)?jn(s,o):pe(o,e)}return i}if(r instanceof Set)return[...r].map(i=>pe(i,e));let t={};for(let[i,n]of Object.entries(r)){if(Ji(i)){t[i]=jn(i,n);continue}t[i]=pe(n,e)}return t}function en(r){return pe(r)}function tn(r){let e=io(r),t=pe(e),i=Ae(t);return Ze(i)}function rn(r){let e=[],t=[],i=(u,c,d)=>{e.push({id:u,status:c,...d?{detail:d}:{}}),(c==="degraded"||c==="unhealthy")&&t.push(d?`${u}: ${d}`:u)};if(r.runtimeInitialized?r.runtimeDestroyed?i("runtime","unknown","Runtime destroyed"):i("runtime","healthy"):i("runtime","unknown","Runtime not initialized"),!r.transport.enabled)i("transport","healthy","Transport disabled by config");else if(!r.transport.state)i("transport","unknown","Transport state unavailable");else{let u=r.transport.state;u.circuitBreakerState==="open"?i("circuitBreaker","unhealthy","Circuit breaker open"):u.circuitBreakerState==="half_open"?i("circuitBreaker","degraded","Circuit breaker half-open"):i("circuitBreaker","healthy"),u.online===!1?i("offline","degraded","Client offline"):u.online===!0?i("offline","healthy"):i("offline","unknown"),typeof u.dlqCount=="number"&&u.dlqCount>0?i("dlq","degraded",`DLQ has ${u.dlqCount} entries`):i("dlq","healthy")}r.integrations.enabled&&r.integrations.active===!1?i("integrations","degraded","Integrations enabled but inactive"):i("integrations","healthy"),r.behaviorViewport?.enabled===!0&&r.behaviorViewport.available===!1&&i("behaviorViewport","degraded","BEHAVIOR_VIEWPORT_UNAVAILABLE: IntersectionObserver not available");let n=r.behaviorEngagement;if(n?.enabled===!0&&n.running===!0){let u=n.evaluationIntervalMs,c=n.lastDriftMs;n.hasError?i("behaviorEngagement","degraded","BEHAVIOR_ENGAGEMENT_CALC_ERROR: score calculation failed"):typeof c=="number"&&u>0&&c>u&&i("behaviorEngagement","degraded",`BEHAVIOR_ENGAGEMENT_DRIFT: scheduler drift ${c}ms`)}let o=r.behaviorRateLimit;if(o?.enabled===!0){let u=o.accepted+o.dropped;(u>0?o.dropped/u:0)>=.5&&o.dropped>0&&i("behaviorRateLimit","degraded",`BEHAVIOR_RATE_LIMIT_HIGH_DROP: ${o.dropped}/${u} dropped`)}let s=r.behaviorBuffer;s?.enabled===!0&&s.maxSize>0&&s.size>=s.maxSize&&i("behaviorBuffer","degraded","BEHAVIOR_BUFFER_FULL: buffer reached maxSize");let a=r.behaviorStateMachine;a?.enabled===!0&&a.invalidTransitionCount>0&&i("behaviorStateMachine","degraded",`BEHAVIOR_STATE_INVALID_TRANSITIONS: ${a.invalidTransitionCount}`);let l="healthy";return e.some(u=>u.status==="unhealthy")?l="unhealthy":e.some(u=>u.status==="degraded")?l="degraded":(e.every(u=>u.status==="unknown")||e.some(u=>u.status==="unknown")&&!r.runtimeInitialized)&&(l="unknown"),{status:l,checks:e,reasons:t}}function nn(r){let e=r.services,t=r.transport.state,i={sdkVersion:r.sdkVersion,capturedAt:Date.now(),runtime:{initialized:r.runtimeInitialized,destroyed:r.runtimeDestroyed,moduleCount:r.moduleRegistry.length,activeModuleCount:r.moduleRegistry.filter(n=>n.initialized).length,moduleNames:r.moduleRegistry.map(n=>n.name),activeModuleNames:r.moduleRegistry.filter(n=>n.initialized).map(n=>n.name)},modules:r.moduleRegistry.map(n=>({id:n.name,configuredEnabled:n.configuredEnabled,initialized:n.initialized})),core:{enabled:r.moduleRegistry.some(n=>n.name==="core"&&n.configuredEnabled),visitorId:e?.visitorId??null,sessionId:e?.sessionId??null,sessionExpired:e?.sessionExpired??null,fingerprint:e?.fingerprint??null,urlContextEnabled:e?.urlContextEnabled??!1},urlContext:e?.urlContextSnapshot?{enabled:e.urlContextEnabled,available:!0,managedKeys:Object.keys(e.urlContextSnapshot.managed),forwardedKeys:Object.keys(e.urlContextSnapshot.forwarded),source:{...e.urlContextSnapshot.source},queryParamCount:e.urlContextSnapshot.queryParamCount}:{enabled:!1,available:!1,managedKeys:[],forwardedKeys:[],source:{},queryParamCount:0},attribution:{enabled:e?.attributionEnabled??!1,available:e?.attributionIdentifiers!=null,identifierKeys:e?.attributionIdentifiers?Object.keys(e.attributionIdentifiers):[],identifiers:e?.attributionIdentifiers?{...e.attributionIdentifiers}:{}},commerce:{enabled:e?.commerceEnabled??!1,available:e!=null,mode:e?.commerceMode??null,currency:e?.commerceCurrency??null,catalogSize:e?.catalogSize??0,itemCount:e?.itemCount??0,cartValue:e?.cartValue??null,productIds:e?.productIds??[]},behavior:{enabled:r.behaviorEnabled,configuredTrackers:[...r.behaviorTrackers],configuredEngines:[...r.behaviorEngines],heartbeat:r.behaviorHeartbeat?{enabled:r.behaviorHeartbeat.enabled,initialized:r.behaviorHeartbeat.initialized,running:r.behaviorHeartbeat.running,intervalMs:r.behaviorHeartbeat.intervalMs,hiddenIntervalMs:r.behaviorHeartbeat.hiddenIntervalMs,sequence:r.behaviorHeartbeat.sequence,emittedCount:r.behaviorHeartbeat.emittedCount,skippedCount:r.behaviorHeartbeat.skippedCount,lastEmittedAt:r.behaviorHeartbeat.lastEmittedAt,nextExpectedAt:r.behaviorHeartbeat.nextExpectedAt,lastDriftMs:r.behaviorHeartbeat.lastDriftMs}:null,viewport:r.behaviorViewport?{enabled:r.behaviorViewport.enabled,initialized:r.behaviorViewport.initialized,available:r.behaviorViewport.available,targetCount:r.behaviorViewport.targetCount,matchedElementCount:r.behaviorViewport.matchedElementCount,observedElementCount:r.behaviorViewport.observedElementCount,activeElementCount:r.behaviorViewport.activeElementCount,pendingElementCount:r.behaviorViewport.pendingElementCount,enterCount:r.behaviorViewport.enterCount,exitCount:r.behaviorViewport.exitCount,mutationObserverEnabled:r.behaviorViewport.mutationObserverEnabled,maxObservedElements:r.behaviorViewport.maxObservedElements,limitReached:r.behaviorViewport.limitReached,lastEventAt:r.behaviorViewport.lastEventAt}:null,engagement:r.behaviorEngagement?{enabled:r.behaviorEngagement.enabled,initialized:r.behaviorEngagement.initialized,running:r.behaviorEngagement.running,score:r.behaviorEngagement.score,previousScore:r.behaviorEngagement.previousScore,peakScore:r.behaviorEngagement.peakScore,averageScore:r.behaviorEngagement.averageScore,level:r.behaviorEngagement.level,evaluationCount:r.behaviorEngagement.evaluationCount,emittedUpdateCount:r.behaviorEngagement.emittedUpdateCount,emittedSummaryCount:r.behaviorEngagement.emittedSummaryCount,lastEvaluatedAt:r.behaviorEngagement.lastEvaluatedAt,lastEmittedAt:r.behaviorEngagement.lastEmittedAt,evaluationIntervalMs:r.behaviorEngagement.evaluationIntervalMs,lastDriftMs:r.behaviorEngagement.lastDriftMs,hasError:r.behaviorEngagement.hasError,signalCounts:{...r.behaviorEngagement.signalCounts}}:null,rateLimit:r.behaviorRateLimit?{...r.behaviorRateLimit}:null,buffer:r.behaviorBuffer?{...r.behaviorBuffer}:null,stateMachine:r.behaviorStateMachine?{...r.behaviorStateMachine}:null,sessionSummary:r.behaviorSessionSummary?{...r.behaviorSessionSummary}:null},conversion:{enabled:r.conversion.enabled,autoEnabled:r.conversion.autoEnabled,manualEnabledFlags:{...r.conversion.manualEnabledFlags},detectorCount:r.conversion.detectorCount,activeDetectors:[...r.conversion.activeDetectors],dedupeKeyCount:r.conversion.dedupeKeyCount},integrations:{enabled:r.integrations.enabled,available:!0,active:r.integrations.active,destinationNames:[...r.integrations.destinationNames],metrics:r.integrations.metrics?{...r.integrations.metrics}:null},transport:t?{enabled:r.transport.enabled,available:!0,online:t.online,senderMode:t.senderMode,queueSize:t.queueSize,sentCount:t.sentCount,ackCount:t.ackCount,inFlight:t.inFlight,retryPending:t.retryPending,circuitBreakerState:t.circuitBreakerState,dlqCount:t.dlqCount,isLeader:t.isLeader,persistenceEnabled:t.persistenceEnabled}:{enabled:r.transport.enabled,available:!1,online:"unknown",senderMode:r.transport.enabled?"unavailable":"unknown",queueSize:"unavailable",sentCount:"unavailable",ackCount:"unavailable",inFlight:"unavailable",retryPending:"unavailable",circuitBreakerState:"unavailable",dlqCount:"unavailable",isLeader:"unavailable",persistenceEnabled:"unavailable"},health:rn(r),warnings:js(r),errors:[],config:r.configSafe};return tn(i)}function js(r){let e=[];return r.runtimeInitialized||e.push({code:"RUNTIME_NOT_INITIALIZED",message:"Snapshot captured before init()",source:"runtime"}),r.runtimeDestroyed&&e.push({code:"RUNTIME_DESTROYED",message:"Snapshot captured after destroy()",source:"runtime"}),r.transport.enabled&&!r.transport.state&&e.push({code:"TRANSPORT_STATE_UNAVAILABLE",message:"Transport enabled but debug state unavailable",source:"transport"}),e}var Je=class{constructor(e){this.destroyed=!1;this.deps=e}markDestroyed(){this.destroyed=!0}markAlive(){this.destroyed=!1}getSnapshot(){return nn(this.collect())}collect(){let e=this.deps.getRuntime(),t=this.deps.getConfig(),i=e.getDebugServices(),n=this.deps.getTransportModule(),o=this.deps.getConversionModule(),s=this.deps.getIntegrationsModule(),a=n.getDebugState(),l=this.deps.getRegisteredModules(),u=new Set(e.getInitializedModuleNames()),c=l.map(P=>({name:P.name,configuredEnabled:P.configuredEnabled,initialized:u.has(P.name)})),d=null;if(i){let P=i.urlContext.isEnabled()?i.urlContext.getSnapshot():null,zn=i.commerce.state.getSnapshot(),Hn=i.commerce.catalog.list(),qn=zn.selectedItems??[],$n=0;for(let ee of qn){let Qe=typeof ee.price=="number"?ee.price:void 0,Os=Hn.find(Fs=>Fs.id===ee.productId)?.price;$n+=(Qe??Os??0)*(ee.quantity??1)}let _s=i.attribution.getSnapshot(),Kn={};for(let[ee,Qe]of Object.entries(_s))typeof Qe=="string"&&Qe.length>0&&(Kn[ee]=Qe);let Ls=t.modules.core.session.ttlMs;d={visitorId:i.visitor.getVisitorId(),sessionId:i.session.getSessionId(),sessionExpired:i.session.isExpired(Ls),fingerprint:i.fingerprint.getFingerprint(),urlContextEnabled:i.urlContext.isEnabled(),urlContextSnapshot:P?{managed:{...P.urlContext.managed??{}},forwarded:{...P.urlContext.forwarded??{}},source:{...P.urlContext.source??{}},queryParamCount:Object.keys(P.queryParams).length}:null,attributionEnabled:t.attribution?.enabled!==!1,attributionIdentifiers:Kn,commerceEnabled:i.commerce.isEnabled(),commerceMode:t.commerce?.cart?.mode??null,commerceCurrency:t.commerce?.currency??null,catalogSize:Hn.length,itemCount:zn.count,cartValue:$n,productIds:qn.map(ee=>ee.productId).filter(Boolean)}}let m=t.modules.behavior.trackers,h=t.modules.behavior.heartbeat,p=t.modules.behavior.engagement,f=m?.viewport,b=[];m?.scroll?.enabled&&b.push("scroll"),m?.click?.enabled&&b.push("click"),m?.visibility?.enabled&&b.push("visibility"),m?.idle?.enabled&&b.push("idle"),m?.exitIntent?.enabled&&b.push("exitIntent"),f?.enabled===!0&&b.push("viewport");let S=[];h?.enabled===!0&&S.push("heartbeat"),p?.enabled===!0&&S.push("engagement"),t.modules.behavior.rateLimit?.enabled===!0&&S.push("rateLimit"),t.modules.behavior.buffer?.enabled===!0&&S.push("buffer"),t.modules.behavior.stateMachine?.enabled===!0&&S.push("stateMachine"),t.modules.behavior.sessionSummary?.enabled===!0&&S.push("sessionSummary");let O=this.deps.getBehaviorModule(),zi=O.getHeartbeatSnapshot()??null??(h?{enabled:h.enabled===!0,initialized:!1,running:!1,intervalMs:h.intervalMs??15e3,hiddenIntervalMs:h.hiddenIntervalMs??6e4,sequence:0,emittedCount:0,skippedCount:0,lastEmittedAt:void 0,nextExpectedAt:void 0,lastDriftMs:void 0}:null),Ts=O.getViewportSnapshot()??null??(f?{enabled:f.enabled===!0,initialized:!1,available:!1,targetCount:f.targets?.length??0,matchedElementCount:0,observedElementCount:0,activeElementCount:0,pendingElementCount:0,enterCount:0,exitCount:0,mutationObserverEnabled:!1,maxObservedElements:f.maxObservedElements??500,limitReached:!1,lastEventAt:void 0}:null),Is=O.getEngagementSnapshot()??null??(p?{enabled:p.enabled===!0,initialized:!1,running:!1,score:0,previousScore:0,peakScore:0,averageScore:0,level:"low",evaluationCount:0,emittedUpdateCount:0,emittedSummaryCount:0,lastEvaluatedAt:void 0,lastEmittedAt:void 0,evaluationIntervalMs:p.evaluationIntervalMs??5e3,lastDriftMs:void 0,hasError:!1,signalCounts:{HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0}}:null),Ke=t.modules.behavior.rateLimit,xe=t.modules.behavior.buffer,Un=t.modules.behavior.stateMachine,We=t.modules.behavior.sessionSummary,As=O.getRateLimitSnapshot()??(Ke?{enabled:Ke.enabled===!0,windowMs:Ke.windowMs??1e3,maxSignalsPerWindow:Ke.maxSignalsPerWindow??50,criticalBypass:Ke.criticalBypass!==!1,accepted:0,dropped:0,bypassed:0,windowCount:0,windowStartedAt:void 0}:null),Ds=O.getBufferSnapshot()??(xe?{enabled:xe.enabled===!0,size:0,maxSize:xe.maxSize??200,flushSize:xe.flushSize??50,maxAgeMs:xe.maxAgeMs??3e4,dropStrategy:xe.dropStrategy??"compress_similar",flushCount:0,dropCount:0,compressedCount:0,lastFlushAt:void 0,lastFlushReason:void 0}:null),ws=O.getStateMachineSnapshot()??(Un?{enabled:Un.enabled===!0,state:"NOT_INITIALIZED",previousState:void 0,generation:0,changedAt:void 0,transitionCount:0,invalidTransitionCount:0,historySize:0}:null),ks=O.getSessionSummarySnapshot()??(We?{enabled:We.enabled===!0,emitOnHidden:We.emitOnHidden===!0,emitOnDestroy:We.emitOnDestroy!==!1,minimumSessionMs:We.minimumSessionMs??0,emittedCount:0,lastEmittedAt:void 0,startedAt:void 0}:null),J=t.modules.conversion.manual,Rs={lead:J.lead?.enabled===!0,addToCart:J.addToCart?.enabled===!0,removeFromCart:J.removeFromCart?.enabled===!0,initiateCheckout:J.initiateCheckout?.enabled===!0,addPaymentInfo:J.addPaymentInfo?.enabled===!0,purchase:J.purchase?.enabled===!0,viewContent:J.viewContent?.enabled===!0,search:J.search?.enabled===!0},Ms=t.modules.conversion.auto?.detectors??{},Ps=Object.values(Ms).filter(P=>P&&typeof P=="object"&&P.enabled).length,Hi=s.getDebugState(),wr=a?.delivery,Ge=a?.advanced;return{sdkVersion:this.deps.getSdkVersion(),runtimeInitialized:e.isInitialized(),runtimeDestroyed:this.destroyed,moduleRegistry:c,services:d,behaviorEnabled:t.modules.behavior.enabled===!0,behaviorTrackers:b,behaviorEngines:S,behaviorHeartbeat:zi,behaviorViewport:Ts,behaviorEngagement:Is,behaviorRateLimit:As,behaviorBuffer:Ds,behaviorStateMachine:ws,behaviorSessionSummary:ks,conversion:{enabled:t.modules.conversion.enabled===!0,autoEnabled:t.modules.conversion.auto?.enabled===!0,manualEnabledFlags:Rs,detectorCount:Ps,activeDetectors:[...o.getDebugActiveDetectors()],dedupeKeyCount:o.getDebugDedupeKeys().length},integrations:{enabled:t.modules.integrations.enabled===!0,active:Hi?.active===!0,destinationNames:[...Hi?.destinationNames??[]],metrics:Hi?.metrics??null},transport:{enabled:t.transport.enabled===!0,state:a?{online:wr?.offline?.isOnline??"unknown",senderMode:Ge?.senderMode??"unknown",queueSize:a.queueSize,sentCount:a.sentCount,ackCount:wr?.ackCount??0,inFlight:wr?.inFlight??!1,retryPending:wr?.retry?.pendingCount??0,circuitBreakerState:String(Ge?.circuitBreaker?.state??"unavailable"),dlqCount:Ge?.deadLetter?.count??0,isLeader:Ge?.coordination?.isLeader??!0,persistenceEnabled:Ge?.storage?.persistenceEnabled??!1}:null},configSafe:Ys(t)}}};function Ys(r){let e={app:{environment:r.app.environment,debug:r.app.debug,source:r.app.source,target:r.app.target,platform:r.app.platform},identity:{pixelId:r.identity.pixelId?"[Present]":"[Missing]"},transport:{enabled:r.transport.enabled,sender:{mode:r.transport.sender.mode}},modules:{core:{enabled:r.modules.core.enabled},behavior:{enabled:r.modules.behavior.enabled},conversion:{enabled:r.modules.conversion.enabled,auto:{enabled:r.modules.conversion.auto?.enabled}},integrations:{enabled:r.modules.integrations.enabled},privacy:{enabled:r.modules.privacy.enabled}},commerce:{enabled:r.commerce?.enabled,currency:r.commerce?.currency,cartMode:r.commerce?.cart?.mode},attribution:{enabled:r.attribution?.enabled}};return en(e)}var et=class{constructor(e){this.name="diagnostics";this.active=!1;this.snapshotService=e}init(e){this.active||(this.snapshotService.markAlive(),this.active=!0)}destroy(){this.active&&(this.snapshotService.markDestroyed(),this.active=!1)}getSnapshotService(){return this.snapshotService}};var U=class{constructor(){this.listeners=new Map;this.cleared=!1;this.signalSeq=0}publish(e){if(this.cleared)return;let t=this.listeners.get(e.type);if(!(!t||t.size===0))for(let i of[...t])try{i(e)}catch{}}subscribe(e,t){if(this.cleared)return()=>{};let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}}clear(){this.listeners.clear(),this.cleared=!0}reset(){this.listeners.clear(),this.cleared=!1,this.signalSeq=0}listenerCount(e){if(e)return this.listeners.get(e)?.size??0;let t=0;for(let i of this.listeners.values())t+=i.size;return t}createSignal(e,t,i){return this.signalSeq+=1,{id:`bsig_${this.signalSeq}_${Date.now()}`,type:e,timestamp:Date.now(),source:t,...i?{data:i}:{}}}};var he=class{constructor(){this.nextId=1;this.pending=new Map;this.destroyed=!1}schedule(e,t){if(this.destroyed||typeof setTimeout>"u")return{id:-1};let i=this.nextId++,n={id:i},o=Math.max(0,t),s=Date.now()+o,a=setTimeout(()=>{if(this.pending.delete(i),this.lastDrift=Date.now()-s,!this.destroyed)try{e()}catch{}},o);return this.pending.set(i,{handle:n,expectedAt:s,timer:a}),n}cancel(e){let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id))}cancelAll(){for(let e of this.pending.values())clearTimeout(e.timer);this.pending.clear()}activeCount(){return this.pending.size}lastDriftMs(){return this.lastDrift}destroy(){this.destroyed||(this.cancelAll(),this.destroyed=!0)}reset(){this.cancelAll(),this.destroyed=!1,this.lastDrift=void 0}isDestroyed(){return this.destroyed}};var tt=class{constructor(e){this.config=e}shouldEmit(e){return e.reason==="initial"||e.reason==="manual_evaluation"?!0:this.config.emitOnChange?Math.abs(e.score-e.previousScore)>=this.config.minScoreDelta:!1}};var ge=class{constructor(e){this.thresholds=e}resolve(e){return e<=this.thresholds.lowMax?"low":e<=this.thresholds.mediumMax?"medium":"high"}};var De={activeTimeMs:6e4,clicks:10,viewportEntries:5,heartbeats:10,rageClicks:3};function fe(r){return!Number.isFinite(r)||r<0?0:r>1?1:r}function no(r,e){return e<=0?0:fe(r/e)}var rt=class{constructor(e,t){this.config=e,this.levelResolver=t??new ge(e.thresholds)}computeComponents(e){let t=e.visibleDurationMs+e.hiddenDurationMs;return{activeTime:fe(e.activeDurationMs/De.activeTimeMs),scroll:fe(e.maxScrollPercent/100),click:fe(e.clickCount/De.clicks),viewport:fe(e.viewportEntryCount/De.viewportEntries),visibility:no(e.visibleDurationMs,t),heartbeat:fe(e.heartbeatCount/De.heartbeats)}}calculate(e){let{weights:t,penalties:i}=this.config,n=this.computeComponents(e),o=n.activeTime*t.activeTime+n.scroll*t.scroll+n.click*t.click+n.viewport*t.viewport+n.visibility*t.visibility+n.heartbeat*t.heartbeat,s=e.activeDurationMs+e.idleDurationMs,a=i.idle*no(e.idleDurationMs,s),l=i.rageClick*fe(e.rageClickCount/De.rageClicks),u=(o-a-l)*100,c=Math.max(0,Math.min(100,Math.round(u))),d=this.levelResolver.resolve(c);return{components:n,weights:t,penalties:{idle:a,rageClick:l},rawScore:u,finalScore:c,level:d}}};var oo={HEARTBEAT:0,SCROLL:0,CLICK:0,RAGE_CLICK:0,IDLE:0,ACTIVITY:0,VISIBLE:0,HIDDEN:0,VIEWPORT_ENTER:0,VIEWPORT_EXIT:0},it=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0;this.signalCounts={...oo}}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0,this.signalCounts={...oo}}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type in this.signalCounts&&(this.signalCounts[e.type]+=1),e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}getSignalCounts(){return{...this.signalCounts}}};var nt=class{build(e){let{state:t}=e;return{score:e.score,peakScore:e.peakScore,averageScore:e.averageScore,level:e.level,activeDurationMs:t.activeDurationMs,idleDurationMs:t.idleDurationMs,visibleDurationMs:t.visibleDurationMs,hiddenDurationMs:t.hiddenDurationMs,maxScrollPercent:t.maxScrollPercent,clickCount:t.clickCount,rageClickCount:t.rageClickCount,viewportEntryCount:t.viewportEntryCount,heartbeatCount:t.heartbeatCount,startedAt:t.startedAt,endedAt:e.endedAt}}};var Xs=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","VIEWPORT_ENTER","VIEWPORT_EXIT"],ot=class{constructor(e,t){this.id="engagement";this.accumulator=new it;this.summaryBuilder=new nt;this.initialized=!1;this.running=!1;this.destroyed=!1;this.hasError=!1;this.tickHandle=null;this.unsubscribers=[];this.score=0;this.lastEmittedScore=0;this.peakScore=0;this.scoreSum=0;this.evaluationCount=0;this.emittedUpdateCount=0;this.emittedSummaryCount=0;this.level="low";this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new U,this.ownsBus=!0),t.scheduler?(this.scheduler=t.scheduler,this.ownsScheduler=!1):(this.scheduler=new he,this.ownsScheduler=!0);let i=new ge(this.config.thresholds);this.calculator=new rt(this.config,i),this.emissionPolicy=new tt(this.config)}init(){if(this.initialized&&!this.destroyed)return;let e=Date.now();this.destroyed=!1,this.hasError=!1,this.accumulator.reset(e),this.ownsBus&&this.signalBus instanceof U&&this.signalBus.reset(),this.ownsScheduler&&this.scheduler instanceof he&&this.scheduler.reset(),this.score=0,this.lastEmittedScore=0,this.peakScore=0,this.scoreSum=0,this.evaluationCount=0,this.emittedUpdateCount=0,this.emittedSummaryCount=0,this.level="low",this.lastEvaluatedAt=void 0,this.lastEmittedAt=void 0,this.tickHandle=null,this.bindSignals(),this.initialized=!0,this.running=!0,this.evaluate("initial"),this.scheduleNext()}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.initialized;this.running=!1,this.destroyed=!0,this.cancelTick(),e&&this.config.emitSummaryOnDestroy&&this.emitSummary(),this.unbindSignals(),this.ownsScheduler&&this.scheduler.destroy(),this.ownsBus&&this.signalBus instanceof U&&this.signalBus.clear(),this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}evaluateNow(){return!this.running||this.destroyed?null:this.evaluate("manual_evaluation")}activeTimerCount(){return this.scheduler.activeCount()}debugPublishSignal(e,t){this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,score:this.score,previousScore:this.lastEmittedScore,peakScore:this.peakScore,averageScore:this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,level:this.level,evaluationCount:this.evaluationCount,emittedUpdateCount:this.emittedUpdateCount,emittedSummaryCount:this.emittedSummaryCount,lastEvaluatedAt:this.lastEvaluatedAt,lastEmittedAt:this.lastEmittedAt,evaluationIntervalMs:this.config.evaluationIntervalMs,lastDriftMs:this.scheduler.lastDriftMs(),hasError:this.hasError,signalCounts:this.accumulator.getSignalCounts()}}bindSignals(){this.unbindSignals();for(let e of Xs)this.unsubscribers.push(this.signalBus.subscribe(e,t=>{this.destroyed||!this.running||this.accumulator.ingest(t)}))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(){this.cancelTick(),!(this.destroyed||!this.running)&&(this.tickHandle=this.scheduler.schedule(()=>this.tick(),this.config.evaluationIntervalMs))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){this.tickHandle=null,!(this.destroyed||!this.running)&&(this.evaluate("interval"),this.scheduleNext())}evaluate(e){let t=Date.now();this.accumulator.flush(t);let i;try{i=this.calculator.calculate(this.accumulator.getState())}catch{return this.hasError=!0,this.context.logger.warn("[Pixel] Engagement score calculation failed (isolated)"),null}return this.evaluationCount+=1,this.score=i.finalScore,this.level=i.level,this.scoreSum+=i.finalScore,i.finalScore>this.peakScore&&(this.peakScore=i.finalScore),this.lastEvaluatedAt=t,this.emissionPolicy.shouldEmit({reason:e,score:i.finalScore,previousScore:this.lastEmittedScore})&&this.emitUpdate(i.finalScore,i.level,e,t),i}emitUpdate(e,t,i,n){let o=this.lastEmittedScore,s=e-o;try{let a=this.context.services.eventBuilder.build({type:"ENGAGEMENT_UPDATE",category:"ENGAGEMENT",score:e,previousScore:o,delta:s,level:t,evaluatedAt:n,reason:i});this.context.services.dispatcher.dispatch(a),this.lastEmittedScore=e,this.emittedUpdateCount+=1,this.lastEmittedAt=n}catch{this.context.logger.warn("[Pixel] Engagement update emit failed (listener isolated)")}}emitSummary(){if(this.emittedSummaryCount>0)return;let e=Date.now();this.accumulator.flush(e);let t=this.accumulator.getState(),i=this.evaluationCount>0?Math.round(this.scoreSum/this.evaluationCount):0,n=this.summaryBuilder.build({state:t,score:this.score,peakScore:this.peakScore,averageScore:i,level:this.level,endedAt:e});try{let o=this.context.services.eventBuilder.build({type:"ENGAGEMENT_SUMMARY",category:"ENGAGEMENT",...n});this.context.services.dispatcher.dispatch(o),this.emittedSummaryCount+=1}catch{this.emittedSummaryCount+=1,this.context.logger.warn("[Pixel] Engagement summary emit failed (listener isolated)")}}};var Mr=class{constructor(e){this.config=e}canEmit(e,t){if(t.destroyed)return{allow:!1,reason:"destroyed"};if(!t.running)return{allow:!1,reason:"not_running"};let i=e.idle===!0;return!this.config.emitWhenHidden&&e.visible===!1?{allow:!1,reason:"hidden"}:!this.config.emitWhenIdle&&i?{allow:!1,reason:"idle"}:{allow:!0,reason:"ok"}}resolveIntervalMs(e){return e.visible===!1?this.config.hiddenIntervalMs:this.config.intervalMs}};var Pr=class{constructor(e){this.config=e}build(e,t,i=Date.now()){let n=e.idle===!0,o=e.visible!==!1,a={sequence:t,active:!n&&o,idle:n,visible:o,elapsedMs:Math.max(0,i-e.startedAt)};return this.config.includeSnapshot?{...a,...e.lastActivityAt!==void 0?{lastActivityAt:e.lastActivityAt}:{},...e.idleSince!==void 0?{idleSince:e.idleSince}:{},...e.visibleSince!==void 0?{visibleSince:e.visibleSince}:{},...e.hiddenSince!==void 0?{hiddenSince:e.hiddenSince}:{}}:a}};var _r=class{constructor(e,t){this.id="heartbeat";this.scheduler=new he;this.initialized=!1;this.running=!1;this.destroyed=!1;this.tickHandle=null;this.unsubscribers=[];this.sequence=0;this.emittedCount=0;this.skippedCount=0;this.startedAt=0;this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0};this.context=e,this.config=t.config,t.signalBus?(this.signalBus=t.signalBus,this.ownsBus=!1):(this.signalBus=new U,this.ownsBus=!0),this.policy=new Mr(t.config),this.snapshotBuilder=new Pr(t.config)}init(){this.initialized&&!this.destroyed||(this.destroyed=!1,this.scheduler.reset(),this.sequence=0,this.emittedCount=0,this.skippedCount=0,this.lastEmittedAt=void 0,this.nextExpectedAt=void 0,this.tickHandle=null,this.startedAt=Date.now(),this.activity={visible:void 0,idle:void 0,lastActivityAt:void 0,idleSince:void 0,visibleSince:void 0,hiddenSince:void 0},this.seedEnvironmentState(),this.bindSignals(),this.initialized=!0,this.running=!0,this.config.fireImmediately?this.tick():this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState())))}destroy(){this.destroyed&&!this.initialized||(this.running=!1,this.destroyed=!0,this.cancelTick(),this.scheduler.destroy(),this.unbindSignals(),this.nextExpectedAt=void 0,this.ownsBus&&this.signalBus instanceof U&&this.signalBus.clear(),this.initialized=!1)}isInitialized(){return this.initialized}isRunning(){return this.running}getMetrics(){return{sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}getSnapshot(){return{enabled:this.config.enabled,initialized:this.initialized,running:this.running,intervalMs:this.config.intervalMs,hiddenIntervalMs:this.config.hiddenIntervalMs,sequence:this.sequence,emittedCount:this.emittedCount,skippedCount:this.skippedCount,lastEmittedAt:this.lastEmittedAt,nextExpectedAt:this.nextExpectedAt,lastDriftMs:this.scheduler.lastDriftMs()}}activeTimerCount(){return this.scheduler.activeCount()}seedEnvironmentState(){if(typeof document>"u")return;let e=Date.now(),t=document.visibilityState==="visible";this.activity.visible=t,t?(this.activity.visibleSince=e,this.activity.hiddenSince=void 0):(this.activity.hiddenSince=e,this.activity.visibleSince=void 0)}bindSignals(){if(this.unbindSignals(),this.unsubscribers.push(this.signalBus.subscribe("ACTIVITY",e=>{this.activity.lastActivityAt=e.timestamp,this.activity.idle=!1,this.activity.idleSince=void 0})),this.unsubscribers.push(this.signalBus.subscribe("IDLE",e=>{this.activity.idle=!0,this.activity.idleSince=e.timestamp;let t=e.data?.idleSince;typeof t=="number"&&(this.activity.idleSince=t)})),this.unsubscribers.push(this.signalBus.subscribe("VISIBLE",e=>{this.activity.visible=!0,this.activity.visibleSince=e.timestamp,this.activity.hiddenSince=void 0,this.rescheduleForVisibilityChange()})),this.unsubscribers.push(this.signalBus.subscribe("HIDDEN",e=>{this.activity.visible=!1,this.activity.hiddenSince=e.timestamp,this.rescheduleForVisibilityChange()})),typeof document<"u"){let e=()=>{if(typeof document>"u")return;let t=Date.now();document.visibilityState==="visible"?(this.activity.visible=!0,this.activity.visibleSince=t,this.activity.hiddenSince=void 0):(this.activity.visible=!1,this.activity.hiddenSince=t),this.rescheduleForVisibilityChange()};document.addEventListener("visibilitychange",e),this.unsubscribers.push(()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",e)})}}rescheduleForVisibilityChange(){!this.running||this.destroyed||this.scheduleNext(this.policy.resolveIntervalMs(this.readActivityState()))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}scheduleNext(e){this.cancelTick(),!(this.destroyed||!this.running)&&(this.nextExpectedAt=Date.now()+e,this.tickHandle=this.scheduler.schedule(()=>this.tick(),e))}cancelTick(){this.tickHandle&&(this.scheduler.cancel(this.tickHandle),this.tickHandle=null)}tick(){if(this.tickHandle=null,this.destroyed||!this.running)return;let e=this.readActivityState();this.policy.canEmit(e,{running:this.running,destroyed:this.destroyed}).allow?this.emitHeartbeat(e):this.skippedCount+=1,this.scheduleNext(this.policy.resolveIntervalMs(e))}readActivityState(){return{startedAt:this.startedAt,visible:this.activity.visible,idle:this.activity.idle,lastActivityAt:this.activity.lastActivityAt,idleSince:this.activity.idleSince,visibleSince:this.activity.visibleSince,hiddenSince:this.activity.hiddenSince}}emitHeartbeat(e){this.sequence+=1;let t=Date.now(),i=this.snapshotBuilder.build(e,this.sequence,t);try{let n=this.context.services.eventBuilder.build({type:"BEHAVIOR_HEARTBEAT",category:"ENGAGEMENT",...i});this.context.services.dispatcher.dispatch(n),this.emittedCount+=1,this.lastEmittedAt=t,this.signalBus.publish(this.signalBus.createSignal("HEARTBEAT","HeartbeatEngine",{sequence:this.sequence}))}catch{this.skippedCount+=1,this.context.logger.warn("[Pixel] Heartbeat emit failed (listener isolated)")}}};var ie={activeTime:.25,scroll:.2,click:.15,viewport:.2,visibility:.1,heartbeat:.1},on={idle:.2,rageClick:.1},st={lowMax:29,mediumMax:69},so={enabled:!1,evaluationIntervalMs:5e3,emitOnChange:!0,minScoreDelta:5,emitSummaryOnDestroy:!0,weights:ie,penalties:on,thresholds:st},Zs=["activeTime","scroll","click","viewport","visibility","heartbeat"];function N(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function ne(r){return r<0?0:r>1?1:r}function Js(r){let e={activeTime:ne(N(r?.activeTime,ie.activeTime)),scroll:ne(N(r?.scroll,ie.scroll)),click:ne(N(r?.click,ie.click)),viewport:ne(N(r?.viewport,ie.viewport)),visibility:ne(N(r?.visibility,ie.visibility)),heartbeat:ne(N(r?.heartbeat,ie.heartbeat))},t=0;for(let i of Zs)t+=e[i];return t<=0?{...ie}:{activeTime:e.activeTime/t,scroll:e.scroll/t,click:e.click/t,viewport:e.viewport/t,visibility:e.visibility/t,heartbeat:e.heartbeat/t}}function ea(r){return{idle:ne(N(r?.idle,on.idle)),rageClick:ne(N(r?.rageClick,on.rageClick))}}function ta(r){let e=Math.round(N(r?.lowMax,st.lowMax)),t=Math.round(N(r?.mediumMax,st.mediumMax));return e>=0&&e<t&&t<100||(e=st.lowMax,t=st.mediumMax),{lowMax:e,mediumMax:t}}function ao(r){return ra(r.engagement)}function ra(r){let e=r?.enabled===!0,t=Math.floor(N(r?.evaluationIntervalMs,so.evaluationIntervalMs));t<1e3&&(t=1e3);let i=Math.floor(N(r?.minScoreDelta,so.minScoreDelta));return i<0&&(i=0),{enabled:e,evaluationIntervalMs:t,emitOnChange:r?.emitOnChange!==!1,minScoreDelta:i,emitSummaryOnDestroy:r?.emitSummaryOnDestroy!==!1,weights:Js(r?.weights),penalties:ea(r?.penalties),thresholds:ta(r?.thresholds)}}var lo={enabled:!1,intervalMs:15e3,hiddenIntervalMs:6e4,emitWhenHidden:!1,emitWhenIdle:!0,includeSnapshot:!0,fireImmediately:!1},Lr=1e3;function uo(r){return ia(r.heartbeat)}function ia(r){let e=r?.enabled===!0,t=typeof r?.intervalMs=="number"&&Number.isFinite(r.intervalMs)?Math.floor(r.intervalMs):lo.intervalMs;t<Lr&&(t=Lr);let i=typeof r?.hiddenIntervalMs=="number"&&Number.isFinite(r.hiddenIntervalMs)?Math.floor(r.hiddenIntervalMs):lo.hiddenIntervalMs;i<Lr&&(i=Lr);let n={enabled:e,intervalMs:t,hiddenIntervalMs:i,emitWhenHidden:r?.emitWhenHidden===!0,emitWhenIdle:r?.emitWhenIdle!==!1,includeSnapshot:r?.includeSnapshot!==!1,fireImmediately:r?.fireImmediately===!0};return typeof r?.minActivityWindowMs=="number"&&Number.isFinite(r.minActivityWindowMs)&&r.minActivityWindowMs>=0?{...n,minActivityWindowMs:Math.floor(r.minActivityWindowMs)}:n}var na=["drop_oldest","drop_newest","compress_similar"];function ye(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function sn(r,e){return typeof r=="boolean"?r:e}function oa(r){let e=Math.floor(ye(r?.windowMs,1e3));e<100&&(e=100);let t=Math.floor(ye(r?.maxSignalsPerWindow,50));return t<1&&(t=1),{enabled:r?.enabled===!0,windowMs:e,maxSignalsPerWindow:t,criticalBypass:sn(r?.criticalBypass,!0)}}function sa(r){let e=Math.floor(ye(r?.maxSize,200));e<1&&(e=1);let t=Math.floor(ye(r?.maxAgeMs,3e4));t<0&&(t=0);let i=Math.floor(ye(r?.flushSize,50));i<1&&(i=1),i>e&&(i=e);let n=r?.dropStrategy&&na.includes(r.dropStrategy)?r.dropStrategy:"compress_similar";return{enabled:r?.enabled===!0,maxSize:e,maxAgeMs:t,flushSize:i,dropStrategy:n,flushOnHidden:sn(r?.flushOnHidden,!0)}}function aa(r){let e=Math.floor(ye(r?.historyLimit,50));return e<1&&(e=1),e>1e3&&(e=1e3),{enabled:r?.enabled===!0,historyLimit:e}}function la(r){let e=Math.floor(ye(r?.minimumSessionMs,0));return e<0&&(e=0),{enabled:r?.enabled===!0,emitOnHidden:r?.emitOnHidden===!0,emitOnDestroy:sn(r?.emitOnDestroy,!0),minimumSessionMs:e}}function co(r){return{rateLimit:oa(r.rateLimit),buffer:sa(r.buffer),stateMachine:aa(r.stateMachine),sessionSummary:la(r.sessionSummary)}}var mo=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var ua=new Set(mo),at=class{constructor(e){this.windowTimestamps=[];this.accepted=0;this.dropped=0;this.bypassed=0;this.config=e}reset(){this.windowTimestamps=[],this.accepted=0,this.dropped=0,this.bypassed=0}evaluate(e,t){return this.config.enabled?this.config.criticalBypass&&ua.has(e)?(this.bypassed+=1,"bypassed"):(this.prune(t),this.windowTimestamps.length<this.config.maxSignalsPerWindow?(this.windowTimestamps.push(t),this.accepted+=1,"accepted"):(this.dropped+=1,"dropped")):(this.accepted+=1,"accepted")}prune(e){let t=e-this.config.windowMs,i=0;for(let n of this.windowTimestamps)if(n<=t)i+=1;else break;i>0&&this.windowTimestamps.splice(0,i)}getSnapshot(){return{enabled:this.config.enabled,windowMs:this.config.windowMs,maxSignalsPerWindow:this.config.maxSignalsPerWindow,criticalBypass:this.config.criticalBypass,accepted:this.accepted,dropped:this.dropped,bypassed:this.bypassed,windowCount:this.windowTimestamps.length,windowStartedAt:this.windowTimestamps[0]}}};var po=["IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT"];var ho=new Set(po),lt=class{constructor(e){this.entries=[];this.flushCount=0;this.dropCount=0;this.compressedCount=0;this.config=e}reset(){this.entries=[],this.flushCount=0,this.dropCount=0,this.compressedCount=0,this.lastFlushAt=void 0,this.lastFlushReason=void 0}size(){return this.entries.length}add(e,t){if(this.entries.length<this.config.maxSize){this.entries.push({signal:e,bufferedAt:t,count:1});return}switch(this.config.dropStrategy){case"drop_newest":this.dropCount+=1;return;case"drop_oldest":this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1});return;case"compress_similar":default:this.addCompressed(e,t);return}}addCompressed(e,t){if(!ho.has(e.type))for(let n=this.entries.length-1;n>=0;n-=1){let o=this.entries[n];if(o&&o.signal.type===e.type){this.entries[n]={signal:e,bufferedAt:t,count:o.count+1},this.compressedCount+=1;return}}let i=this.findOldestCompressibleIndex();i>=0?this.entries.splice(i,1):this.entries.shift(),this.dropCount+=1,this.entries.push({signal:e,bufferedAt:t,count:1})}findOldestCompressibleIndex(){for(let e=0;e<this.entries.length;e+=1){let t=this.entries[e];if(t&&!ho.has(t.signal.type))return e}return-1}shouldFlushBySize(){return this.entries.length>=this.config.flushSize}hasAgedEntries(e){if(this.config.maxAgeMs<=0)return!1;let t=this.entries[0];return t?e-t.bufferedAt>=this.config.maxAgeMs:!1}flush(e,t){let i=this.entries;return this.entries=[],this.flushCount+=1,this.lastFlushAt=t,this.lastFlushReason=e,i}getSnapshot(){return{enabled:this.config.enabled,size:this.entries.length,maxSize:this.config.maxSize,flushSize:this.config.flushSize,maxAgeMs:this.config.maxAgeMs,dropStrategy:this.config.dropStrategy,flushCount:this.flushCount,dropCount:this.dropCount,compressedCount:this.compressedCount,lastFlushAt:this.lastFlushAt,lastFlushReason:this.lastFlushReason}}};var ca={NOT_INITIALIZED:["INITIALIZING","DESTROYING"],INITIALIZING:["ACTIVE","DESTROYING"],ACTIVE:["IDLE","HIDDEN","PAUSED","DESTROYING"],IDLE:["ACTIVE","HIDDEN","PAUSED","DESTROYING"],HIDDEN:["ACTIVE","IDLE","PAUSED","DESTROYING"],PAUSED:["ACTIVE","IDLE","HIDDEN","DESTROYING"],DESTROYING:["DESTROYED"],DESTROYED:["INITIALIZING"]},ut=class{constructor(e){this.state="NOT_INITIALIZED";this.generation=0;this.transitionCount=0;this.invalidTransitionCount=0;this.history=[];this.preHiddenState="ACTIVE";this.config=e}getState(){return this.state}getGeneration(){return this.generation}getHistory(){return this.history}beginInit(e){this.generation+=1,this.transition("INITIALIZING","init",e),this.transition("ACTIVE","init_complete",e)}beginDestroy(e){this.transition("DESTROYING","destroy",e)}finishDestroy(e){this.transition("DESTROYED","destroy_complete",e)}pause(e){return this.transition("PAUSED","pause",e)}resume(e){let t=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";return this.transition(t,"resume",e)}applySignal(e,t){switch(e){case"ACTIVITY":this.transition("ACTIVE","signal:ACTIVITY",t);break;case"IDLE":this.transition("IDLE","signal:IDLE",t);break;case"HIDDEN":(this.state==="ACTIVE"||this.state==="IDLE")&&(this.preHiddenState=this.state),this.transition("HIDDEN","signal:HIDDEN",t);break;case"VISIBLE":{if(this.state!=="HIDDEN")break;let i=this.preHiddenState==="IDLE"?"IDLE":"ACTIVE";this.transition(i,"signal:VISIBLE",t);break}default:break}}transition(e,t,i){if(this.state===e)return!0;if(!(ca[this.state]??[]).includes(e))return this.invalidTransitionCount+=1,!1;let o={from:this.state,to:e,at:i,reason:t,generation:this.generation};return this.previousState=this.state,this.state=e,this.changedAt=i,this.transitionCount+=1,this.pushHistory(o),!0}pushHistory(e){this.history.push(e),this.history.length>this.config.historyLimit&&this.history.splice(0,this.history.length-this.config.historyLimit)}getSnapshot(){return{enabled:this.config.enabled,state:this.state,previousState:this.previousState,generation:this.generation,changedAt:this.changedAt,transitionCount:this.transitionCount,invalidTransitionCount:this.invalidTransitionCount,historySize:this.history.length}}};var ct=class{constructor(){this.startedAt=0;this.lastFlushAt=0;this.activeDurationMs=0;this.idleDurationMs=0;this.visibleDurationMs=0;this.hiddenDurationMs=0;this.viewportVisibleDurationMs=0;this.maxScrollPercent=0;this.clickCount=0;this.rageClickCount=0;this.viewportEntryCount=0;this.heartbeatCount=0;this.isIdle=!1;this.isVisible=!0;this.activeViewportCount=0}reset(e){this.startedAt=e,this.lastFlushAt=e,this.lastSignalAt=void 0,this.activeDurationMs=0,this.idleDurationMs=0,this.visibleDurationMs=0,this.hiddenDurationMs=0,this.viewportVisibleDurationMs=0,this.maxScrollPercent=0,this.clickCount=0,this.rageClickCount=0,this.viewportEntryCount=0,this.heartbeatCount=0,this.isIdle=!1,this.isVisible=!0,this.activeViewportCount=0}flush(e){let t=Math.max(0,e-this.lastFlushAt);t>0&&(this.isIdle?this.idleDurationMs+=t:this.activeDurationMs+=t,this.isVisible?this.visibleDurationMs+=t:this.hiddenDurationMs+=t,this.activeViewportCount>0&&(this.viewportVisibleDurationMs+=t)),this.lastFlushAt=e}ingest(e){let t=e.timestamp;switch(this.flush(t),this.lastSignalAt=t,e.type){case"HEARTBEAT":this.heartbeatCount+=1;break;case"CLICK":this.clickCount+=1;break;case"RAGE_CLICK":this.rageClickCount+=1;break;case"SCROLL":{let i=e.data?.maxScrollPercent;typeof i=="number"&&Number.isFinite(i)&&(this.maxScrollPercent=Math.min(100,Math.max(this.maxScrollPercent,i)));break}case"IDLE":this.isIdle=!0;break;case"ACTIVITY":this.isIdle=!1;break;case"VISIBLE":this.isVisible=!0;break;case"HIDDEN":this.isVisible=!1;break;case"VIEWPORT_ENTER":this.viewportEntryCount+=1,this.activeViewportCount+=1;break;case"VIEWPORT_EXIT":this.activeViewportCount>0&&(this.activeViewportCount-=1);break;default:break}}getState(){return{activeDurationMs:this.activeDurationMs,idleDurationMs:this.idleDurationMs,visibleDurationMs:this.visibleDurationMs,hiddenDurationMs:this.hiddenDurationMs,maxScrollPercent:this.maxScrollPercent,clickCount:this.clickCount,rageClickCount:this.rageClickCount,viewportEntryCount:this.viewportEntryCount,viewportVisibleDurationMs:this.viewportVisibleDurationMs,heartbeatCount:this.heartbeatCount,startedAt:this.startedAt,lastSignalAt:this.lastSignalAt}}};var da=["HEARTBEAT","SCROLL","CLICK","RAGE_CLICK","IDLE","ACTIVITY","VISIBLE","HIDDEN","EXIT_INTENT","VIEWPORT_ENTER","VIEWPORT_EXIT"],dt=class{constructor(e,t){this.id="runtimeIntelligence";this.signalBus=null;this.accumulator=new ct;this.unsubscribers=[];this.initialized=!1;this.running=!1;this.destroyed=!1;this.emittedCount=0;this.hiddenSummaryEmitted=!1;this.context=e,this.config=t.config,this.getEngagement=t.getEngagement,this.rateLimiter=new at(t.config.rateLimit),this.buffer=new lt(t.config.buffer),this.stateMachine=new ut(t.config.stateMachine)}init(e){if(this.initialized&&!this.destroyed)return;let t=Date.now();this.signalBus=e,this.destroyed=!1,this.startedAt=t,this.hiddenSummaryEmitted=!1,this.rateLimiter.reset(),this.buffer.reset(),this.accumulator.reset(t),this.stateMachine.beginInit(t),this.bindSignals(),this.initialized=!0,this.running=!0}destroy(){if(this.destroyed&&!this.initialized)return;let e=this.running;this.running=!1,this.destroyed=!0,this.unbindSignals();let t=Date.now();this.safe(()=>this.stateMachine.beginDestroy(t)),this.config.buffer.enabled&&this.safe(()=>this.drainBufferToAccumulator("destroy",t)),e&&this.config.sessionSummary.emitOnDestroy&&this.safe(()=>this.emitSummary("destroy",t)),this.safe(()=>this.stateMachine.finishDestroy(t)),this.signalBus=null,this.initialized=!1}isInitialized(){return this.initialized}isRunning(){return this.running}flushNow(){!this.running||this.destroyed||this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",Date.now())}emitSummaryNow(e="hidden"){if(!this.running||this.destroyed)return!1;let t=Date.now();return this.config.buffer.enabled&&this.drainBufferToAccumulator("manual",t),this.emitSummary(e,t)}getRateLimitSnapshot(){return this.rateLimiter.getSnapshot()}getBufferSnapshot(){return this.buffer.getSnapshot()}getStateMachineSnapshot(){return this.stateMachine.getSnapshot()}getSessionSummarySnapshot(){return{enabled:this.config.sessionSummary.enabled,emitOnHidden:this.config.sessionSummary.emitOnHidden,emitOnDestroy:this.config.sessionSummary.emitOnDestroy,minimumSessionMs:this.config.sessionSummary.minimumSessionMs,emittedCount:this.emittedCount,lastEmittedAt:this.lastEmittedAt,startedAt:this.startedAt}}bindSignals(){this.unbindSignals();let e=this.signalBus;if(e)for(let t of da)this.unsubscribers.push(e.subscribe(t,i=>this.handleSignal(i)))}unbindSignals(){for(let e of this.unsubscribers)try{e()}catch{}this.unsubscribers=[]}handleSignal(e){if(!(this.destroyed||!this.running))try{let t=e.timestamp;if(this.rateLimiter.evaluate(e.type,t)==="dropped")return;this.config.stateMachine.enabled&&this.stateMachine.applySignal(e.type,t),this.config.buffer.enabled?(this.buffer.add(e,t),this.buffer.shouldFlushBySize()?this.drainBufferToAccumulator("size",t):this.buffer.hasAgedEntries(t)&&this.drainBufferToAccumulator("age",t)):this.config.sessionSummary.enabled&&this.accumulator.ingest(e),e.type==="HIDDEN"?this.onHidden(t):(e.type==="VISIBLE"||e.type==="ACTIVITY")&&(this.hiddenSummaryEmitted=!1)}catch{this.context.logger.warn("[Pixel] Behavior runtime pipeline error (isolated)")}}onHidden(e){this.config.buffer.enabled&&this.config.buffer.flushOnHidden&&this.drainBufferToAccumulator("hidden",e),this.config.sessionSummary.enabled&&this.config.sessionSummary.emitOnHidden&&!this.hiddenSummaryEmitted&&this.emitSummary("hidden",e)&&(this.hiddenSummaryEmitted=!0)}drainBufferToAccumulator(e,t){let i=this.buffer.flush(e,t);if(this.config.sessionSummary.enabled)for(let n of i)for(let o=0;o<n.count;o+=1)this.accumulator.ingest(n.signal)}emitSummary(e,t){if(!this.config.sessionSummary.enabled)return!1;let i=this.startedAt??t;if(this.config.sessionSummary.minimumSessionMs>0&&t-i<this.config.sessionSummary.minimumSessionMs)return!1;this.accumulator.flush(t);let n=this.accumulator.getState(),o=this.getEngagement()??{score:0,peakScore:0},s=this.stateMachine.getState(),a=this.stateMachine.getGeneration(),l={activeDurationMs:n.activeDurationMs,idleDurationMs:n.idleDurationMs,visibleDurationMs:n.visibleDurationMs,hiddenDurationMs:n.hiddenDurationMs,maxScrollPercent:n.maxScrollPercent,clickCount:n.clickCount,rageClickCount:n.rageClickCount,viewportEntryCount:n.viewportEntryCount,viewportVisibleDurationMs:n.viewportVisibleDurationMs,heartbeatCount:n.heartbeatCount,engagementScore:o.score,engagementPeakScore:o.peakScore,startedAt:i,endedAt:t,finalState:s};try{let u=this.context.services.eventBuilder.build({type:"BEHAVIOR_SESSION_SUMMARY",category:"ENGAGEMENT",...l,generation:a,reason:e});return this.context.services.dispatcher.dispatch(u),this.emittedCount+=1,this.lastEmittedAt=t,!0}catch{return this.emittedCount+=1,this.lastEmittedAt=t,this.context.logger.warn("[Pixel] Behavior session summary emit failed (listener isolated)"),!0}}safe(e){try{e()}catch{this.context.logger.warn("[Pixel] Behavior runtime coordinator step failed (isolated)")}}};var w=class{constructor(e){this.active=!1;this.managedListeners=[];this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}clearManagedTimeout(e){return e&&clearTimeout(e),null}dispatchEngagement(e){let t=this.context.services.eventBuilder.build(e);this.context.services.dispatcher.dispatch(t)}};var ma=100,mt=class extends w{constructor(t,i){super(t);this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0};this.throttleTimer=null;this.debounceTimer=null;this.lastScrollY=0;this.lastScrollTime=0;this.velocitySum=0;this.crossedThresholds=new Set;this.lastDispatchedMaxPercent=-1;this.lastDispatchAt=0;this.signalBus=i?.signalBus}onInit(){this.isWindowAvailable()&&(this.resetState(),this.lastScrollY=window.scrollY,this.lastScrollTime=Date.now(),this.addWindowListener("scroll",()=>this.handleScroll(),{passive:!0}))}onDestroy(){this.throttleTimer=this.clearManagedTimeout(this.throttleTimer),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resetState(){this.state={maxScrollPercent:0,scrollEvents:0,scrollVelocityAvg:0,lastScrollAt:0},this.lastScrollY=0,this.lastScrollTime=0,this.velocitySum=0,this.crossedThresholds.clear(),this.lastDispatchedMaxPercent=-1,this.lastDispatchAt=0}getMaxScrollPercent(){if(!this.isWindowAvailable()||!this.isDocumentAvailable())return 0;let t=document.documentElement,i=document.body?document.body.scrollHeight:0,n=Math.max(t.scrollHeight,i),o=t.clientHeight;if(n<=o)return 100;let s=n-o,a=window.scrollY||window.pageYOffset;return Math.min(100,Math.round(a/s*100))}canDispatch(t){return Date.now()-this.lastDispatchAt>=t}handleScroll(){if(!this.isWindowAvailable())return;let{debounceMs:t}=this.context.config.modules.behavior.trackers.scroll;this.throttleTimer||(this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.updateScrollState(),this.maybeDispatchOnThresholdCrossing(t),this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.maybeDispatchOnScrollEnd(t)},t)},ma))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),i=window.scrollY||window.pageYOffset,n=this.getMaxScrollPercent();if(n>this.state.maxScrollPercent&&(this.state.maxScrollPercent=n),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(i-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=i,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:i}=this.context.config.modules.behavior.trackers.scroll,n=this.state.maxScrollPercent,o=!1;for(let s of i)n>=s&&!this.crossedThresholds.has(s)&&(this.crossedThresholds.add(s),o=!0);o&&this.canDispatch(t)&&this.emitScrollEvent()}maybeDispatchOnScrollEnd(t){this.state.maxScrollPercent!==this.lastDispatchedMaxPercent&&this.canDispatch(t)&&this.emitScrollEvent()}emitScrollEvent(){this.dispatchEngagement({type:"SCROLL",category:"ENGAGEMENT",maxScrollPercent:this.state.maxScrollPercent,scrollEvents:this.state.scrollEvents,scrollVelocityAvg:this.state.scrollVelocityAvg,lastScrollAt:this.state.lastScrollAt}),this.signalBus?.publish(this.signalBus.createSignal("SCROLL","ScrollTracker",{maxScrollPercent:this.state.maxScrollPercent})),this.lastDispatchedMaxPercent=this.state.maxScrollPercent,this.lastDispatchAt=Date.now()}};function an(r){if(!r)return;let e=r,t=r.classList?.length?Array.from(r.classList):void 0,i,n=e.innerText?.trim()??e.textContent?.trim();n&&(i=n.length>80?`${n.slice(0,80)}\u2026`:n);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:r.tagName?.toLowerCase(),id:r.id||void 0,classes:t,text:i,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function go(r){if(!r||!(r instanceof Element))return"unknown";let e=r.tagName.toLowerCase(),t=r.id?`#${r.id}`:"",i=r.className&&typeof r.className=="string"?`.${r.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",n=[];return typeof r.getAttributeNames=="function"&&r.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=r.getAttribute(o);s!=null&&n.push(`${o}=${s.slice(0,50)}`)}),[e,t,i,n.join("|")].filter(Boolean).join("")}var pt=class extends w{constructor(t,i){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map;this.signalBus=i?.signalBus}onInit(){this.isDocumentAvailable()&&(this.resetState(),this.addDocumentListener("click",t=>this.handleClick(t),!0))}onDestroy(){this.clickHistory.clear(),this.rageCooldownUntil.clear()}resetState(){this.state={clickCount:0,rageClickCount:0,lastClickAt:0},this.clickHistory.clear(),this.rageCooldownUntil.clear()}handleClick(t){let i=Date.now(),{rageClick:n}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=i,this.signalBus?.publish(this.signalBus.createSignal("CLICK","ClickTracker",{clickCount:this.state.clickCount}));let o=t.target instanceof Element?t.target:null,s=t.currentTarget instanceof Element?t.currentTarget:null,a=an(o),l=an(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:i,target:a,currentTarget:l,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!n.enabled)return;let u=go(o),c=this.rageCooldownUntil.get(u)??0;if(i<c)return;let m=(this.clickHistory.get(u)??[]).filter(h=>i-h<n.windowMs);m.push(i),this.clickHistory.set(u,m),m.length>=n.threshold&&(this.state.rageClickCount+=1,this.signalBus?.publish(this.signalBus.createSignal("RAGE_CLICK","ClickTracker",{rageClickCount:this.state.rageClickCount})),this.dispatchEngagement({type:"RAGE_CLICK",category:"ENGAGEMENT",threshold:n.threshold,windowMs:n.windowMs,clickCount:m.length,target:a}),this.clickHistory.delete(u),this.rageCooldownUntil.set(u,i+n.windowMs))}};var ht=class extends w{constructor(t,i){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null};this.signalBus=i?.signalBus}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),i=document.visibilityState==="visible";this.state={isVisible:i,visibleSince:t,hiddenAt:i?null:t},this.publishVisibilitySignal(),this.addDocumentListener("visibilitychange",()=>this.handleVisibilityChange()),this.emitVisibilityEvent()}onDestroy(){}handleVisibilityChange(){if(!this.isDocumentAvailable())return;let t=Date.now();document.visibilityState==="visible"?this.state={isVisible:!0,visibleSince:t,hiddenAt:null}:this.state={isVisible:!1,visibleSince:this.state.visibleSince,hiddenAt:t},this.publishVisibilitySignal(),this.emitVisibilityEvent()}publishVisibilitySignal(){this.signalBus&&(this.state.isVisible?this.signalBus.publish(this.signalBus.createSignal("VISIBLE","VisibilityTracker",{visibleSince:this.state.visibleSince})):this.signalBus.publish(this.signalBus.createSignal("HIDDEN","VisibilityTracker",{hiddenAt:this.state.hiddenAt})))}emitVisibilityEvent(){this.dispatchEngagement({type:"VISIBILITY_CHANGE",category:"ENGAGEMENT",isVisible:this.state.isVisible,visibleSince:this.state.visibleSince,hiddenAt:this.state.hiddenAt})}};var pa=["mousemove","scroll","keydown","touchstart"],gt=class extends w{constructor(t,i){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null;this.signalBus=i?.signalBus}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of pa)this.addWindowListener(t,()=>this.onActivity(),{passive:!0})}}onDestroy(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.isIdle=!1,this.idleSince=0}get thresholdMs(){return this.context.config.modules.behavior.trackers.idle.thresholdMs}scheduleIdleCheck(){this.idleTimer=this.clearManagedTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>this.enterIdle(),this.thresholdMs)}onActivity(){let t=Date.now();if(this.signalBus?.publish(this.signalBus.createSignal("ACTIVITY","IdleTracker",{at:t})),this.isIdle){let i=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:i})}this.scheduleIdleCheck()}enterIdle(){if(this.isIdle)return;let t=Date.now();this.isIdle=!0,this.idleSince=t,this.signalBus?.publish(this.signalBus.createSignal("IDLE","IdleTracker",{idleSince:t,thresholdMs:this.thresholdMs})),this.dispatchEngagement({type:"USER_IDLE",category:"ENGAGEMENT",idleSince:t,thresholdMs:this.thresholdMs})}};var ha=5,ft=class extends w{constructor(t){super(t);this.fired=!1}onInit(){this.isDocumentAvailable()&&(this.fired=!1,this.addDocumentListener("mousemove",t=>this.handleMouseMove(t),{passive:!0}))}onDestroy(){this.fired=!1}handleMouseMove(t){if(this.fired||t.clientY>ha)return;this.fired=!0;let i=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:i,clientY:t.clientY})}};function ln(r){if(!r)return;let e=r.classList?.length?Array.from(r.classList):void 0;return{tagName:r.tagName?r.tagName.toLowerCase():void 0,id:r.id||void 0,classes:e,role:r.getAttribute("role")??void 0,name:r.getAttribute("name")??void 0}}function W(r,e,t){return!Number.isFinite(r)||r<e?e:r>t?t:r}function ga(r){return typeof r=="string"&&r.trim().length>0}function yt(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function fo(r){let e=[],t=new Set,i=[],n=Array.isArray(r.targets)?r.targets:[];for(let a of n){let l=fa(a,t,e);l&&i.push(l)}let o=Math.max(0,yt(r.mutationDebounceMs,100)),s=Math.max(1,yt(r.maxObservedElements,500));return{enabled:r.enabled===!0,targets:i,rootMargin:ga(r.rootMargin)?r.rootMargin:"0px",observeMutations:r.observeMutations!==!1,mutationDebounceMs:o,maxObservedElements:s,warnings:e}}function fa(r,e,t){let i=typeof r?.key=="string"?r.key.trim():"";if(!i)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_KEY",message:"Viewport target ignored: empty key."}),null;if(e.has(i))return t.push({code:"BEHAVIOR_VIEWPORT_DUPLICATE_KEY",message:`Viewport target ignored: duplicate key "${i}".`}),null;let n=typeof r?.selector=="string"?r.selector.trim():"";if(!n)return t.push({code:"BEHAVIOR_VIEWPORT_EMPTY_SELECTOR",message:`Viewport target "${i}" ignored: empty selector.`}),null;e.add(i);let o=W(yt(r.enterThreshold,.5),0,1),s=W(yt(r.exitThreshold,0),0,o),a=Math.max(0,yt(r.minVisibleMs,0));return{key:i,selector:n,enterThreshold:o,exitThreshold:s,minVisibleMs:a,trackExit:r.trackExit??!0,once:r.once??!1,includeElement:r.includeElement??!1}}function Or(r,e){return`${r}::${e}`}function ya(r,e,t){return{targetKey:r,selector:e,elementId:t,active:!1,completed:!1,candidateEnteredAt:void 0,enteredAt:void 0,exitedAt:void 0,lastRatio:0,maxRatio:0,pendingTimer:null}}var Fr=class{constructor(){this.states=new Map}get(e,t){return this.states.get(Or(e,t))}set(e){this.states.set(Or(e.targetKey,e.elementId),e)}getOrCreate(e,t,i){let n=Or(e,i),o=this.states.get(n);return o||(o=ya(e,t,i),this.states.set(n,o)),o}delete(e,t){let i=Or(e,t),n=this.states.get(i);n&&this.cancelTimer(n),this.states.delete(i)}clear(){for(let e of this.states.values())this.cancelTimer(e);this.states.clear()}forEach(e){for(let[t,i]of this.states)e(i,t)}counts(){let e=0,t=0;for(let i of this.states.values())i.active&&(e+=1),i.pendingTimer!==null&&(t+=1);return{active:e,pending:t}}cancelTimer(e){e.pendingTimer!==null&&(clearTimeout(e.pendingTimer),e.pendingTimer=null)}size(){return this.states.size}};var Nr=class{constructor(e){this.elementIds=new WeakMap;this.entriesById=new Map;this.sequence=0;this.maxObservedElements=Math.max(1,e)}tryRegister(e,t){let i=this.elementIds.get(e);if(i!==void 0){let s=this.entriesById.get(i);if(s)return s.targets.add(t),{ok:!0,entry:s,isNewElement:!1}}if(this.entriesById.size>=this.maxObservedElements)return{ok:!1,reason:"limit_reached"};this.sequence+=1;let n=`vp_el_${this.sequence}`,o={elementId:n,element:e,targets:new Set([t])};return this.elementIds.set(e,n),this.entriesById.set(n,o),{ok:!0,entry:o,isNewElement:!0}}unregister(e){let t=this.elementIds.get(e);t!==void 0&&(this.elementIds.delete(e),this.entriesById.delete(t))}unregisterById(e){let t=this.entriesById.get(e);t&&this.elementIds.delete(t.element),this.entriesById.delete(e)}getByElement(e){let t=this.elementIds.get(e);return t!==void 0?this.entriesById.get(t):void 0}getById(e){return this.entriesById.get(e)}allObserved(){return Array.from(this.entriesById.values())}isObserved(e){return this.elementIds.has(e)}count(){return this.entriesById.size}isAtCapacity(){return this.entriesById.size>=this.maxObservedElements}disconnect(){this.entriesById.clear()}};function va(){return typeof IntersectionObserver<"u"}function yo(r){let e=new Set([0,1]);for(let t of r)e.add(W(t.enterThreshold,0,1)),e.add(W(t.exitThreshold,0,1));return Array.from(e).sort((t,i)=>t-i)}function vo(r,e){if(!va())return{available:!1,observer:void 0,error:"IntersectionObserver unavailable"};try{return{available:!0,observer:new IntersectionObserver(r,{root:null,rootMargin:e.rootMargin,threshold:e.thresholds}),error:void 0}}catch(t){return{available:!1,observer:void 0,error:t instanceof Error?t.message:"IntersectionObserver init failed"}}}var vt=class extends w{constructor(t,i){super(t);this.normalized=null;this.registry=null;this.stateStore=null;this.observer=null;this.observerAvailable=!1;this.mutationObserver=null;this.mutationTimer=null;this.initialized=!1;this.limitWarned=!1;this.enterCount=0;this.exitCount=0;this.signalBus=i.signalBus,this.rawConfig=i.config}onInit(){let t=fo(this.rawConfig);this.normalized=t,this.initialized=!0;for(let o of t.warnings)this.context.logger.warn(`[Pixel] ${o.code}: ${o.message}`);if(!t.enabled||t.targets.length===0||!this.isDocumentAvailable())return;this.registry=new Nr(t.maxObservedElements),this.stateStore=new Fr;let i=yo(t.targets),n=vo(o=>this.handleIntersections(o),{rootMargin:t.rootMargin,thresholds:i});if(this.observerAvailable=n.available,!n.available){this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_UNAVAILABLE: ${n.error??"IntersectionObserver unavailable"}`);return}this.observer=n.observer,this.scanAndObserve(t.targets),t.observeMutations&&typeof MutationObserver<"u"&&this.setupMutationObserver(t)}onDestroy(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.mutationObserver?.disconnect(),this.mutationObserver=null,this.observer?.disconnect(),this.observer=null,this.observerAvailable=!1,this.stateStore?.clear(),this.stateStore=null,this.registry?.disconnect(),this.registry=null,this.enterCount=0,this.exitCount=0,this.lastEventAt=void 0,this.limitWarned=!1,this.normalized=null,this.initialized=!1}getSnapshot(){let t=this.normalized,i=this.stateStore?.counts()??{active:0,pending:0},n=this.registry?.count()??0;return{enabled:t?.enabled??!1,initialized:this.initialized,available:this.observerAvailable,targetCount:t?.targets.length??0,matchedElementCount:n,observedElementCount:n,activeElementCount:i.active,pendingElementCount:i.pending,enterCount:this.enterCount,exitCount:this.exitCount,mutationObserverEnabled:this.mutationObserver!==null,maxObservedElements:t?.maxObservedElements??0,limitReached:this.limitWarned,lastEventAt:this.lastEventAt}}scanAndObserve(t){for(let i of t)this.observeTarget(i)}observeTarget(t){if(!this.registry||!this.observer||!this.isDocumentAvailable())return;let i;try{i=document.querySelectorAll(t.selector)}catch{this.context.logger.warn(`[Pixel] BEHAVIOR_VIEWPORT_INVALID_SELECTOR: target "${t.key}" has an invalid selector.`);return}i.forEach(n=>this.registerElement(n,t))}registerElement(t,i){if(!this.registry||!this.observer)return;let n=this.registry.tryRegister(t,i);if(!n.ok){this.limitWarned||(this.limitWarned=!0,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_LIMIT_REACHED: maxObservedElements reached."));return}n.isNewElement&&this.observer.observe(t)}setupMutationObserver(t){if(!this.isDocumentAvailable()||typeof MutationObserver>"u")return;let i=document.body??document.documentElement;if(i)try{this.mutationObserver=new MutationObserver(()=>{this.scheduleMutationRescan(t)}),this.mutationObserver.observe(i,{childList:!0,subtree:!0})}catch{this.mutationObserver=null,this.context.logger.warn("[Pixel] BEHAVIOR_VIEWPORT_OBSERVER_FAILED: MutationObserver init failed.")}}scheduleMutationRescan(t){this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=setTimeout(()=>{this.mutationTimer=null,this.handleMutationRescan(t)},t.mutationDebounceMs)}handleMutationRescan(t){this.registry&&(this.cleanupDisconnectedElements(),this.scanAndObserve(t.targets))}cleanupDisconnectedElements(){if(!this.registry||!this.stateStore)return;let t=this.registry.allObserved().filter(i=>!i.element.isConnected);for(let i of t){this.observer?.unobserve(i.element);for(let n of i.targets){let o=this.stateStore.get(n.key,i.elementId);o&&this.finalizeRemovedElement(o,n)}this.registry.unregister(i.element)}}finalizeRemovedElement(t,i){this.stateStore&&(this.stateStore.cancelTimer(t),t.active&&(t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,"removed")),t.active=!1,t.completed=!0,this.stateStore.delete(i.key,t.elementId))}handleIntersections(t){if(!(!this.registry||!this.stateStore))for(let i of t){let n=this.registry.getByElement(i.target);if(n)for(let o of n.targets)this.processEntry(i,n.elementId,o)}}processEntry(t,i,n){if(!this.stateStore)return;let o=this.stateStore.getOrCreate(n.key,n.selector,i);if(o.completed)return;let s=W(t.intersectionRatio,0,1);if(o.lastRatio=s,s>o.maxRatio&&(o.maxRatio=s),o.active)this.handleActiveElement(o,n,t,s);else{let a=t.isIntersecting&&s>=n.enterThreshold;this.handleCandidateEnter(o,n,a)}}handleCandidateEnter(t,i,n){if(this.stateStore){if(!n){t.candidateEnteredAt!==void 0&&(this.stateStore.cancelTimer(t),t.candidateEnteredAt=void 0);return}if(t.candidateEnteredAt===void 0){if(t.candidateEnteredAt=Date.now(),i.minVisibleMs===0){this.confirmEnter(t,i);return}t.pendingTimer=setTimeout(()=>{t.pendingTimer=null,this.confirmEnter(t,i)},i.minVisibleMs)}}}confirmEnter(t,i){t.active||t.completed||(t.active=!0,t.enteredAt=Date.now(),t.candidateEnteredAt=void 0,this.emitEnter(t,i),i.once&&!i.trackExit&&(t.completed=!0,this.finishTargetCycle(t,i)))}handleActiveElement(t,i,n,o){if(!(!n.isIntersecting||o<=i.exitThreshold))return;let a=n.isIntersecting?"threshold":"not_intersecting";this.completeCycle(t,i,a)}completeCycle(t,i,n){this.stateStore&&(this.stateStore.cancelTimer(t),t.active=!1,t.exitedAt=Date.now(),i.trackExit&&this.emitExit(t,i,n),i.once?(t.completed=!0,this.finishTargetCycle(t,i)):(t.enteredAt=void 0,t.exitedAt=void 0,t.candidateEnteredAt=void 0))}finishTargetCycle(t,i){if(this.registry){let n=this.registry.getById(t.elementId);n&&(n.targets.delete(i),n.targets.size===0&&(this.observer?.unobserve(n.element),this.registry.unregisterById(t.elementId)))}this.stateStore?.delete(i.key,t.elementId)}emitEnter(t,i){let n=t.enteredAt??Date.now(),o=W(t.lastRatio,0,1),s=this.registry?.getById(t.elementId)?.element??null;this.enterCount+=1,this.lastEventAt=n,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_ENTER","ViewportTracker",{key:i.key,elementId:t.elementId,visibilityRatio:o,enteredAt:n})),this.dispatchEngagement({type:"VIEWPORT_ENTER",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:o,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:n,minVisibleMs:i.minVisibleMs,...i.includeElement?{element:ln(s)}:{}})}emitExit(t,i,n){let o=t.enteredAt??Date.now(),s=t.exitedAt??Date.now(),a=Math.max(0,s-o),l=W(t.lastRatio,0,1),u=this.registry?.getById(t.elementId)?.element??null;this.exitCount+=1,this.lastEventAt=s,this.signalBus?.publish(this.signalBus.createSignal("VIEWPORT_EXIT","ViewportTracker",{key:i.key,elementId:t.elementId,visibilityRatio:l,enteredAt:o,exitedAt:s,visibleDurationMs:a})),this.dispatchEngagement({type:"VIEWPORT_EXIT",category:"ENGAGEMENT",key:i.key,selector:i.selector,elementId:t.elementId,visibilityRatio:l,enterThreshold:i.enterThreshold,exitThreshold:i.exitThreshold,enteredAt:o,exitedAt:s,visibleDurationMs:a,reason:n,...i.includeElement?{element:ln(u)}:{}})}};var bt=class{constructor(){this.name="behavior";this.trackers=[];this.heartbeatEngine=null;this.engagementEngine=null;this.viewportTracker=null;this.signalBus=null;this.coordinator=null;this.coordinatorActive=!1;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Behavior module already initialized");return}let{enabled:t,trackers:i}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let n=new U;this.signalBus=n;let o=ao(e.config.modules.behavior);if(o.enabled){let d=new ot(e,{config:o,signalBus:n});d.init(),this.engagementEngine=d}else this.engagementEngine=null;let s=co(e.config.modules.behavior);(s.rateLimit.enabled||s.buffer.enabled||s.stateMachine.enabled||s.sessionSummary.enabled)&&(this.coordinator||(this.coordinator=new dt(e,{config:s,getEngagement:()=>{let d=this.engagementEngine?.getSnapshot();return d?{score:d.score,peakScore:d.peakScore}:null}})),this.coordinator.init(n),this.coordinatorActive=!0);let l=[];i.scroll.enabled&&l.push(new mt(e,{signalBus:n})),i.click.enabled&&l.push(new pt(e,{signalBus:n})),i.visibility.enabled&&l.push(new ht(e,{signalBus:n})),i.idle.enabled&&l.push(new gt(e,{signalBus:n})),i.exitIntent.enabled&&l.push(new ft(e));let u=null;i.viewport.enabled&&(u=new vt(e,{signalBus:n,config:i.viewport}),l.push(u)),this.viewportTracker=u;for(let d of l)d.init();this.trackers=l;let c=uo(e.config.modules.behavior);if(c.enabled){let d=new _r(e,{config:c,signalBus:n});d.init(),this.heartbeatEngine=d}else this.heartbeatEngine=null;this.active=!0}destroy(){if(!this.active){this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null,this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null;return}this.destroyCoordinator(),this.engagementEngine?.destroy(),this.engagementEngine=null,this.heartbeatEngine?.destroy(),this.heartbeatEngine=null;for(let e=this.trackers.length-1;e>=0;e-=1)this.trackers[e]?.destroy();this.trackers=[],this.viewportTracker=null,this.signalBus?.clear(),this.signalBus=null,this.active=!1}destroyCoordinator(){this.coordinatorActive&&this.coordinator&&this.coordinator.destroy(),this.coordinatorActive=!1}getHeartbeatSnapshot(){return this.heartbeatEngine?this.heartbeatEngine.getSnapshot():null}getViewportSnapshot(){return this.viewportTracker?this.viewportTracker.getSnapshot():null}getEngagementSnapshot(){return this.engagementEngine?this.engagementEngine.getSnapshot():null}getRateLimitSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getRateLimitSnapshot()}getBufferSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getBufferSnapshot()}getStateMachineSnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getStateMachineSnapshot()}getSessionSummarySnapshot(){return!this.coordinator||!this.coordinatorActive?null:this.coordinator.getSessionSummarySnapshot()}evaluateEngagementNow(){this.engagementEngine?.evaluateNow()}flushBufferNow(){this.coordinator?.flushNow()}emitSessionSummaryNow(e="hidden"){return this.coordinator?.emitSummaryNow(e)??!1}debugPublishSignal(e,t){this.signalBus&&this.signalBus.publish(this.signalBus.createSignal(e,"debug",t))}};var E=class{constructor(e){this.active=!1;this.managedListeners=[];this.observer=null;this.context=e}init(){this.active||(this.onInit(),this.active=!0)}destroy(){this.active&&(this.onDestroy(),this.removeAllManagedListeners(),this.observer?.disconnect(),this.observer=null,this.active=!1)}isWindowAvailable(){return typeof window<"u"}isDocumentAvailable(){return typeof document<"u"}addWindowListener(e,t,i){if(!this.isWindowAvailable())return;let n=t;window.addEventListener(e,n,i),this.managedListeners.push({target:"window",type:e,handler:n,options:i})}addDocumentListener(e,t,i){if(!this.isDocumentAvailable())return;let n=t;document.addEventListener(e,n,i),this.managedListeners.push({target:"document",type:e,handler:n,options:i})}observeDom(e){this.isDocumentAvailable()&&(this.observer?.disconnect(),this.observer=new MutationObserver(()=>e()),document.body&&this.observer.observe(document.body,{childList:!0,subtree:!0}))}clearManagedTimeout(e){return e&&clearTimeout(e),null}removeAllManagedListeners(){for(let e of this.managedListeners)e.target==="window"&&this.isWindowAvailable()?window.removeEventListener(e.type,e.handler,e.options):e.target==="document"&&this.isDocumentAvailable()&&document.removeEventListener(e.type,e.handler,e.options);this.managedListeners.length=0}};function B(r,e,t){let i=t.trim().replace(/\s+/g,"-")||"unnamed";return`auto:${r}:${e}:${i}`}var Br=["email","emailaddress","customerEmail","customer_email","e-mail","email_address","emailAddress","#email","#emailaddress"],Vr=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile","phone_number","phoneNumber","phonenumber","#phone"],Ur=["name","nome","fullName","full_name","fullname","billing_name","creditcards_name","addresses_name","shipping_name","#creditcards_name","#addresses_name"],zr=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name","#first_name"],Hr=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name","#last_name"],bo=["address","street","street_address","billing_address","shipping_address","endereco","address1","address_1","billing_address1","shipping_address1","creditcards_address","addresses_address","addr","#address1","#addr","#creditcards_address","#addresses_address","#billing_address1"],So=["address2","address_2","apt","apartment","suite","complement","complemento","billing_address2","shipping_address2","addr2","#address2","#addr2","#billing_address2"],Eo=["city","cidade","billing_city","shipping_city","creditcards_city","addresses_city","#city","#creditcards_city","#addresses_city","#billing_city"],Co=["state","estado","region","billing_state","shipping_state","creditcards_state","addresses_state","state_intl","#state","#state_intl","#creditcards_state","#addresses_state","#billing_state"],xo=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip","billing_postal_code","shipping_zip","shipping_postal_code","creditcards_zip","addresses_zip","#postal_code","#zip","#creditcards_zip","#addresses_zip","#billing_postal_code"],To=["country","pais","billing_country","country_code","shipping_country","creditcards_country","addresses_country","#country","#creditcards_country","#addresses_country","#billing-country","#billing_country"];var ba=/\b(card|cardnumber|card_number|cc[-_]?number|credit[-_]?card|cvv|cvc|security(?:code)?|expir(?:y|ation)|exp(?:date|iry)?|password|senha|secret|token)\b/i;function Q(r){return typeof Element<"u"&&r instanceof Element}function L(r){return typeof HTMLFormElement<"u"&&r instanceof HTMLFormElement}function we(r){return typeof HTMLInputElement<"u"&&r instanceof HTMLInputElement}function _(r){if(r==null)return;let e=String(r).trim();return e.length>0?e:void 0}function un(r){let e=_(r);if(!e)return;let t=e.replace(/[^\d.,-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let i=t.includes(","),n=t.includes(".");i&&n?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):i&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function cn(r){let e=_(r);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function Do(r){if(we(r)&&r.type==="password")return!0;let e=[r.getAttribute("name"),r.getAttribute("id"),r.getAttribute("autocomplete"),r.getAttribute("placeholder"),r.getAttribute("aria-label")].filter(Boolean).join(" ");return ba.test(e)}function z(r,e){for(let t of e){if(!t)continue;let i=(t.startsWith("data-"),t),n=_(r.getAttribute(i));if(n)return n}}function G(r){if(!Do(r)&&(we(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement))return _(r.value)}function Sa(r){return/^[#.\[:]/.test(r)||/[\s>+~]/.test(r)}function wo(r,e){for(let t of e)if(!(!t||!Sa(t)))try{let i=r.matches(t)?r:r.querySelector(t);if(!i)continue;let n=G(i);if(n)return n}catch{}}function H(r,e,t={}){let i=o=>!(!o||t.ignoreHidden&&$r(o)||t.denyNamePattern&&Ea(o,t.denyNamePattern));for(let o of e){if(!o)continue;let s=r.querySelector(`input[name="${qr(o)}"], textarea[name="${qr(o)}"], select[name="${qr(o)}"], input[id="${qr(o)}"]`);if(s&&i(s)){let a=G(s);if(a)return a}}let n=[];if((we(r)||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)&&n.push(r),n.push(...Array.from(r.querySelectorAll("input, textarea, select"))),!t.exactOnly)for(let o of e){let s=o.toLowerCase();for(let a of n){if(!i(a)||Do(a))continue;let l=(a.getAttribute("name")??"").toLowerCase(),u=(a.getAttribute("id")??"").toLowerCase();if(!Ca(l,u,s))continue;let c=G(a);if(c)return c}}}function $r(r){return we(r)&&r.type==="hidden"}function Ea(r,e){let t=r.getAttribute("name")??"",i=r.getAttribute("id")??"";return e.test(t)||e.test(i)}function Ca(r,e,t){return t?r===t||e===t?!0:t.length<4?!1:Io(r,t)||Io(e,t):!1}function Io(r,e){if(!r)return!1;let t=0;for(;t<=r.length;){let i=r.indexOf(e,t);if(i<0)return!1;let n=i===0?"":r.charAt(i-1),o=i+e.length,s=o>=r.length?"":r.charAt(o);if(Ao(n)&&Ao(s))return!0;t=i+1}return!1}function Ao(r){return r===""||/[^a-z0-9]/.test(r)}function qr(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/["\\]/g,"\\$&")}function ke(...r){let e={};for(let t of r)if(t)for(let[i,n]of Object.entries(t))n==null||n===""||e[i]===void 0&&(e[i]=n);return e}function St(r,e){let t=new Set,i=[];for(let n of[...r??[],...e]){let o=n?.trim();!o||t.has(o)||(t.add(o),i.push(o))}return i}var xa=["data-email"],Ta=["data-phone","data-telefone"],Ia=["data-name","data-nome"],Aa=["data-first-name","data-firstname"],Da=["data-last-name","data-lastname"],wa=["data-address"],ka=["data-address2","data-apt"],Ra=["data-city"],Ma=["data-state"],Pa=["data-zip","data-postal"],_a=["data-country"],La=/\b(product|sku|offer|codename|account[_-]?id|item[_-]?id)\b/i,q=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!Q(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=L(i)?this.extractFromScope(i):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return ke(t,n,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return Q(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:zr,autocomplete:"given-name",attrs:Aa}),i=this.pick(e,{mappingKey:"lastName",defaults:Hr,autocomplete:"family-name",attrs:Da}),n=this.pick(e,{mappingKey:"name",defaults:Ur,autocomplete:"name",attrs:Ia}),o=t&&i?`${t} ${i}`:t??i,s=t&&i?o:n??o,a=this.pick(e,{mappingKey:"address",defaults:bo,autocomplete:["street-address","address-line1"],attrs:wa}),l=a&&Oa(a)?void 0:a,u=this.pick(e,{mappingKey:"address2",defaults:So,autocomplete:"address-line2",attrs:ka}),c=this.pick(e,{mappingKey:"postalCode",defaults:xo,autocomplete:"postal-code",attrs:Pa}),d=!!(l||c),m=this.pick(e,{mappingKey:"city",defaults:Eo,autocomplete:"address-level2",attrs:Ra}),h=this.pick(e,{mappingKey:"state",defaults:Co,autocomplete:"address-level1",attrs:Ma}),p=this.pick(e,{mappingKey:"country",defaults:To,autocomplete:["country-name","country"],attrs:_a});return ke({email:this.pick(e,{mappingKey:"email",defaults:Br,type:"email",autocomplete:"email",attrs:xa}),phone:this.pick(e,{mappingKey:"phone",defaults:Vr,type:"tel",autocomplete:"tel",attrs:Ta}),name:_(s),firstName:t,lastName:i,address:l,address2:u,city:d?m:void 0,state:d?h:void 0,postalCode:c,country:d?p:void 0})}pick(e,t){let i=t.type?this.readTypedInput(e,t.type):void 0,n=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],o;for(let a of n)if(o=this.readAutocomplete(e,a),o)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return i??o??(t.attrs?z(e,t.attrs):void 0)??wo(e,s)??H(e,s,{ignoreHidden:!0,denyNamePattern:La})}fieldsFor(e,t){return St(this.fieldMappings[e],t)}readTypedInput(e,t){let i=`input[type="${t}"]`,n=e.matches(i)?e:e.querySelector(i);if(!(!n||$r(n)))return G(n)}readAutocomplete(e,t){let i=t.toLowerCase(),n=[];e.matches("input, select, textarea")&&ko(e).includes(i)&&n.push(e),n.push(...Array.from(e.querySelectorAll("input, select, textarea")).filter(o=>ko(o).includes(i)));for(let o of n){if($r(o))continue;let s=G(o);if(s)return s}}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};function Oa(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function ko(r){let e=(r.getAttribute("autocomplete")??"").trim().toLowerCase();return e?e.split(/\s+/).filter(Boolean):[]}var Fa=["data-product-id","data-product","data-sku","data-item-id","data-id"],Na=["data-product-name","data-item-name"],Ba=["data-product-price","data-price","data-value","data-amount"],Va=["data-quantity","data-qty"],Ua=["data-currency"],za=["productId","product_id","sku","item_id"],Ha=["productName","product_name","item_name"],qa=["price","product_price","item_price"],$a=["quantity","qty"],Ka=["currency"],Wa=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),ve=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!Q(e))return{};let t=this.extractFromScope(e),i=e.closest("form"),n=L(i)?this.extractFromScope(i):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==i?this.extractFromScope(o):{};return ke(t,n,s)}extractFromForm(e){return L(e)?this.extractFromScope(e):{}}extractFromContainer(e){return Q(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=z(e,this.attrsFor("productId",Fa))??H(e,this.fieldsFor("productId",za),{exactOnly:!0}),i=z(e,this.attrsFor("productName",Na))??H(e,this.fieldsFor("productName",Ha),{exactOnly:!0}),n=z(e,this.attrsFor("price",Ba))??H(e,this.fieldsFor("price",qa),{exactOnly:!0}),o=z(e,this.attrsFor("quantity",Va))??H(e,this.fieldsFor("quantity",$a),{exactOnly:!0}),s=z(e,this.attrsFor("currency",Ua))??H(e,this.fieldsFor("currency",Ka),{exactOnly:!0});return ke({productId:_(t),productName:_(i),price:un(n),quantity:cn(o),currency:_(s)})}attrsFor(e,t){return St(this.attributeMappings[e],t)}fieldsFor(e,t){return St(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(Wa)??null}};var Ro="all",Mo="auto",Ga=["input","change","submit","click","auto"],Qa={email:{attrs:["data-email"],fields:[...Br],type:"email",autocomplete:"email"},phone:{attrs:["data-phone","data-telefone"],fields:[...Vr],type:"tel",autocomplete:"tel"},name:{attrs:["data-name","data-nome"],fields:[...Ur],autocomplete:"name"},firstName:{attrs:["data-first-name","data-firstname"],fields:[...zr],autocomplete:"given-name"},lastName:{attrs:["data-last-name","data-lastname"],fields:[...Hr],autocomplete:"family-name"},productId:{attrs:["data-product-id","data-product","data-sku","data-item-id","data-id"],fields:["productId","product_id","product","sku","item_id","id"]},quantity:{attrs:["data-quantity","data-qty"],fields:["quantity","qty"]}},Et=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?_o(e):null}getConfig(){return this.normalized?{...this.normalized,fields:[...this.normalized.fields]}:null}evaluate(e={}){if(!this.hasConfig||!this.normalized)return this.result({matched:!1,reason:"no_config",fields:[],filledFields:[],missingFields:[],values:{},config:null});let t=this.normalized;if(t.fields.length===0)return this.result({matched:!1,reason:"no_fields",fields:[],filledFields:[],missingFields:[],values:{},config:t});if(!this.isTriggerCompatible(t.trigger,e.trigger))return this.result({matched:!1,reason:"trigger_mismatch",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let i=this.resolveScope(e,t);if(i==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!i)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let n={},o=[],s=[];for(let u of t.fields){let c=Xa(i,u);c?(n[u]=c,o.push(u)):s.push(u)}let a=this.matchesRequirement(t,o.length,t.fields.length),l="matched";return a||(l=t.minRequired!=null?"min_required_not_met":"missing_required_fields"),this.result({matched:a,reason:l,fields:[...t.fields],filledFields:o,missingFields:s,values:n,config:t})}matchesRequirement(e,t,i){if(e.minRequired!=null){let n=Math.max(0,e.minRequired);return t>=n}return e.mode==="any"?t>=1:t===i&&i>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){let i=Q(e.element)?e.element:null;if(t.formSelector){let n=Ya(t.formSelector);return n?L(e.form)?n===e.form||n.contains(e.form)?n:null:i?n===i||n.contains(i)?n:null:n:"missing_form_selector"}if(L(e.form))return e.form;if(i){let n=ja(i);if(n)return n;let o=i.closest("form");if(L(o))return o}return Q(e.container)?e.container:i||null}result(e){return{...e,config:e.config?{...e.config,fields:[...e.config.fields]}:null,fields:[...e.fields],filledFields:[...e.filledFields],missingFields:[...e.missingFields],values:{...e.values}}}};function _o(r){if(r==null)return null;if(Array.isArray(r))return{fields:Po(r),mode:Ro,trigger:Mo};if(typeof r!="object")return null;let e=Po(r.fields??[]),t=r.mode==="any"||r.mode==="all"?r.mode:Ro,i=Ga.includes(r.trigger)?r.trigger:Mo,n={fields:e,mode:t,trigger:i};typeof r.minRequired=="number"&&Number.isFinite(r.minRequired)&&(n.minRequired=r.minRequired);let o=_(r.formSelector);return o&&(n.formSelector=o),typeof r.debounceMs=="number"&&Number.isFinite(r.debounceMs)&&(n.debounceMs=r.debounceMs),typeof r.fireOnce=="boolean"&&(n.fireOnce=r.fireOnce),n}function Po(r){let e=new Set,t=[];for(let i of r){let n=typeof i=="string"?i.trim():"";!n||e.has(n)||(e.add(n),t.push(n))}return t}function ja(r){if(we(r)||r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement){let e=r.form;return L(e)?e:null}return null}function Ya(r){if(typeof document>"u")return null;try{return document.querySelector(r)}catch{return null}}function Xa(r,e){let t=e.trim();if(!t)return;let i=Qa[t];if(i?.type){let s=Za(r,i.type);if(s)return s}if(i?.autocomplete){let s=Ja(r,i.autocomplete);if(s)return s}if(i){let s=z(r,i.attrs);if(s)return s;let a=H(r,i.fields);if(a)return a}let n=el(t),o=z(r,[`data-${n}`,`data-${t}`]);return o||H(r,[t,n])}function Za(r,e){let t=`input[type="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?G(i):void 0}catch{return}}function Ja(r,e){let t=`input[autocomplete="${e}"]`;try{let i=r.matches(t)?r:r.querySelector(t);return i?G(i):void 0}catch{return}}function el(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var Re=class{constructor(e=[],t={}){this.productsById=new Map;this.productsBySku=new Map;this.orderedIds=[];this.indexProducts(e??[],t.defaultCurrency)}list(){return this.orderedIds.map(e=>this.cloneProduct(this.productsById.get(e)))}getById(e){if(!e)return null;let t=this.productsById.get(e);return t?this.cloneProduct(t):null}getBySku(e){if(!e)return null;let t=this.productsBySku.get(e);return t?this.cloneProduct(t):null}hasProduct(e){return!!e&&this.productsById.has(e)}getSnapshot(){let e=this.list();return{products:e,count:e.length}}indexProducts(e,t){for(let i of e){if(!i||typeof i!="object")continue;let n=typeof i.id=="string"?i.id.trim():"";if(!n||this.productsById.has(n))continue;let o=this.normalizeProduct(i,n,t);this.productsById.set(n,o),this.orderedIds.push(n);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,i){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():i,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...n!==void 0?{sku:n}:{},...o!==void 0?{currency:o}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var Me=class{constructor(e=[],t={}){this.itemsByProductId=new Map;this.allowDynamicItems=t.allowDynamicItems!==!1,this.seed(e??[])}getSelectedItems(){return Array.from(this.itemsByProductId.values()).map(e=>this.cloneItem(e))}hasItem(e){return!!e&&this.itemsByProductId.has(e)}getItem(e){if(!e)return null;let t=this.itemsByProductId.get(e);return t?this.cloneItem(t):null}upsertItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;if(e.selected===!1){this.itemsByProductId.delete(t);return}let i=this.normalizeQuantity(e.quantity);if(i<=0){this.itemsByProductId.delete(t);return}if(!this.itemsByProductId.has(t)&&!this.allowDynamicItems)return;let o=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:o?.metadata?{...o.metadata}:void 0,a={...o,...e,productId:t,quantity:i,selected:!0,...s?{metadata:s}:{}};this.itemsByProductId.set(t,a)}removeItem(e){e&&this.itemsByProductId.delete(e)}updateQuantity(e,t){if(!e||!this.itemsByProductId.has(e))return;let i=this.normalizeQuantity(t);if(i<=0){this.itemsByProductId.delete(e);return}let n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,quantity:i})}clear(){this.itemsByProductId.clear()}getSnapshot(){let e=this.getSelectedItems();return{selectedItems:e,count:e.length}}seed(e){for(let t of e)this.seedItem(t)}seedItem(e){if(!e||typeof e!="object")return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t||e.selected===!1)return;let i=this.normalizeQuantity(e.quantity);i<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:i,selected:!0,...e.metadata?{metadata:{...e.metadata}}:{}})}normalizeQuantity(e){return e==null||typeof e!="number"||!Number.isFinite(e)?1:e}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var oe=class{calculate(e){let i=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of i)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(i),o=this.resolveCurrency(e,i);return{items:i,...n!==void 0?{value:n}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,i=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let o=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*o,i=!0}return i?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let i of t)if(typeof i.currency=="string"&&i.currency.trim())return i.currency.trim();if(typeof e.defaultCurrency=="string"&&e.defaultCurrency.trim())return e.defaultCurrency.trim()}cloneItem(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var se=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=rl(e.defaultCurrency),this.calculateValueFrom=de(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},i=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",o=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",a=y(t.priceId)??y(t.productId)??y(i.productId)??(s?this.lookupIdBySku(y(t.sku)??y(i.sku)):void 0),l=!a&&o?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let u=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(y(t.sku)??y(i.sku)):null,c=a??u?.id,d=o&&c?this.state.getItem(c)??l:null;if(n==="catalog"&&!c&&!u)return{data:{...t}};let m=y(t.productName)??y(i.productName)??u?.name,h=M(t.price)??M(i.price)??(o?M(d?.price):void 0)??u?.price,p=M(t.quantity)??M(i.quantity)??(o?M(d?.quantity):void 0)??u?.quantity??1,f=y(t.currency)??y(i.currency)??(o?y(d?.currency):void 0)??u?.currency??this.defaultCurrency,b=tl(u,{priceId:y(t.priceId),productId:c,offerId:y(t.offerId),id:y(t.id)}),S={};b.id&&(S.id=b.id),b.priceId&&(S.priceId=b.priceId),b.productId&&(S.productId=b.productId),b.offerId&&(S.offerId=b.offerId),m&&(S.productName=m),h!==void 0&&(S.price=h),f&&(S.currency=f),p!==void 0&&(S.quantity=p);for(let[O,$e]of Object.entries(t))$e!==void 0&&(O in S||(S[O]=$e));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(i=>this.catalog.getById(i.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},i=e.extractedProduct??{},n=y(t.productId)??y(i.productId)??this.lookupIdBySku(y(t.sku)??y(i.sku)),o=n?this.catalog.getById(n):null,s=n??o?.id,a=s?this.state.getItem(s):null,l=M(t.quantity)??M(i.quantity)??M(a?.quantity)??1,u={};s&&(u.productId=s),l!==void 0&&(u.quantity=l);for(let[c,d]of Object.entries(t))d!==void 0&&(c in u||(u[c]=d));return{data:u}}resolveCheckoutLike(e,t){let i={...e.payload??{}},n=M(i.value),o=y(i.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),u=l.map(b=>this.toPixelItem(b)),c=a!=="catalog"&&this.calculateValueFrom!=="manual",d=n===void 0&&c,m=this.calculator.calculate({items:l,value:d?void 0:n,currency:o,defaultCurrency:this.defaultCurrency}),h=n!==void 0?n:c?m.value:void 0,p=o??m.currency??this.defaultCurrency,f={...i};return u.length>0?f.items=u:s===null&&delete f.items,h!==void 0?f.value=h:delete f.value,p&&(f.currency=p),{data:f,items:m.items,...h!==void 0?{value:h}:{},...p?{currency:p}:{}}}resolveViewContent(e){let t={...e.payload??{}},i=e.enrichmentSource??"event_or_cart";if(i==="cart"||i==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:i}),o=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:i},!1),s={...t},a=y(t.contentId)??y(n.data.productId)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].id=="string"?o.data.items[0].id:void 0),l=y(t.contentName)??y(n.data.productName)??(Array.isArray(o.data.items)&&o.data.items[0]&&typeof o.data.items[0].name=="string"?o.data.items[0].name:void 0);return a&&(s.contentId=a),l&&(s.contentName=l),M(t.value)===void 0&&o.value!==void 0&&(s.value=o.value),!y(t.currency)&&o.currency&&(s.currency=o.currency),t.items===void 0&&Array.isArray(o.data.items)&&(s.items=o.data.items),{data:s,...o.value!==void 0?{value:o.value}:{},...o.currency?{currency:o.currency}:{},items:o.items}}if(i==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),o={...t};return n.data.productId&&!y(t.contentId)&&(o.contentId=n.data.productId),n.data.productName&&!y(t.contentName)&&(o.contentName=n.data.productName),n.data.price!==void 0&&M(t.value)===void 0&&(o.value=n.data.price),n.data.currency&&!y(t.currency)&&(o.currency=n.data.currency),{data:o}}return{data:t}}readPayloadItems(e){if(e.items)return e.items.map(i=>this.normalizeLooseItem(i));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(i=>this.normalizeLooseItem(i&&typeof i=="object"?i:{}))}resolveItemsSource(e,t){if(e!==null)return e.map(i=>this.enrichItem(i));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(i=>this.enrichItem({productId:i.productId,price:i.price,quantity:i.quantity,currency:i.currency}));if(this.calculateValueFrom==="catalog"){let i=this.state.getSelectedItems();return i.length>0?i.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,i=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??i?.id;return{...e,...n?{productId:n}:{},productName:e.productName??i?.name,sku:e.sku??i?.sku,price:e.price??i?.price,quantity:e.quantity??i?.quantity??1,currency:e.currency??i?.currency??this.defaultCurrency,category:e.category??i?.category,variant:e.variant??i?.variant,brand:e.brand??i?.brand,type:e.type??i?.type,metadata:e.metadata??i?.metadata}}toPixelItem(e){return{...e.productId?{id:e.productId}:{},...e.productName?{name:e.productName}:{},...e.category?{category:e.category}:{},...e.price!==void 0?{price:e.price}:{},...e.quantity!==void 0?{quantity:e.quantity}:{}}}normalizeLooseItem(e){return{productId:y(e.productId)??y(e.id),sku:y(e.sku),productName:y(e.productName)??y(e.name),price:M(e.price),quantity:M(e.quantity),currency:y(e.currency),category:y(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function tl(r,e){let t=r?.metadata??{},i=y(t.priceId),n=y(t.productId),o=y(t.offerId),s=e.priceId??i;if(!s){let a=e.productId??r?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:o??e.offerId??s}}function y(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function M(r){if(!(typeof r!="number"||!Number.isFinite(r)))return r}function rl(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}var Pe=class{constructor(e){this.config={...te,...e,catalog:{products:e?.catalog?.products??[]},cart:{...te.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...Te,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new Re(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new Me(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new se({catalog:this.catalog,state:this.state,calculator:new oe,defaultCurrency:this.config.currency,calculateValueFrom:de(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],i=Te[e];return{enabled:t?.enabled??i.enabled,source:t?.source??i.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,i={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:i,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),i=t.data.items??[],n=i[0],o=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&i.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...i.length>0?{items:i}:{},...o?{contentId:o}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return de(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function il(r){return r.trim().replace(/\s+/g," ")}function Lo(r,e){let t=il(r);return e?t:t.toLowerCase()}function Oo(r,e){let t=r.textContent;if(t==null)return!1;let i=e.caseSensitive===!0,n=Lo(t,i),o=Lo(e.value,i);return o?e.exact===!0?n===o:n.includes(o):!1}function dn(r,e){if(!Oo(r,e))return!1;let t=r.querySelectorAll("*");for(let i=0;i<t.length;i+=1){let n=t[i];if(n&&Oo(n,e))return!1}return!0}function No(r,e){if(typeof document>"u")return[];let t=e??document;if(r.closest)try{let i=[];t instanceof Element&&t.matches(r.closest)&&i.push(t),i.push(...Array.from(t.querySelectorAll(r.closest)));let n=[];for(let o of i)n.push(...Fo(o,r));return Array.from(new Set(n))}catch{return[]}return Fo(t,r)}function Fo(r,e){let t=[],i=Array.from(r.querySelectorAll("*"));r instanceof Element&&i.unshift(r);for(let n of i)dn(n,e)&&t.push(n);return t}var nl={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},$=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let i=Array.isArray(e)?e:[e],n=[];for(let o of i){let s=this.normalizeInput(o,t);s&&n.push(s)}return n}queryAll(e,t="css",i){if(typeof document>"u")return[];let n=i??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,n));return Array.from(new Set(o))}matches(e,t,i="css"){for(let n of this.normalize(t,i))if(this.matchesNormalized(e,n))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let i=e.trim();if(!i)return null;let n=this.parsePrefix(i);return n?this.fromDescriptor({type:n.type,value:n.value}):this.fromDescriptor({type:t,value:i})}fromDescriptor(e){let t=e.value?.trim();return t?{type:e.type,value:t,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest}:null}parsePrefix(e){let t=e.indexOf(":");if(t<=0)return null;let i=e.slice(0,t).toLowerCase(),n=nl[i];if(!n)return null;let o=e.slice(t+1).trim();return o?{type:n,value:o}:null}queryNormalized(e,t){if(e.type==="text")return No({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let i=this.toCssSelector(e);if(!i)return[];try{let n=Array.from(t.querySelectorAll(i));return e.closest?n.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):n}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${i}`,n),[]}}matchesNormalized(e,t){if(t.closest)try{if(e.closest(t.closest)==null)return!1}catch{return this.logger?.debug(`[SelectorResolver] Invalid closest selector ignored: ${t.closest}`),!1}if(t.type==="text")return dn(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let i=this.toCssSelector(t);if(!i)return!1;try{return e.matches(i)}catch(n){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${i}`,n),!1}}toCssSelector(e){if(e.type==="text")return null;let{value:t}=e;if(t.startsWith("[")||t.startsWith(".")||t.startsWith("#"))return t;switch(e.type){case"id":return`#${Bo(t)}`;case"class":return`.${Bo(t)}`;case"attribute":return`[data-track="${ol(t)}"]`;case"css":return t;default:return t}}};function Bo(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function ol(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var Kr=class extends E{constructor(t,i,n){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=i,this.options=n;let{source:o}=n;this.formEvaluator=new Et(o.selectorForm),this.selectorResolver=new $(t.logger),this.hasSelector=this.selectorResolver.hasEntries(o.selector),this.selectorType=sl(o),this.origin=n.origin??B("form",n.eventType,o.name);let s=t.services.commerce.config;this.customerExtractor=new q({fieldMappings:re(s?.customer,s?.mappings?.fields)}),this.productExtractor=new ve({attributeMappings:s?.mappings?.attributes,fieldMappings:s?.mappings?.fields});let a=this.formEvaluator.getConfig(),l=o.debounceMs,u=a?.debounceMs;this.debounceMs=typeof l=="number"&&l>0?l:typeof u=="number"&&u>0?u:0,this.fireOnce=o.fireOnce===!0||a?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType}:${this.options.source.name})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",i=this.resolveDomEvents(t);for(let n of i)this.addDocumentListener(n,o=>this.handleDomEvent(o,n),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,i){if(this.destroyed||this.fireOnce&&this.hasFired)return;let n=i,o=t.target instanceof Element?t.target:null;if(!this.isEventInScope(o,n))return;let s=this.formEvaluator.evaluate({element:o,trigger:n});if(!s.matched){this.context.logger.debug(`[ConfiguredFormDetector] ${this.options.eventType} skipped: ${s.reason}`);return}let a=this.buildPayload(o);a!==null&&this.scheduleTrack(a)}isEventInScope(t,i){if(this.hasSelector&&!this.matchesSelector(t))return!1;let n=this.formEvaluator.getConfig()?.formSelector;if(n&&typeof document<"u")try{let o=document.querySelector(n);if(!o)return!1;if(!t)return i!=="click";if(o!==t&&!o.contains(t))return!1}catch{return!1}return!0}matchesSelector(t){if(!t||!this.options.source.selector)return!1;let i=t;for(;i&&i!==document.body;){if(this.selectorResolver.matches(i,this.options.source.selector,this.selectorType))return!0;i=i.parentElement}return!1}resolveCustomerRoot(t){let i=this.formEvaluator.getConfig()?.formSelector;if(i&&typeof document<"u")try{let n=document.querySelector(i);if(n)return n}catch{}return t}buildPayload(t){let{eventType:i}=this.options;if(i==="LEAD"){let n=this.resolveCustomerRoot(t),o=L(n)?this.customerExtractor.extractFromForm(n):this.customerExtractor.extractFromElement(n);return!o.email&&!o.phone&&!o.name?(this.context.logger.debug("[ConfiguredFormDetector] LEAD skipped: no email/phone/name"),null):{...o.email?{email:o.email}:{},...o.phone?{phone:o.phone}:{},...o.name?{name:o.name}:{}}}if(i==="ADD_TO_CART"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}return{}}scheduleTrack(t){if(this.debounceMs<=0){this.track(t);return}this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,!this.destroyed&&this.track(t)},this.debounceMs)}track(t){this.destroyed||this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,t,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};function sl(r){return r.selectorType??"css"}var al=new Set(["id","priceId","productId","offerId","priceCode","productName","price","currency","quantity"]),ll=new Set(["id","priceId","productId","priceCode","quantity"]),ul=new Set(["id","priceId","productId","offerId","contentId","priceCode","value","price","currency"]),cl=new Set(["email","phone","name"]),dl=new Set(["value","currency"]);function v(r){if(typeof r=="string"&&r.trim()!=="")return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}function _e(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let e=r.trim();if(!/^-?\d+(\.\d+)?$/.test(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0}}function Le(r,e){return Object.keys(r).filter(t=>!e.has(t))}function Wr(r){switch(r){case"ADD_TO_CART":case"REMOVE_FROM_CART":case"VIEW_CONTENT":case"SEARCH":case"LEAD":case"INITIATE_CHECKOUT":return!0;case"ADD_PAYMENT_INFO":case"PURCHASE":return!1;default:return!1}}function Vo(r,e){switch(r){case"ADD_TO_CART":{let t=Le(e,al),i=v(e.priceId)??v(e.priceCode),n=v(e.productId)??i,o=v(e.offerId),s=v(e.id)??i,a=v(e.productName),l=_e(e.price),u=v(e.currency),c=_e(e.quantity);return!n&&!i?{ok:!1,reason:"ADD_TO_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...s?{id:s}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...o?{offerId:o}:{},...a?{productName:a}:{},...l!=null?{price:l}:{},...u?{currency:u}:{},...c!=null?{quantity:c}:{}},...t.length?{unknownKeys:t}:{}}}case"REMOVE_FROM_CART":{let t=Le(e,ll),i=v(e.priceId)??v(e.priceCode),n=v(e.productId)??i,o=v(e.id)??i,s=_e(e.quantity);return!n&&!i?{ok:!1,reason:"REMOVE_FROM_CART link source requires priceId or productId",unknownKeys:t}:{ok:!0,data:{...o?{id:o}:{},...i?{priceId:i}:{},...n?{productId:n}:{},...s!=null?{quantity:s}:{}},...t.length?{unknownKeys:t}:{}}}case"VIEW_CONTENT":{let t=Le(e,ul),i=v(e.contentId),n=v(e.productId),o=v(e.priceId)??v(e.priceCode),s=v(e.offerId);if(i&&n&&i!==n&&!o)return{ok:!1,reason:"VIEW_CONTENT contentId/productId conflict",unknownKeys:t};let a=o??i??n??v(e.id);if(!a)return{ok:!1,reason:"VIEW_CONTENT requires priceId, contentId, or productId",unknownKeys:t};let l=_e(e.value)??_e(e.price),u=v(e.currency);return{ok:!0,data:{...o?{id:v(e.id)??o,priceId:o}:{},contentId:i??a,productId:n??a,...s?{offerId:s}:{},...l!=null?{value:l}:{},...u?{currency:u}:{}},...t.length?{unknownKeys:t}:{}}}case"SEARCH":{let t=v(e.query);return t?{ok:!0,data:{query:t},unknownKeys:Le(e,new Set(["query"]))}:{ok:!1,reason:"SEARCH requires query"}}case"LEAD":{let t=Le(e,cl),i=v(e.email),n=v(e.phone),o=v(e.name);return!i&&!n&&!o?{ok:!1,reason:"LEAD requires email, phone, or name",unknownKeys:t}:{ok:!0,data:{...i?{email:i}:{},...n?{phone:n}:{},...o?{name:o}:{}},...t.length?{unknownKeys:t}:{}}}case"INITIATE_CHECKOUT":{let t=Le(e,dl),i=_e(e.value),n=v(e.currency);return{ok:!0,data:{...i!=null?{value:i}:{},...n?{currency:n}:{}},...t.length?{unknownKeys:t}:{}}}case"ADD_PAYMENT_INFO":return{ok:!1,reason:"link source does not support ADD_PAYMENT_INFO"};case"PURCHASE":return{ok:!1,reason:"link source does not support PURCHASE in this stage"};default:return{ok:!1,reason:`unsupported event: ${r}`}}}var Oe=Object.freeze({});function C(r){if(!r||r==="/")return"/";let e=r.startsWith("/")?r:`/${r}`;return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function ml(r){try{return decodeURIComponent(r)}catch{return r}}function Uo(r,e){let t=e.replace(/^\/+|\/+$/g,"");if(!t)return!1;if(r===t)return!0;if(!r.startsWith(t))return!1;if(/[^a-zA-Z0-9]$/.test(t))return!0;let i=r.charAt(t.length);return!!(i>="0"&&i<="9"||i==="_"&&/\d/.test(r.slice(t.length+1)))}function mn(r,e){let t=C(r).split("/").filter(Boolean).map(ml),i=C(e).split("/").filter(Boolean);if(t.length!==i.length)return null;let n=Object.create(null),o=new Set;for(let s=0;s<i.length;s+=1){let a=i[s],l=t[s];if(a.startsWith(":")){let u=a.slice(1);if(!u||o.has(u)||u==="__proto__"||u==="constructor"||u==="prototype"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(u))return null;o.add(u),n[u]=l;continue}if(a!==l)return null}return n}function zo(r,e,t){return t?r===e:r.toLowerCase()===e.toLowerCase()}function pl(r,e,t){return t?r.startsWith(e):r.toLowerCase().startsWith(e.toLowerCase())}function hl(r,e){let t=r.get(e.key),i="caseSensitive"in e&&e.caseSensitive===!0;switch(e.operator){case"exists":return t!==null&&t!=="";case"absent":return t===null||t==="";case"equals":return t===null?!1:zo(t,e.value,i);case"starts_with":return t===null?!1:pl(t,e.value,i);case"one_of":return t===null?!1:e.value.some(n=>zo(t,n,i));default:return!1}}function Ho(r,e){if(e.protocols?.length){if(!e.protocols.includes(r.protocol))return{matched:!1,pathParams:Oe}}else if(r.protocol!=="http:"&&r.protocol!=="https:")return{matched:!1,pathParams:Oe};if(e.origins?.length&&!e.origins.some(s=>s===r.origin))return{matched:!1,pathParams:Oe};if(e.hostnames?.length){let o=r.hostname.toLowerCase();if(!e.hostnames.some(a=>a.toLowerCase()===o))return{matched:!1,pathParams:Oe}}let t=Object.create(null),i,n=e.path;if(n){let o=C(r.pathname);if(n.template){let s=mn(o,n.template);s&&(t=s,i={type:"template",pattern:C(n.template)})}if(!i&&n.exact?.length){let s=n.exact.find(a=>C(a)===o);s!==void 0&&(i={type:"exact",pattern:C(s)})}if(!i&&n.prefixes?.length){let s=n.prefixes.find(a=>{let l=C(a);if(l==="/"||o===l||o.startsWith(`${l}/`)||/[^a-zA-Z0-9/]$/.test(l)&&o.startsWith(l))return!0;let u=l.replace(/^\//,""),c=o.split("/").filter(Boolean)[0]??"";return!!(o.startsWith(l)&&Uo(c,u))});s!==void 0&&(i={type:"prefix",pattern:C(s)})}if(!i&&n.segmentPrefixes?.length){let s=o.split("/").filter(Boolean),a=n.segmentPrefixes.find(l=>s.some(u=>Uo(u,l)));a!==void 0&&(i={type:"prefix",pattern:`/${a.replace(/^\/+|\/+$/g,"")}`})}if(!i)return{matched:!1,pathParams:Oe}}if(e.query?.conditions?.length){let o=e.query.mode??"all",s=e.query.conditions.map(l=>hl(r.searchParams,l));if(!(o==="any"?s.some(Boolean):s.every(Boolean)))return{matched:!1,pathParams:Oe}}return{matched:!0,pathParams:Object.freeze({...t}),...i?{matchedPath:i}:{}}}function qo(r){if(!r)return null;if(r.type==="prefix"){let e=C(r.pattern);return e==="/"?"/:redacted":`${e}/:redacted`}if(r.type==="exact"){let e=C(r.pattern).split("/").filter(Boolean);return e.length===0?"/":`/${e.map(()=>":redacted").join("/")}`}return r.pattern}function gl(r){return r===void 0||typeof r=="string"&&r.trim()===""}function fl(r){return C(r).split("/").filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}})}function yl(r){return r.replace(/\.html?$/i,"")}function vl(r){if(r==null)return;let e=r.replace(/\s+/g," ").trim();return e===""?void 0:e}function $o(r,e){if(!(r instanceof HTMLElement))return;let t=r.dataset[e];if(t!==void 0)return t.trim()===""?void 0:t}function Ko(r,e){let t=r.getAttribute(e);if(t!==null)return t.trim()===""?void 0:t}function bl(r,e){switch(r.source){case"query":{let t=e.url.searchParams.get(r.key);return t===null?void 0:t}case"pathParam":{let t=e.pathParams[r.key];return t===void 0?void 0:t}case"pathSegment":{let t=fl(e.url.pathname),i=r.index;if(!Number.isInteger(i)||(i<0&&(i=t.length+i),i<0||i>=t.length))return;let n=t[i];return n===void 0?void 0:yl(n)}case"attribute":return Ko(e.target,r.name)??Ko(e.anchor,r.name);case"dataset":return $o(e.target,r.key)??$o(e.anchor,r.key);case"static":return r.value;case"href":return e.url.href;case"origin":return e.url.origin;case"hostname":return e.url.hostname;case"pathname":return C(e.url.pathname);case"text":return vl(e.anchor.textContent);default:return}}function Sl(r,e){switch(e){case"trim":return typeof r=="string"?r.trim():void 0;case"lowercase":return typeof r=="string"?r.toLowerCase():void 0;case"uppercase":return typeof r=="string"?r.toUpperCase():void 0;case"number":{if(typeof r=="number")return Number.isFinite(r)?r:void 0;if(typeof r=="string"){let t=r.trim();if(t===""||!/^-?\d+(\.\d+)?$/.test(t))return;let i=Number(t);return Number.isFinite(i)?i:void 0}return}default:return}}function El(r,e){let t=Array.isArray(r.from)?r.from:[r.from],i=!1;for(let n of t){let o=bl(n,e);if(gl(o))continue;if(!r.transform)return{value:o,transformFailed:!1};let s=Sl(o,r.transform);if(s===void 0){i=!0;continue}if(!(typeof s=="string"&&s.trim()===""))return{value:s,transformFailed:!1}}return{value:void 0,transformFailed:i}}function Wo(r,e){if(!r||Object.keys(r).length===0)return{valid:!0,values:Object.freeze({}),missingRequired:Object.freeze([])};let t=Object.create(null),i=[];for(let[n,o]of Object.entries(r)){if(n==="__proto__"||n==="constructor"||n==="prototype")continue;let{value:s}=El(o,e);if(s!==void 0){t[n]=s;continue}o.required===!0&&i.push(n)}return{valid:i.length===0,values:Object.freeze(t),missingRequired:Object.freeze(i)}}var Cl=50,xl=50,pn=50,Tl=20,Il=30,Al=10,Dl=50,wl=128,kl=2048,Rl=new Set(["__proto__","constructor","prototype"]),jo=/^[A-Za-z_][A-Za-z0-9_]*$/,Ml=new Set(["trim","lowercase","uppercase","number"]);function g(r){return{ok:!1,reason:r}}function K(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Gr(r){return!Rl.has(r)}function k(r){return typeof r=="string"&&r.trim().length>0}function I(r,e=kl){return typeof r=="string"&&r.length<=e}function Pl(r){return!r||r.length>253||r.includes("/")||r.includes(" ")||r.includes(":")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)}function Go(r){return typeof r!="number"||!Number.isFinite(r)||r<0?void 0:Math.min(r,6e4)}function _l(r){try{let e=new URL(r);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username!==""||e.password!==""||e.pathname!=="/"&&e.pathname!==""||e.search!==""||e.hash!==""?null:e.origin}catch{return null}}function Qo(r){if(typeof r=="string")return I(r)?r:null;if(!K(r)||!k(r.type)||!k(r.value)||!I(r.value))return null;let e=r.type;return e!=="css"&&e!=="id"&&e!=="class"&&e!=="attribute"&&e!=="text"?null:{type:e,value:r.value,...r.exact===!0?{exact:!0}:{},...r.caseSensitive===!0?{caseSensitive:!0}:{},...typeof r.closest=="string"&&I(r.closest)?{closest:r.closest}:{}}}function Ll(r){if(typeof r=="string")return I(r)?r:null;if(Array.isArray(r)){if(r.length===0)return null;let e=[];for(let t of r){let i=Qo(t);if(!i)return null;e.push(i)}return e}return Qo(r)}function Ol(r){let e=C(r).split("/").filter(Boolean),t=new Set;for(let i of e){if(!i.startsWith(":"))continue;let n=i.slice(1);if(!n)return"path.template has empty param name";if(!jo.test(n))return`path.template param name is invalid: ${n}`;if(!Gr(n))return`path.template param name is reserved: ${n}`;if(t.has(n))return`path.template has duplicate param: ${n}`;t.add(n)}return mn(r.replace(/:[^/]+/g,"x"),r),null}function Fl(r){if(!K(r)||!k(r.key)||!I(r.key))return null;let e=r.key.trim();if(!Gr(e))return null;let t=r.operator;if(t==="exists"||t==="absent")return{key:e,operator:t};if(t==="equals"||t==="starts_with")return typeof r.value!="string"||!I(r.value)?null:{key:e,operator:t,value:r.value,...r.caseSensitive===!0?{caseSensitive:!0}:{}};if(t==="one_of"){if(!Array.isArray(r.value)||r.value.length===0||r.value.length>Dl)return null;let i=r.value.filter(n=>typeof n=="string"&&I(n));return i.length===0?null:{key:e,operator:"one_of",value:[...i],...r.caseSensitive===!0?{caseSensitive:!0}:{}}}return null}function Nl(r,e){if(!K(r))return null;let t=r.source;if(typeof t!="string")return null;switch(t){case"query":return k(r.key)&&I(r.key)?{source:"query",key:r.key.trim()}:null;case"pathParam":if(!e||!k(r.key)||!I(r.key))return null;{let i=r.key.trim();return!jo.test(i)||!Gr(i)?null:{source:"pathParam",key:i}}case"pathSegment":return typeof r.index!="number"||!Number.isInteger(r.index)||r.index<-32||r.index>64?null:{source:"pathSegment",index:r.index};case"attribute":return k(r.name)&&I(r.name)?{source:"attribute",name:r.name.trim()}:null;case"dataset":return k(r.key)&&I(r.key)?{source:"dataset",key:r.key.trim()}:null;case"static":{let i=r.value;return i===null||typeof i=="boolean"?{source:"static",value:i}:typeof i=="string"?I(i)?{source:"static",value:i}:null:typeof i=="number"&&Number.isFinite(i)?{source:"static",value:i}:null}case"href":case"origin":case"hostname":case"pathname":case"text":return{source:t};default:return null}}function Bl(r,e){if(!K(r)||r.from==null)return null;let t=Array.isArray(r.from)?r.from:[r.from];if(t.length===0||t.length>Al)return null;let i=[];for(let o of t){let s=Nl(o,e);if(!s)return null;i.push(s)}let n=r.transform;return n!==void 0&&(typeof n!="string"||!Ml.has(n))?null:{from:i.length===1?i[0]:i,...r.required===!0?{required:!0}:{},...typeof n=="string"?{transform:n}:{}}}function Vl(r){return!!(r.protocols?.length||r.origins?.length||r.hostnames?.length||r.path?.exact?.length||r.path?.prefixes?.length||r.path?.segmentPrefixes?.length||r.path?.template||r.query?.conditions?.length)}function Ul(r){if(!K(r))return g("source must be an object");if(!k(r.name))return g("name is required");if(r.name.trim().length>wl)return g("name exceeds defensive limit");if(r.type!=="link")return g("type must be link");if(r.trigger!==void 0&&r.trigger!=="click")return g("trigger must be click when provided");if(!K(r.match))return g("match is required");let e=r.match,t={};if(e.protocols!==void 0){if(!Array.isArray(e.protocols)||e.protocols.length===0)return g("protocols must be a non-empty array when provided");let u=[];for(let c of e.protocols){if(c!=="http:"&&c!=="https:")return g("protocols only allow http: and https:");u.includes(c)||u.push(c)}t.protocols=u}if(e.origins!==void 0){if(!Array.isArray(e.origins)||e.origins.length===0)return g("origins must be a non-empty array when provided");if(e.origins.length>Cl)return g("origins exceeds defensive limit");let u=[];for(let c of e.origins){if(!k(c)||!I(c))return g("origin entries must be non-empty");let d=_l(c.trim());if(!d)return g("origin must be protocol+host[+port] only (no path/query/hash/userinfo)");u.includes(d)||u.push(d)}t.origins=u}if(e.hostnames!==void 0){if(!Array.isArray(e.hostnames)||e.hostnames.length===0)return g("hostnames must be a non-empty array when provided");if(e.hostnames.length>xl)return g("hostnames exceeds defensive limit");let u=[];for(let c of e.hostnames){if(!k(c))return g("hostname entries must be non-empty");let d=c.trim().toLowerCase();if(!Pl(d))return g("hostname is invalid");u.includes(d)||u.push(d)}t.hostnames=u}if(e.path!==void 0){if(!K(e.path))return g("path must be an object when provided");let u={};if(e.path.exact!==void 0){if(!Array.isArray(e.path.exact)||e.path.exact.length===0)return g("path.exact must be non-empty when provided");if(e.path.exact.length>pn)return g("path.exact exceeds defensive limit");if(u.exact=e.path.exact.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),u.exact.length===0)return g("path.exact has no valid entries")}if(e.path.prefixes!==void 0){if(!Array.isArray(e.path.prefixes)||e.path.prefixes.length===0)return g("path.prefixes must be non-empty when provided");if(e.path.prefixes.length>pn)return g("path.prefixes exceeds defensive limit");if(u.prefixes=e.path.prefixes.filter(c=>k(c)&&I(c)).map(c=>C(c.trim())),u.prefixes.length===0)return g("path.prefixes has no valid entries")}if(e.path.segmentPrefixes!==void 0){if(!Array.isArray(e.path.segmentPrefixes)||e.path.segmentPrefixes.length===0)return g("path.segmentPrefixes must be non-empty when provided");if(e.path.segmentPrefixes.length>pn)return g("path.segmentPrefixes exceeds defensive limit");if(u.segmentPrefixes=e.path.segmentPrefixes.filter(c=>k(c)&&I(c)).map(c=>c.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),u.segmentPrefixes.length===0)return g("path.segmentPrefixes has no valid entries")}if(e.path.template!==void 0){if(!k(e.path.template))return g("path.template must be non-empty when provided");if(!I(e.path.template))return g("path.template exceeds defensive limit");let c=C(e.path.template.trim()),d=Ol(c);if(d)return g(d);u.template=c}if(!u.exact&&!u.prefixes&&!u.segmentPrefixes&&!u.template)return g("path must define exact, prefixes, segmentPrefixes, or template");t.path=u}if(e.query!==void 0){if(!K(e.query))return g("query must be an object when provided");if(!Array.isArray(e.query.conditions)||e.query.conditions.length===0)return g("query.conditions must be a non-empty array");if(e.query.conditions.length>Tl)return g("query.conditions exceeds defensive limit");if(e.query.mode!==void 0&&e.query.mode!=="all"&&e.query.mode!=="any")return g("query.mode must be all or any");let u=[];for(let c of e.query.conditions){let d=Fl(c);if(!d)return g("query condition is invalid");u.push(d)}t.query={...e.query.mode==="all"||e.query.mode==="any"?{mode:e.query.mode}:{},conditions:u}}if(!Vl(t))return g("match must include at least one useful rule");let i=!!t.path?.template,n;if(r.bindings!==void 0){if(!K(r.bindings))return g("bindings must be an object when provided");let u=Object.keys(r.bindings);if(u.length>Il)return g("bindings exceeds defensive limit");n=Object.create(null);let c=new Set;for(let d of u){if(!k(d))return g("binding key must be non-empty");let m=d.trim();if(!Gr(m))return g(`binding key is reserved: ${m}`);if(c.has(m))return g(`binding key collision after trim: ${m}`);c.add(m);let h=r.bindings[d],p=Bl(h,i);if(!p)return!i&&K(h)&&JSON.stringify(h).includes('"pathParam"')?g("pathParam requires path.template"):g(`binding ${d} is invalid`);n[m]=p}}let o=Go(r.debounceMs),s=Go(r.cooldownMs),a;if(r.selector!==void 0){let u=Ll(r.selector);if(!u)return g("selector is invalid");a=u}return{ok:!0,source:{name:r.name.trim(),type:"link",match:t,...r.enabled===!1?{enabled:!1}:{},...r.fireOnce===!0?{fireOnce:!0}:{},...o!==void 0?{debounceMs:o}:{},...s!==void 0?{cooldownMs:s}:{},...r.trigger==="click"?{trigger:"click"}:{},...a!==void 0?{selector:a}:{},...r.selectorType==="css"||r.selectorType==="id"||r.selectorType==="class"||r.selectorType==="attribute"||r.selectorType==="text"?{selectorType:r.selectorType}:{},...n?{bindings:n}:{}}}}function Qr(r){try{return Ul(r)}catch{return g("source normalization failed")}}var Xo=new Set(["http:","https:"]);function Yo(r){return!!(r.hasAttribute("disabled")||r.getAttribute("aria-disabled")==="true")}function zl(r){if(typeof HTMLAnchorElement<"u"&&r instanceof HTMLAnchorElement&&r.hasAttribute("href"))return r;let e=r.closest("a[href]");return e instanceof HTMLAnchorElement?e:null}function Hl(r,e){try{let t=new URL(r,e);return Xo.has(t.protocol)?t:null}catch{return null}}var jr=class extends E{constructor(t,i,n){super(t);this.hasFired=!1;this.destroyed=!1;this.initialized=!1;this.debounceTimer=null;this.lastFireAt=0;this.stats={matches:0,ignoredClicks:0,invalidUrl:0,unsupportedProtocol:0,missingRequired:0,mapperRejected:0,fired:0,fireOnceBlocked:0,debounceBlocked:0,cooldownBlocked:0,lastIgnoredReason:null,lastResolvedKeys:[],lastHostname:null,lastPathname:null};this.factory=i,this.eventType=n.eventType;let o=Qr(n.source);o.ok?(this.inactiveReason=null,this.source=o.source):(this.inactiveReason=o.reason,this.source={name:n.source.name?.trim()||"invalid-link",type:"link",match:{path:{exact:["/__invalid_link_source__"]}}},this.context.logger.debug(`[ConfiguredLinkDetector] inactive: ${o.reason}`)),this.selectorType=this.source.selectorType??"css",this.fireOnce=this.source.fireOnce===!0,this.debounceMs=typeof this.source.debounceMs=="number"&&Number.isFinite(this.source.debounceMs)&&this.source.debounceMs>0?this.source.debounceMs:0,this.cooldownMs=typeof this.source.cooldownMs=="number"&&Number.isFinite(this.source.cooldownMs)&&this.source.cooldownMs>0?this.source.cooldownMs:0,this.origin=n.origin??B("link",n.eventType,this.source.name),this.resolver=new $(t.logger)}get name(){return`ConfiguredLink(${this.eventType}:${this.source.name})`}get isActive(){return this.inactiveReason===null&&this.source.enabled!==!1}getDebugSnapshot(){return{sourceName:this.source.name,sourceType:"link",eventType:this.eventType,enabled:this.isActive,initialized:this.initialized,matches:this.stats.matches,ignoredClicks:this.stats.ignoredClicks,invalidUrl:this.stats.invalidUrl,unsupportedProtocol:this.stats.unsupportedProtocol,missingRequired:this.stats.missingRequired,mapperRejected:this.stats.mapperRejected,fired:this.stats.fired,fireOnceBlocked:this.stats.fireOnceBlocked,debounceBlocked:this.stats.debounceBlocked,cooldownBlocked:this.stats.cooldownBlocked,lastIgnoredReason:this.inactiveReason??this.stats.lastIgnoredReason,lastResolvedKeys:[...this.stats.lastResolvedKeys],lastHostname:this.stats.lastHostname,lastPathname:this.stats.lastPathname}}onInit(){this.destroyed=!1,this.hasFired=!1,this.lastFireAt=0,this.initialized=!0,!this.inactiveReason&&this.source.enabled!==!1&&this.isDocumentAvailable()&&Wr(this.eventType)&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){this.destroyed=!0,this.initialized=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}ignore(t){this.stats.ignoredClicks+=1,this.stats.lastIgnoredReason=t}handleClick(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}try{if(typeof t.button=="number"&&t.button!==0){this.ignore("non-primary-button");return}let i=this.resolveClickElements(t);if(!i){this.ignore("no-match");return}let{anchor:n,target:o}=i;if(Yo(o)||Yo(n)){this.ignore("disabled");return}let s=n.getAttribute("href");if(!s||s.trim()===""){this.ignore("missing-href");return}let a=s.trim().toLowerCase();if(a.startsWith("mailto:")||a.startsWith("tel:")||a.startsWith("javascript:")){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let l=typeof document<"u"&&document.baseURI?document.baseURI:"https://localhost/",u=Hl(s,l);if(!u){this.stats.invalidUrl+=1,this.ignore("invalid-url");return}if(!Xo.has(u.protocol)){this.stats.unsupportedProtocol+=1,this.ignore("unsupported-protocol");return}let c=Ho(u,this.source.match);if(!c.matched){this.ignore("target-mismatch");return}this.stats.matches+=1,this.stats.lastHostname=u.hostname,this.stats.lastPathname=qo(c.matchedPath);let d=Wo(this.source.bindings,{anchor:n,target:o,url:u,pathParams:c.pathParams});if(this.stats.lastResolvedKeys=Object.keys(d.values),!d.valid){this.stats.missingRequired+=1,this.ignore(`missing-required:${d.missingRequired.join(",")}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} missing required bindings`,d.missingRequired);return}let m=Vo(this.eventType,d.values);if(!m.ok){this.stats.mapperRejected+=1,this.ignore(`mapper:${m.reason}`),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} mapper rejected: ${m.reason}`);return}m.unknownKeys?.length&&this.context.logger.debug(`[ConfiguredLinkDetector] ${this.source.name} unknown binding keys ignored`,m.unknownKeys),this.scheduleFire(m.data)}catch(i){this.ignore("exception"),this.context.logger.debug(`[ConfiguredLinkDetector] ${this.eventType} ignored:`,i)}}}scheduleFire(t){let i=Date.now();if(this.cooldownMs>0&&i-this.lastFireAt<this.cooldownMs){this.stats.cooldownBlocked+=1;return}if(this.debounceMs>0){this.stats.debounceBlocked+=1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.fire(t)},this.debounceMs);return}this.fire(t)}fire(t){if(!(this.destroyed||this.inactiveReason)&&this.source.enabled!==!1){if(this.fireOnce&&this.hasFired){this.stats.fireOnceBlocked+=1;return}this.factory.trackAuto(this.eventType,t,{origin:this.origin}),this.stats.fired+=1,this.lastFireAt=Date.now(),this.fireOnce&&(this.hasFired=!0)}}resolveClickElements(t){let i=t.target instanceof Element?t.target:null;if(!i)return null;let n=zl(i);if(!n)return null;if(!this.source.selector)return{anchor:n,target:n};let o=[],s=i;for(;s&&s!==document.documentElement;)o.push(s),s=s.parentElement;o.includes(n)||o.unshift(n);for(let a of o)if(this.resolver.matches(a,this.source.selector,this.selectorType))return{anchor:n,target:a};return null}};var ql=new Set(["click","submit","hover","visible"]);function $l(r){let e=r.getAttribute("data-trigger")?.trim()||r.getAttribute("data-track-trigger")?.trim();if(!e)return null;let t=new Set;for(let i of e.toLowerCase().split(/[\s,]+/))ql.has(i)&&t.add(i);return t}function hn(r,e){let t=$l(r);return t==null?!0:t.has(e)}var Yr=class extends E{constructor(t,i,n){super(t);this.visibleFired=new WeakSet;this.observedElements=new Set;this.intersectionObserver=null;this.hasFired=!1;this.destroyed=!1;this.factory=i,this.config=n,this.selectorType=n.source.selectorType??"css",this.fireOnce=n.source.fireOnce===!0,this.trigger=n.source.trigger??"both",this.visibleThreshold=Kl(n.source.visibleThreshold),this.origin=n.origin??B("selector",n.eventType,n.source.name),this.resolver=new $(t.logger);let o=t.services.commerce.config;this.customerExtractor=new q({fieldMappings:re(o?.customer,o?.mappings?.fields)}),this.productExtractor=new ve({attributeMappings:o?.mappings?.attributes,fieldMappings:o?.mappings?.fields})}get name(){return`ConfiguredSelector(${this.config.eventType}:${this.config.source.name})`}onInit(){this.destroyed=!1,this.hasFired=!1,this.isDocumentAvailable()&&((this.trigger==="click"||this.trigger==="both")&&this.addDocumentListener("click",t=>this.handleEvent(t),!0),(this.trigger==="submit"||this.trigger==="both")&&this.addDocumentListener("submit",t=>this.handleEvent(t),!0),this.trigger==="hover"&&this.addDocumentListener("mouseover",t=>this.handleHover(t),!0),this.trigger==="visible"&&this.startVisibleObserver())}onDestroy(){this.destroyed=!0,this.intersectionObserver?.disconnect(),this.intersectionObserver=null,this.observedElements.clear()}handleHover(t){if(!(t instanceof MouseEvent))return;let i=this.findMatchedElement(t);if(!i)return;let n=t.relatedTarget instanceof Node?t.relatedTarget:null;n&&i.contains(n)||this.dispatchFromElement(i,"hover")}handleEvent(t){if(this.trigger==="click"&&t.type!=="click"||this.trigger==="submit"&&t.type!=="submit")return;let i=this.findMatchedElement(t);i&&this.dispatchFromElement(i,t.type==="submit"?"submit":"click")}startVisibleObserver(){if(typeof IntersectionObserver>"u"){this.context.logger.debug("[ConfiguredSelectorDetector] IntersectionObserver unavailable");return}this.intersectionObserver=new IntersectionObserver(t=>{for(let i of t)i.isIntersecting&&(this.visibleThreshold>0&&i.intersectionRatio<this.visibleThreshold||this.handleVisible(i.target))},{threshold:this.visibleThreshold}),this.syncVisibleTargets(),this.observeDom(()=>this.syncVisibleTargets())}syncVisibleTargets(){if(this.destroyed||!this.intersectionObserver)return;let t=this.resolver.queryAll(this.config.source.selector,this.selectorType).filter(n=>hn(n,"visible")),i=new Set(t);for(let n of this.observedElements)i.has(n)||(this.intersectionObserver.unobserve(n),this.observedElements.delete(n));for(let n of t)this.observedElements.has(n)||(this.intersectionObserver.observe(n),this.observedElements.add(n))}handleVisible(t){this.visibleFired.has(t)||this.dispatchFromElement(t,"visible")&&this.visibleFired.add(t)}dispatchFromElement(t,i){if(this.destroyed||this.fireOnce&&this.hasFired||!hn(t,i))return!1;try{let n=this.extractData(t);return n===null?!1:(this.factory.trackAuto(this.config.eventType,n,{origin:this.origin}),this.fireOnce&&(this.hasFired=!0),!0)}catch(n){return this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,n),!1}}findMatchedElement(t){let i=[];t.type==="submit"&&t.target instanceof Element&&i.push(t.target);let n=t.target instanceof Element?t.target:null;for(;n&&n!==document.documentElement;)i.push(n),n=n.parentElement;for(let o of i)if(this.resolver.matches(o,this.config.source.selector,this.selectorType))return o;return null}extractData(t){let{eventType:i}=this.config;if(i==="LEAD"){let n=this.customerExtractor.extractFromElement(t);return!n.email&&!n.phone&&!n.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...n.email?{email:n.email}:{},...n.phone?{phone:n.phone}:{},...n.name?{name:n.name}:{}}}if(i==="ADD_TO_CART"||i==="REMOVE_FROM_CART"){let n=this.productExtractor.extractFromElement(t);return i==="REMOVE_FROM_CART"?{...n.productId?{productId:n.productId}:{},...n.quantity!=null?{quantity:n.quantity}:{}}:{...n.productId?{productId:n.productId}:{},...n.productName?{productName:n.productName}:{},...n.price!=null?{price:n.price}:{},...n.currency?{currency:n.currency}:{},...n.quantity!=null?{quantity:n.quantity}:{}}}if(i==="SEARCH"){let n=t.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&t instanceof HTMLInputElement?t.value:"");return n.trim()?{query:n.trim()}:null}if(i==="INITIATE_CHECKOUT"||i==="PURCHASE")return{};if(i==="VIEW_CONTENT"){let n=this.productExtractor.extractFromElement(t);return{...n.productId?{contentId:n.productId}:{},...n.price!=null?{value:n.price}:{},...n.currency?{currency:n.currency}:{}}}return{}}};function Kl(r){return typeof r!="number"||!Number.isFinite(r)||r<0?0:r>1?1:r}var Wl=["card_number","cardNumber","card-number","cc_number"],Gl=["card_number","cardNumber","cc_number"],Ql=["cvv","cvc","security_code"],jl=["cvv","cvc","security_code"];function gn(r){return r.type!=="hidden"&&!r.disabled}function fn(r){return r.value.length>0}function Jo(r){return typeof document>"u"?null:r??document}function Zo(r,e,t){let i=Jo(t);if(!i)return!1;for(let n of r){let o=i===document?document.getElementById(n):i.querySelector(`#${Yl(n)}`);if(o instanceof HTMLInputElement&&gn(o)&&fn(o))return!0}for(let n of e){let o=i.querySelectorAll(`input[name="${n}"]`);for(let s of o)if(s instanceof HTMLInputElement&&gn(s)&&fn(s))return!0}return!1}function Ct(r,e){let t=Jo(e);if(!t)return!1;let i=t.querySelectorAll(`input[autocomplete="${r}"]`);for(let n of i)if(n instanceof HTMLInputElement&&gn(n)&&fn(n))return!0;return!1}function Yl(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/([^a-zA-Z0-9_-])/g,"\\$1")}function es(r){return Ct("cc-number",r)||Zo(Wl,Gl,r)||Ct("cc-exp",r)||Ct("cc-exp-month",r)||Ct("cc-exp-year",r)||Ct("cc-csc",r)||Zo(Ql,jl,r)}var Xl=["input","change","focusin"],xt=class extends E{constructor(t,i,n){super(t);this.checkTimer=null;this.tracked=!1;this.factory=i;let o=n?.source;this.paymentMethod=Zl(o?.paymentMethod),this.fireOnce=o?.fireOnce!==!1,this.formSelector=o?.formSelector,this.origin=n?.origin??(o?B("payment","ADD_PAYMENT_INFO",o.name):"auto:card")}get name(){return`CardDetector(${this.origin.includes(":")?this.origin.split(":").pop():"card"})`}onInit(){if(this.tracked=!1,!!this.isDocumentAvailable()){for(let t of Xl)this.addDocumentListener(t,()=>this.scheduleCheck(),!0);this.observeDom(()=>this.scheduleCheck()),this.scheduleCheck()}}onDestroy(){this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.tracked=!1}scheduleCheck(){this.fireOnce&&this.tracked||(this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.evaluate()},300))}evaluate(){if(this.fireOnce&&this.tracked||!this.isDocumentAvailable())return;let t=this.resolveFormRoot();this.formSelector&&!t||es(t)&&(this.tracked=!0,this.factory.trackAuto("ADD_PAYMENT_INFO",{paymentMethod:this.paymentMethod},{origin:this.origin}))}resolveFormRoot(){if(!this.formSelector||typeof document>"u")return typeof document<"u"?document:null;try{return document.querySelector(this.formSelector)}catch{return null}}};function Zl(r){switch(r){case"CREDIT_CARD":case"PIX":case"BOLETO":case"PAYPAL":case"OTHER":return r;case"BANK_SLIP":return"BOLETO";default:return"CREDIT_CARD"}}var Jl=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],Xr=class extends E{constructor(t,i){super(t);this.name="CheckoutDetector";this.factory=i}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i)return;let n=i.textContent?.toLowerCase()??"",o=i.href?.toLowerCase()??"";(Jl.some(a=>i.matches(a))||n.includes("checkout")&&!n.includes("continue shopping")||n.includes("finalizar")&&n.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let i=t.target instanceof HTMLFormElement?t.target:null;if(!i)return;((i.getAttribute("action")?.toLowerCase()??"").includes("checkout")||i.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var Zr=class extends E{constructor(t,i,n){super(t);this.hasFired=!1;this.factory=i,this.options=n,this.fireOnce=n.source.fireOnce!==!1,this.origin=n.origin??B("lifecycle",n.eventType,n.source.name)}get name(){return`Lifecycle(${this.options.eventType}:${this.options.source.name})`}onInit(){this.hasFired=!1,this.fire()}onDestroy(){this.hasFired=!1}fire(){this.fireOnce&&this.hasFired||(this.factory.trackAuto(this.options.eventType,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0))}};var eu={purchase:"PURCHASE",lead:"LEAD",add_to_cart:"ADD_TO_CART",addtocart:"ADD_TO_CART",remove_from_cart:"REMOVE_FROM_CART",removefromcart:"REMOVE_FROM_CART",initiate_checkout:"INITIATE_CHECKOUT",initiatecheckout:"INITIATE_CHECKOUT",checkout:"INITIATE_CHECKOUT",add_payment_info:"ADD_PAYMENT_INFO",addpaymentinfo:"ADD_PAYMENT_INFO",view_content:"VIEW_CONTENT",viewcontent:"VIEW_CONTENT",search:"SEARCH"};function yn(r){let e=r.trim().toLowerCase().replace(/\s+/g,"_");return eu[e]??null}function ts(r){return r.startsWith("[")||r.startsWith(".")||r.startsWith("#")?r:`[data-track="${r}"]`}var Jr=class extends E{constructor(t,i,n=[]){super(t);this.name="SelectorDetector";this.factory=i,this.selectors=n.length>0?n:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target:null;for(;i&&i!==document.body;){let n=this.matchElement(i);if(n){this.factory.trackAuto(n.type,n.data,{origin:"auto:selector"});return}i=i.parentElement}}matchElement(t){for(let n of this.selectors){let o=ts(n);if(!t.matches(o))continue;let s=t.getAttribute("data-track")??t.getAttribute("data-track-event")??t.getAttribute("data-event");if(!s)continue;let a=yn(s);if(!a)continue;let l={},u=t.getAttribute("data-track-value");return u&&a==="PURCHASE"&&Object.assign(l,{value:Number(u)||void 0}),{type:a,data:l}}let i=t.getAttribute("data-track");if(i){let n=yn(i);if(n)return{type:n,data:{}}}return null}};var tu=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],ei=class extends E{constructor(t,i,n=[]){super(t);this.name="TextDetector";this.factory=i,this.keywords=n}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let i=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!i?.textContent)return;let n=i.textContent.trim().toLowerCase();if(n){for(let o of tu)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&n.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(n.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var j=class{static subscribe(e){return typeof window>"u"||typeof history>"u"?()=>{}:(this.listeners.add(e),this.refCount+=1,this.install(),()=>{this.listeners.delete(e),this.refCount-=1,this.refCount<=0&&(this.uninstall(),this.refCount=0)})}static resetForTests(){this.listeners.clear(),this.refCount=0,this.uninstall()}static install(){this.installed||(this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.notify()},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.notify()},this.installed=!0)}static uninstall(){this.installed&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installed=!1)}static notify(){for(let e of this.listeners)e()}};j.refCount=0,j.listeners=new Set,j.originalPushState=null,j.originalReplaceState=null,j.installed=!1;var Tt=class extends E{constructor(t,i,n=[],o){super(t);this.hasFired=!1;this.unsubscribeHistory=null;this.factory=i,this.patterns=n.map(s=>new RegExp(s,"i")),this.eventType=o?.eventType,this.fireOnce=o?.fireOnce===!0,this.origin=o?.origin??(o?.sourceName&&o.eventType?B("url",o.eventType,o.sourceName):"auto:url")}get name(){return this.eventType?`UrlDetector(${this.eventType})`:"UrlDetector"}onInit(){this.hasFired=!1,this.isWindowAvailable()&&(this.checkUrl(),this.addWindowListener("popstate",()=>this.checkUrl()),this.unsubscribeHistory=j.subscribe(()=>this.checkUrl()))}onDestroy(){this.unsubscribeHistory?.(),this.unsubscribeHistory=null,this.hasFired=!1}checkUrl(){if(!this.isWindowAvailable()||this.fireOnce&&this.hasFired)return;let t=window.location.href,i=window.location.pathname;for(let n of this.patterns)if(n.test(t)||n.test(i)){let o=this.eventType??(/thank|success|order|obrigado/i.test(n.source)?"PURCHASE":"INITIATE_CHECKOUT");this.factory.trackAuto(o,{},{origin:this.origin}),this.fireOnce&&(this.hasFired=!0);return}}};var ru=[{configKey:"lead",eventType:"LEAD"},{configKey:"addToCart",eventType:"ADD_TO_CART"},{configKey:"removeFromCart",eventType:"REMOVE_FROM_CART"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT"},{configKey:"purchase",eventType:"PURCHASE"},{configKey:"addPaymentInfo",eventType:"ADD_PAYMENT_INFO"},{configKey:"search",eventType:"SEARCH"},{configKey:"viewContent",eventType:"VIEW_CONTENT"}],iu=new Set(["LEAD","ADD_TO_CART","INITIATE_CHECKOUT"]),ti=class{static create(e,t){let{auto:i,rules:n}=e.config.modules.conversion,o=[],s=e.logger;return i.enabled?(o.push(...this.createSourceDetectors(e,t,i)),n.enabled&&(n.selectors.length>0&&(o.push(new Jr(e,t,n.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),n.texts.length>0&&(o.push(new ei(e,t,n.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),n.urlPatterns.length>0&&(o.push(new Tt(e,t,n.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),n.checkout.enabled&&(o.push(new Xr(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),n.card.enabled&&(o.push(new xt(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (rules)"))),s.debug(`[AutoTrackerFactory] Created ${o.length} detector(s)`),o):(s.debug("[AutoTrackerFactory] Auto detection disabled"),o)}static createSourceDetectors(e,t,i){let n=[],o=new $(e.logger),s=e.logger,a=e.config.modules.conversion.rules.enabled?e.config.modules.conversion.rules.card.enabled:!1;for(let l of ru){let u=i.detectors[l.configKey];if(!u.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${l.configKey}`);continue}let c=u.sources??[];for(let d of c){if(d.enabled===!1){s.debug(`[AutoTrackerFactory] Skipped disabled source: ${l.configKey}/${d.name}`);continue}let m=this.createDetectorForSource(e,t,l.eventType,d,o,{rulesCardActive:a});m&&(d.type==="payment"&&d.cardDetection,n.push(m),s.debug(`[AutoTrackerFactory] ${m.name??d.type} registered for ${l.eventType}`))}}return n}static createDetectorForSource(e,t,i,n,o,s){let a=e.logger;switch(n.type){case"form":return iu.has(i)?new Kr(e,t,{eventType:i,source:n}):(a.debug(`[AutoTrackerFactory] Skipped form source for unsupported event: ${i}`),null);case"selector":{let l=n;return o.hasEntries(l.selector)?new Yr(e,t,{eventType:i,source:l}):(a.debug(`[AutoTrackerFactory] Skipped selector source ${n.name}: empty selector`),null)}case"payment":{if(i!=="ADD_PAYMENT_INFO")return a.debug(`[AutoTrackerFactory] Skipped payment source for ${i}`),null;let l=n;return l.cardDetection===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: cardDetection false`),null):l.autoDispatch===!1?(a.debug(`[AutoTrackerFactory] Skipped payment source ${n.name}: autoDispatch false`),null):new xt(e,t,{source:l})}case"lifecycle":return new Zr(e,t,{eventType:i,source:n});case"url":{let l=n;return l.patterns?.length?new Tt(e,t,l.patterns,{eventType:i,sourceName:l.name,fireOnce:l.fireOnce}):(a.debug(`[AutoTrackerFactory] Skipped url source ${n.name}: empty patterns`),null)}case"link":{if(!Wr(i))return a.debug(`[AutoTrackerFactory] Skipped link source for unsupported event: ${i}`),null;let l;try{l=Qr(n)}catch(u){return a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: normalization threw`,u),null}return l.ok?new jr(e,t,{eventType:i,source:l.source}):(a.debug(`[AutoTrackerFactory] Skipped link source ${n.name}: ${l.reason}`),null)}default:return a.debug(`[AutoTrackerFactory] Unknown source type: ${n.type}`),null}}};var ri=class{constructor(){this.sentKeys=new Set}has(e){return this.sentKeys.has(e)}add(e){this.sentKeys.add(e)}clear(){this.sentKeys.clear()}getKeys(){return Array.from(this.sentKeys)}get size(){return this.sentKeys.size}};function rs(r,e,t,i){let n=vn(t,i),o=typeof e?.productId=="string"?e.productId.trim():"",s=nu(e?.quantity),a=typeof e?.productName=="string"?e.productName.trim():"";return o?`${r}:product:${o}:qty:${s}:bucket:${n}`:a?`${r}:name:${a}:qty:${s}:bucket:${n}`:`${r}:interaction:${n}`}function is(r,e=Date.now(),t=500){return rs("ADD_TO_CART",r,e,t)}function ns(r,e=Date.now(),t=500){return rs("REMOVE_FROM_CART",r,e,t)}function vn(r=Date.now(),e=500){let t=e>0?e:500;return Math.floor(r/t)}function nu(r){return typeof r=="number"&&Number.isFinite(r)?r:1}var ou=new Set(["manual","auto:selector","auto:text","auto:checkout","auto:purchase","auto:lead","auto:addToCart","auto:removeFromCart","auto:initiateCheckout","auto:addPaymentInfo","auto:search","auto:viewContent"]);function Sn(r){return r==="auto:url"||r.startsWith("auto:url:")}function su(r){return Sn(r)?!1:ou.has(r)?!0:r.startsWith("auto:form:")||r.startsWith("auto:selector:")||r.startsWith("auto:lifecycle:")}function au(r=Date.now()){return Math.floor(r/1e3)}function os(){return typeof window>"u"?"":window.location.pathname}function En(r,e,t,i,n=Date.now()){let o=e??{},s=vn(n,500);switch(r){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:Sn(t)?`PURCHASE:url:${os()}`:su(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${au(n)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return is(o,n,500);case"REMOVE_FROM_CART":return ns(o,n,500);case"INITIATE_CHECKOUT":return Sn(t)?`INITIATE_CHECKOUT:url:${os()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${i}`;case"VIEW_CONTENT":{let a=o;return a.contentId?`VIEW_CONTENT:content:${a.contentId}`:`VIEW_CONTENT:interaction:${s}`}case"SEARCH":return`SEARCH:query:${o.query}`;default:return`${r}:interaction:${s}`}}var x=class{constructor(e){this.factory=e}};var ii=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var ni=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var oi=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var si=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var ai=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var li=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var ui=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var ci=class extends x{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var lu={VIEW_CONTENT:"viewContent",ADD_TO_CART:"addToCart",REMOVE_FROM_CART:"removeFromCart",INITIATE_CHECKOUT:"initiateCheckout",ADD_PAYMENT_INFO:"addPaymentInfo",PURCHASE:"purchase",LEAD:"lead"},uu=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE","VIEW_CONTENT","ADD_PAYMENT_INFO"],di=class{constructor(e,t,i,n){if(this.context=e,this.trackFn=t,this.dedupeSessionId=i,this.commerceState=n?.state??null,n){let o=e.services.commerce.config;this.resolver=new se({catalog:n.catalog,state:n.state,calculator:new oe,defaultCurrency:o?.currency,calculateValueFrom:o?.cart?.calculateValueFrom??"cart"})}else this.resolver=null;this.purchase=new ai(this),this.lead=new si(this),this.addToCart=new ni(this),this.removeFromCart=new li(this),this.initiateCheckout=new oi(this),this.addPaymentInfo=new ii(this),this.viewContent=new ci(this),this.search=new ui(this)}trackAuto(e,t,i){this.dispatch(e,t,i?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let i=t,n=i?.query??i?.searchTerm??"";if(!n.trim())throw new Error("[Conversion] SEARCH requires query");return{query:n.trim()}}case"PURCHASE":{let i=t;if(i?.value!=null&&i.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return i??{}}case"LEAD":{let i=t;if(!i?.email&&!i?.phone&&!i?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return i}case"VIEW_CONTENT":{let i={...t??{}};return delete i.productId,i}default:return t??{}}}buildDedupeKey(e,t,i){return En(e,t,i,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,i){let n=this.enrichCommerce(e,t),o=this.normalize(e,n);this.syncCommerceState(e,o);let s=En(e,o,i,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:i})}enrichCommerce(e,t){if(!this.resolver||!cu(e))return t;let i=lu[e];if(!i)return t;let n=this.context.services.commerce;if(!n.isEnrichmentEnabled(i))return t;let o=n.getEnrichmentSource(i);return this.resolver.resolve({eventType:e,payload:t??{},enrichmentSource:o}).data}syncCommerceState(e,t){if(this.commerceState){if(e==="ADD_TO_CART"){this.syncAddToCart(t);return}e==="REMOVE_FROM_CART"&&this.syncRemoveFromCart(t)}}syncAddToCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";if(!t)return;let i=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:i,...typeof e.price=="number"&&Number.isFinite(e.price)?{price:e.price}:{},...typeof e.currency=="string"&&e.currency.trim()?{currency:e.currency.trim()}:{}})}syncRemoveFromCart(e){if(!this.commerceState)return;let t=typeof e.productId=="string"?e.productId.trim():"";t&&this.commerceState.removeItem(t)}};function cu(r){return uu.includes(r)}var mi=class{constructor(e){this.deduper=new ri;this.detectors=[];this.active=!1;this.context=e,this.dedupeSessionId=`${e.config.identity.pixelId}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`;let t=e.services.commerce;this.catalog=t.catalog,this.commerceState=t.state,this.factory=new di(e,(i,n,o)=>{this.dispatch(i,n,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=ti.create(this.context,this.factory);for(let e of this.detectors)e.init();this.active=!0}}destroy(){if(this.active){for(let e=this.detectors.length-1;e>=0;e-=1)this.detectors[e]?.destroy();this.detectors=[],this.deduper.clear(),this.active=!1}}getDedupeKeys(){return this.deduper.getKeys()}getActiveDetectors(){return this.detectors.map(e=>e.name??e.constructor.name)}isActive(){return this.active}dispatch(e,t,i){let n=i??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(n)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${n})`);return}this.deduper.add(n);let o=this.context.services.eventBuilder.build({type:e,category:"CONVERSION",data:t});this.context.logger.debug(`[ConversionEngine] Dispatching ${e}`),this.context.services.dispatcher.dispatch(o)}};var It=class{constructor(){this.name="conversion";this.engine=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Conversion module already initialized");return}if(!e.config.modules.conversion.enabled){e.logger.debug("[Pixel] Conversion module disabled");return}e.logger.debug("[Pixel] Conversion module initialized"),this.engine=new mi(e),this.engine.init(),this.active=!0}destroy(){this.active&&(this.engine?.destroy(),this.engine=null,this.active=!1)}purchase(e){this.engine?.factory.purchase.track(e)}lead(e){this.engine?.factory.lead.track(e)}addToCart(e){this.engine?.factory.addToCart.track(e)}removeFromCart(e){this.engine?.factory.removeFromCart.track(e)}initiateCheckout(e){this.engine?.factory.initiateCheckout.track(e)}addPaymentInfo(e){this.engine?.factory.addPaymentInfo.track(e)}viewContent(e){this.engine?.factory.viewContent.track(e)}search(e){this.engine?.factory.search.track(e)}getDebugDedupeKeys(){return this.engine?.getDedupeKeys()??[]}getDebugActiveDetectors(){return this.engine?.getActiveDetectors()??[]}isEngineActive(){return this.engine?.isActive()??!1}};var At=class{constructor(e){this.context=e}init(){this.context.config.modules.core.fingerprint.enabled&&(this.context.logger.debug("[FingerprintEngine] Ensuring fingerprint"),this.context.services.fingerprint.ensureFingerprint())}destroy(){}};var pi=class{constructor(e){this.started=!1;this.originalPushState=null;this.originalReplaceState=null;this.handlePopState=()=>{this.onNavigate("back")};this.handleHashChange=()=>{this.onNavigate("hash")};this.onNavigate=e}start(){this.started||typeof window>"u"||(this.started=!0,this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState?.(...e),this.onNavigate("pushState")},history.replaceState=(...e)=>{this.originalReplaceState?.(...e),this.onNavigate("replaceState")},window.addEventListener("popstate",this.handlePopState),window.addEventListener("hashchange",this.handleHashChange))}destroy(){!this.started||typeof window>"u"||(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange),this.originalPushState=null,this.originalReplaceState=null,this.started=!1)}};var hi=class{constructor(e){this.lastPath=null;this.lastTimestamp=0;this.dedupeMs=e}shouldDispatch(e,t=Date.now()){return this.lastPath===e&&t-this.lastTimestamp<this.dedupeMs?!1:(this.lastPath=e,this.lastTimestamp=t,!0)}reset(){this.lastPath=null,this.lastTimestamp=0}};var Dt=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new hi(e.config.modules.core.pageView.dedupeMs)}init(){let{pageView:e}=this.context.config.modules.core;e.enabled&&(e.trackInitialPageView&&this.trackPageView(),e.spa&&(this.navigationObserver=new pi(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",i=Date.now();if(!this.deduper.shouldDispatch(t,i)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let n=this.context.services.commerce.resolvePageViewEnrichment(),o=this.context.services.eventBuilder.build({type:"PAGE_VIEW",...n??{}});this.context.logger.debug("[PageViewEngine] Dispatching PAGE_VIEW"),this.context.services.dispatcher.dispatch(o)}destroy(){this.navigationObserver?.destroy(),this.navigationObserver=null,this.deduper.reset()}};var wt=class{constructor(e){this.unsubscribe=null;this.context=e}init(){if(!this.context.config.modules.core.session.enabled)return;this.context.logger.debug("[SessionEngine] Ensuring session");let{ttlMs:e}=this.context.config.modules.core.session;this.applySessionLifecycle(e),this.unsubscribe=this.context.services.dispatcher.subscribe(t=>{t.type==="PAGE_VIEW"&&this.handlePageViewActivity()})}destroy(){this.unsubscribe?.(),this.unsubscribe=null}handlePageViewActivity(){let{ttlMs:e,renewOnActivity:t}=this.context.config.modules.core.session,{session:i}=this.context.services;if(i.isExpired(e)){this.applySessionLifecycle(e);return}t&&(i.touchActivity(),this.context.logger.debug("[SessionEngine] Session activity renewed"))}applySessionLifecycle(e){let t=this.context.services.session.ensureSession(e);if(t.expired&&t.previousSessionId){let i=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(i);let n=this.context.services.eventBuilder.build({type:"SESSION_RENEWED",sessionId:t.sessionId,previousSessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_RENEWED"),this.context.services.dispatcher.dispatch(n)}}};var kt=class{constructor(e){this.started=!1;this.context=e}init(){if(this.started||(this.started=!0,!this.context.config.modules.core.enabled))return;let e=this.context.services.urlContext;e&&(e.init(),this.context.logger.debug("[Pixel] UrlContext engine initialized"))}destroy(){this.started&&(this.context.services.urlContext?.destroy(),this.started=!1)}dispose(){this.destroy()}};var Rt=class{constructor(e){this.context=e}init(){this.context.config.modules.core.visitor.enabled&&(this.context.logger.debug("[VisitorEngine] Ensuring visitor"),this.context.services.visitor.ensureVisitorId())}destroy(){}};var Mt=class{constructor(){this.name="core";this.urlContextEngine=null;this.visitorEngine=null;this.sessionEngine=null;this.fingerprintEngine=null;this.pageViewEngine=null}init(e){e.logger.debug("[Pixel] Core module initialized"),this.urlContextEngine=new kt(e),this.visitorEngine=new Rt(e),this.sessionEngine=new wt(e),this.fingerprintEngine=new At(e),this.pageViewEngine=new Dt(e),this.urlContextEngine.init(),this.visitorEngine.init(),this.sessionEngine.init(),this.fingerprintEngine.init(),this.pageViewEngine.init()}destroy(){this.pageViewEngine?.destroy(),this.fingerprintEngine?.destroy(),this.sessionEngine?.destroy(),this.visitorEngine?.destroy(),this.urlContextEngine?.destroy(),this.pageViewEngine=null,this.fingerprintEngine=null,this.sessionEngine=null,this.visitorEngine=null,this.urlContextEngine=null}};var Pt=class{constructor(){this.adapters=new Map}register(e){if(this.adapters.has(e.name))throw new Error(`[Integration] Destination "${e.name}" is already registered`);this.adapters.set(e.name,e)}remove(e){let t=this.adapters.get(e);return t?(t.destroy?.(),this.adapters.delete(e)):!1}get(e){return this.adapters.get(e)}getAll(){return[...this.adapters.values()]}supports(e){return this.getAll().filter(t=>{try{return t.supports(e)}catch{return!1}})}has(e){return this.adapters.has(e)}size(){return this.adapters.size}clear(){for(let e of this.adapters.values())e.destroy?.();this.adapters.clear()}};function du(){return{sent:0,failed:0,ignored:0,skipped:0,totalDuration:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0,scriptLoadAttempts:0,scriptLoadSuccess:0,scriptLoadFailure:0,initAttempts:0,initSuccess:0,initFailure:0,lastError:null}}var _t=class{constructor(){this.registeredDestinations=0;this.eventsSent=0;this.eventsFailed=0;this.eventsIgnored=0;this.eventsSkipped=0;this.pageViewReceived=0;this.pageViewSent=0;this.pageViewSkipped=0;this.pageViewDeduped=0;this.pageViewFailed=0;this.scriptLoadAttempts=0;this.scriptLoadSuccess=0;this.scriptLoadFailure=0;this.initAttempts=0;this.initSuccess=0;this.initFailure=0;this.totalDuration=0;this.lastExecutionAt=null;this.lastErrorAt=null;this.lastErrorMessage=null;this.perDestination=new Map;this.perDestinationId=new Map}getDestinationCounters(e){let t=this.perDestination.get(e);return t||(t=du(),this.perDestination.set(e,t)),t}setRegisteredCount(e){this.registeredDestinations=e}recordPageViewReceived(){this.pageViewReceived+=1}recordScriptLoadAttempt(e){this.scriptLoadAttempts+=1,this.getDestinationCounters(e).scriptLoadAttempts+=1}recordScriptLoadSuccess(e){this.scriptLoadSuccess+=1,this.getDestinationCounters(e).scriptLoadSuccess+=1}recordScriptLoadFailure(e){this.scriptLoadFailure+=1,this.getDestinationCounters(e).scriptLoadFailure+=1}recordInitAttempt(e){this.initAttempts+=1,this.getDestinationCounters(e).initAttempts+=1}recordInitSuccess(e){this.initSuccess+=1,this.getDestinationCounters(e).initSuccess+=1}recordInitFailure(e){this.initFailure+=1,this.getDestinationCounters(e).initFailure+=1}record(e){let t=e.adapter,i=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,i.sent+=1):e.status==="failed"?(this.eventsFailed+=1,i.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",i.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,i.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,i.skipped+=1),i.totalDuration+=e.duration,e.metadata){let n=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);n>0&&(this.pageViewSent+=n,i.pageViewSent+=n),o>0&&(this.pageViewDeduped+=o,i.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,i.pageViewFailed+=s);let a=e.metadata.pixelIds,l=e.metadata.tagIds,u=a??l;if(u&&n>0)for(let c of u.slice(0,n))this.recordDestinationId(t,c,"sent",n/u.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,i.pageViewFailed+=1)}recordDestinationId(e,t,i,n){let o=`${e}:${t}`,s=this.perDestinationId.get(o);s||(s={sent:0,failed:0,pageViewSent:0,pageViewDeduped:0,pageViewFailed:0},this.perDestinationId.set(o,s)),i==="sent"?(s.sent+=n,s.pageViewSent+=n):(s.failed+=n,s.pageViewFailed+=n)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[i,n]of this.perDestination){let o=n.sent+n.failed;t[i]={sent:n.sent,failed:n.failed,ignored:n.ignored,skipped:n.skipped,averageDuration:o>0?n.totalDuration/o:0,successRate:o>0?n.sent/o:0,pageViewSent:n.pageViewSent,pageViewDeduped:n.pageViewDeduped,pageViewFailed:n.pageViewFailed,scriptLoadAttempts:n.scriptLoadAttempts,scriptLoadSuccess:n.scriptLoadSuccess,scriptLoadFailure:n.scriptLoadFailure,initAttempts:n.initAttempts,initSuccess:n.initSuccess,initFailure:n.initFailure,lastError:n.lastError}}return{registeredDestinations:this.registeredDestinations,activeDestinations:this.registeredDestinations,eventsSent:this.eventsSent,eventsFailed:this.eventsFailed,eventsIgnored:this.eventsIgnored,eventsSkipped:this.eventsSkipped,pageViewReceived:this.pageViewReceived,pageViewSent:this.pageViewSent,pageViewSkipped:this.pageViewSkipped,pageViewDeduped:this.pageViewDeduped,pageViewFailed:this.pageViewFailed,scriptLoadAttempts:this.scriptLoadAttempts,scriptLoadSuccess:this.scriptLoadSuccess,scriptLoadFailure:this.scriptLoadFailure,initAttempts:this.initAttempts,initSuccess:this.initSuccess,initFailure:this.initFailure,averageDuration:e>0?this.totalDuration/e:0,successRate:e>0?this.eventsSent/e:0,lastExecutionAt:this.lastExecutionAt,lastErrorAt:this.lastErrorAt,lastErrorMessage:this.lastErrorMessage,perDestination:t,perDestinationId:Object.fromEntries(this.perDestinationId)}}reset(){this.registeredDestinations=0,this.eventsSent=0,this.eventsFailed=0,this.eventsIgnored=0,this.eventsSkipped=0,this.pageViewReceived=0,this.pageViewSent=0,this.pageViewSkipped=0,this.pageViewDeduped=0,this.pageViewFailed=0,this.scriptLoadAttempts=0,this.scriptLoadSuccess=0,this.scriptLoadFailure=0,this.initAttempts=0,this.initSuccess=0,this.initFailure=0,this.totalDuration=0,this.lastExecutionAt=null,this.lastErrorAt=null,this.lastErrorMessage=null,this.perDestination.clear(),this.perDestinationId.clear()}};var Lt=class r{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new r(this.logger,e)}debug(e,...t){this.logger.debug(`[${this.scope}] ${e}`,...t)}info(e,...t){this.logger.info(`[${this.scope}] ${e}`,...t)}warn(e,...t){this.logger.warn(`[${this.scope}] ${e}`,...t)}error(e,...t){this.logger.error(`[${this.scope}] ${e}`,...t)}};var Ot=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,i){let n=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${n}`),{status:"failed",adapter:e.name,duration:i,timestamp:Date.now(),error:n}}shouldContinue(){return this.continueOnError}};var Ft=class{constructor(e){this.logger=e.logger,this.errorHandler=e.errorHandler,this.hooks=e.hooks??{},this.timeoutMs=e.timeoutMs,this.debug=e.debug??!1}async execute(e,t){let i=Date.now(),n=new AbortController,o=setTimeout(()=>n.abort(),this.timeoutMs),s={event:t,signal:n.signal,timeoutMs:this.timeoutMs,debug:this.debug};try{await this.hooks.beforeExecute?.(e,t);let a=await e.execute(s),l={...a,adapter:a.adapter||e.name,duration:a.duration||Date.now()-i,timestamp:a.timestamp||Date.now()};return await this.hooks.afterExecute?.(e,t,l),l.status==="success"?await this.hooks.onSuccess?.(e,t,l):l.status==="failed"||l.status==="retry"?await this.hooks.onFailure?.(e,t,l):(l.status==="ignored"||l.status==="skipped")&&await this.hooks.onIgnored?.(e,t,l),this.debug&&this.logger.forAdapter(e.name).debug(`Result ${l.status} in ${l.duration}ms`),l}catch(a){let l=this.errorHandler.toFailedResult(e,a,Date.now()-i);return await this.hooks.onFailure?.(e,t,l),await this.hooks.afterExecute?.(e,t,l),l}finally{clearTimeout(o)}}};var Nt=class{constructor(e){this.lastResults=[];this.registry=e.registry,this.executor=e.executor,this.metrics=e.metrics,this.logger=e.logger;let t=e.concurrency??3;this.concurrency=t<=0?1:t}async dispatch(e){let t=this.registry.supports(e);if(t.length===0)return this.lastResults=[],[];let i=[];for(let n=0;n<t.length;n+=this.concurrency){let o=t.slice(n,n+this.concurrency),s=await Promise.allSettled(o.map(a=>this.executor.execute(a,e)));for(let a=0;a<s.length;a+=1){let l=s[a],u=o[a];if(l.status==="fulfilled")i.push(l.value),this.metrics.record(l.value);else{let c={status:"failed",adapter:u.name,duration:0,timestamp:Date.now(),error:l.reason instanceof Error?l.reason.message:String(l.reason)};i.push(c),this.metrics.record(c),this.logger.error(`Unhandled destination error: ${u.name}`,l.reason)}}}return this.lastResults=i,i}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var Bt=class r{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new r([{name:"identity",process(e){return e}}])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,i}getLastSteps(){return this.lastSteps}};var Vt=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var ae=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),R=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??ae}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,i){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...i}}};var Ut=class extends R{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:ae});this.sent=0;this.log=t.log??((i,n)=>{console.log(i,n)})}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});let n={type:t.event.type,timestamp:t.event.timestamp,category:"category"in t.event?t.event.category:void 0};return this.log(`[Console] ${t.event.type}`,n),this.sent+=1,this.createResult("success",Date.now()-i,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var zt=class extends R{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:ae});this.records=[]}async execute(t){let i=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});let n=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:n}),this.createResult("success",Date.now()-i,{metadata:{recordCount:this.records.length}})}getRecords(){return[...this.records]}clear(){this.records.length=0}destroy(){this.clear()}transform(t){return{destination:"memory",eventType:t.type,timestamp:t.timestamp,path:"path"in t?t.path:void 0,data:"data"in t?t.data:void 0}}};var Ht=class extends R{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??ae});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let i=Date.now();if(this.executions+=1,this.delayMs>0&&await this.wait(this.delayMs,t.signal),t.signal.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-i,{ignored:!0});if(this.failOnTypes.has(t.event.type))throw new Error(`[Mock] Simulated failure for ${t.event.type}`);return this.createResult("success",Date.now()-i,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,i){return new Promise((n,o)=>{let s=setTimeout(()=>{l(),n()},t),a=()=>{l(),o(new DOMException("The operation was aborted.","AbortError"))},l=()=>{clearTimeout(s),i.removeEventListener("abort",a)};if(i.aborted){l(),o(new DOMException("The operation was aborted.","AbortError"));return}i.addEventListener("abort",a)})}};var ss=new Set;function le(r,e,t,i,n){return`${r}:${e}:${t}:${i}:${n}`}function ue(r){return ss.has(r)?!0:(ss.add(r),!1)}var Fe=new Map;function be(r){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=Fe.get(r.src);if(e)return e.refCount+=1,e.promise;let t=r.timeoutMs??1e4,i=new Promise((n,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=r.src,r.id&&(s.id=r.id),r.attributes)for(let[u,c]of Object.entries(r.attributes))s.setAttribute(u,c);let a=setTimeout(()=>{l(),o(new Error(`[ScriptLoader] Timeout loading ${r.src}`))},t),l=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{l();let u=Fe.get(r.src);u&&(u.loaded=!0),n()},s.onerror=()=>{l(),Fe.delete(r.src),o(new Error(`[ScriptLoader] Failed to load ${r.src}`))},document.head.appendChild(s)});return Fe.set(r.src,{promise:i,refCount:1,loaded:!1}),i}function Se(r){let e=Fe.get(r);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&Fe.delete(r))}var gi="https://connect.facebook.net/en_US/fbevents.js";function mu(){return typeof window<"u"?window:null}function pu(){let r=mu();if(!r)throw new Error("[MetaScriptLoader] window unavailable");if(r.fbq)return r.fbq;let e=function(...t){let i=e;i.callMethod?i.callMethod(...t):(i.queue=i.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],r.fbq=e,r._fbq||(r._fbq=e),e}var qt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[MetaScriptLoader] Browser APIs unavailable");let t=pu();return this.loaded&&t.loaded||(await be({src:gi,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){Se(gi)}};var $t=class extends R{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new qt;this.initialized=!1;this.fbq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("MetaBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("meta"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("meta"),this.debug&&this.logger.debug("script_load_start");try{this.fbq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("meta"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("meta"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.fbq&&(this.fbq=window.fbq??null);let i=this.fbq;if(!i)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let n=!1;for(let o of this.pixelIds)try{i("init",o)}catch(s){n=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(m){return this.createResult("failed",Date.now()-i,{error:m instanceof Error?m.message:String(m)})}let a=this.fbq??(typeof window<"u"?window.fbq??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"fbq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;for(let m of this.pixelIds){let h=le("meta",m,"PAGE_VIEW",l,u);if(ue(h)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${m}`);continue}try{if(typeof a=="function")try{a("trackSingle",m,"PageView")}catch{a("track","PageView")}c+=1,this.debug&&this.logger.debug(`pageview_sent id=${m}`)}catch(p){this.logger.error(`destination_execute_failure id=${m}`,p)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var Cn="https://www.googletagmanager.com/gtag/js";function hu(){return typeof window<"u"?window:null}function gu(){let r=hu();if(!r)throw new Error("[GoogleScriptLoader] window unavailable");return r.dataLayer=r.dataLayer||[],r.gtag||(r.gtag=function(...t){r.dataLayer?.push(t)}),r.gtag}var Kt=class{constructor(){this.loadedSrc=null}async load(e,t=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[GoogleScriptLoader] Browser APIs unavailable");let i=gu(),n=`${Cn}?id=${encodeURIComponent(e)}`;return await be({src:n,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=n,i("js",new Date),i}release(){this.loadedSrc&&(Se(this.loadedSrc),this.loadedSrc=null)}};var Wt=class extends R{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Kt;this.initialized=!1;this.gtag=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("GoogleBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.tagIds=[...new Set(t.config.tagIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.tagIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.tagIds.length===0)return;this.metrics?.recordInitAttempt("google"),this.debug&&this.logger.debug("destination_init_start");let i=this.tagIds[0];if(this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("google"),this.debug&&this.logger.debug("script_load_start");try{this.gtag=await this.scriptLoader.load(i,t),this.metrics?.recordScriptLoadSuccess("google"),this.debug&&this.logger.debug("script_load_success")}catch(s){throw this.metrics?.recordScriptLoadFailure("google"),this.logger.error("script_load_failure",s),s}}else typeof window<"u"&&window.gtag&&(this.gtag=window.gtag??null);let n=this.gtag;if(!n)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{n("config",s,{send_page_view:!1})}catch(a){o=!0,this.metrics?.recordInitFailure("google"),this.logger.error(`destination_init_failure id=${s}`,a)}this.initialized=!0,o||this.metrics?.recordInitSuccess("google"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-i,{error:p instanceof Error?p.message:String(p)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"gtag unavailable"});let l=n.path??"/",u=n.url??(typeof window<"u"?window.location?.href:void 0)??l,c=typeof document<"u"?document.title:void 0,d=this.getSessionId(),m=0,h=0;for(let p of this.tagIds){let f=le("google",p,"PAGE_VIEW",l,d);if(ue(f)){h+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a("event","page_view",{send_to:p,page_location:u,page_path:l,page_title:c}),m+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(b){this.logger.error(`destination_execute_failure id=${p}`,b)}}return m===0&&h>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:m,deduped:h}}):this.createResult("success",Date.now()-i,{metadata:{sent:m,deduped:h,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var fi="https://analytics.tiktok.com/i18n/pixel/events.js";function as(){return typeof window<"u"?window:null}function fu(){let r=as();if(!r)throw new Error("[TikTokScriptLoader] window unavailable");if(r.ttq)return r.ttq;let e={load(){},page(){},track(){}};return r.TiktokAnalyticsObject="ttq",r.ttq=e,e}var Gt=class{constructor(){this.loaded=!1}async load(e=1e4){if(typeof window>"u"||typeof document>"u")throw new Error("[TikTokScriptLoader] Browser APIs unavailable");let t=fu();return this.loaded?t:(await be({src:fi,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,as()?.ttq??t)}release(){Se(fi)}};var Qt=class extends R{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Gt;this.initialized=!1;this.ttq=null;this.config=t.config,this.getSessionId=t.getSessionId,this.logger=t.logger.forAdapter("TikTokBrowser"),this.metrics=t.metrics,this.debug=t.debug,this.pixelIds=[...new Set(t.config.pixelIds.filter(Boolean))]}supports(t){return this.config.enabled&&this.config.autoPageView!==!1&&this.pixelIds.length>0&&t.type==="PAGE_VIEW"}async ensureInit(t){if(this.initialized||!this.config.enabled||this.pixelIds.length===0)return;if(this.metrics?.recordInitAttempt("tiktok"),this.debug&&this.logger.debug("destination_init_start"),this.config.loadScript!==!1){this.metrics?.recordScriptLoadAttempt("tiktok"),this.debug&&this.logger.debug("script_load_start");try{this.ttq=await this.scriptLoader.load(t),this.metrics?.recordScriptLoadSuccess("tiktok"),this.debug&&this.logger.debug("script_load_success")}catch(o){throw this.metrics?.recordScriptLoadFailure("tiktok"),this.logger.error("script_load_failure",o),o}}else typeof window<"u"&&window.ttq&&(this.ttq=window.ttq??null);let i=this.ttq;if(!i)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let n=!1;for(let o of this.pixelIds)try{i.load(o)}catch(s){n=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,n||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let i=Date.now(),{event:n,signal:o,timeoutMs:s}=t;if(n.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-i,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-i,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(h){return this.createResult("failed",Date.now()-i,{error:h instanceof Error?h.message:String(h)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-i,{error:"ttq unavailable"});let l=n.path??n.url??"/",u=this.getSessionId(),c=0,d=0;if(typeof a.instance=="function")for(let h of this.pixelIds){let p=le("tiktok",h,"PAGE_VIEW",l,u);if(ue(p)){d+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${h}`);continue}try{a.instance(h).page(),c+=1,this.debug&&this.logger.debug(`pageview_sent id=${h}`)}catch(f){this.logger.error(`destination_execute_failure id=${h}`,f)}}else{let h=this.pixelIds[0]??"global",p=le("tiktok",h,"PAGE_VIEW",l,u);if(ue(p))d=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),c=1,this.debug&&this.logger.debug("pageview_sent global")}catch(f){this.logger.error("destination_execute_failure global",f)}}return c===0&&d>0?this.createResult("skipped",Date.now()-i,{skipped:!0,metadata:{sent:c,deduped:d}}):this.createResult("success",Date.now()-i,{metadata:{sent:c,deduped:d,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var jt=class{constructor(e,t,i,n=[]){this.memoryDestination=null;this.active=!1;this.registry=new Pt,this.metrics=new _t,this.logger=new Lt(e),this.pipeline=Bt.identity(),this.debug=t.moduleConfig.debug;let o=new Ot(this.logger,t.moduleConfig.continueOnError),s=new Ft({logger:this.logger,errorHandler:o,hooks:i,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Nt({registry:this.registry,executor:s,metrics:this.metrics,logger:this.logger,concurrency:t.moduleConfig.concurrency});let a=t.moduleConfig.destinations,l=t.moduleConfig.debug;a.console.enabled&&this.registry.register(new Ut({log:l?(u,c)=>this.logger.debug(u,c):()=>{}})),a.memory.enabled&&(this.memoryDestination=new zt,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new Ht),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new $t({config:a.meta,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.google.enabled&&a.google.tagIds.length>0&&this.registry.register(new Wt({config:a.google,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l})),a.tiktok.enabled&&a.tiktok.pixelIds.length>0&&this.registry.register(new Qt({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l}));for(let u of n)this.registry.register(u);this.metrics.setRegisteredCount(this.registry.size())}init(){this.active||(this.active=!0,this.debug&&this.logger.debug("IntegrationEngine initialized (browser destinations)"))}destroy(){this.active&&(this.registry.clear(),this.metrics.reset(),this.dispatcher.clearLastResults(),this.memoryDestination=null,this.active=!1,this.debug&&this.logger.debug("IntegrationEngine destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);if(!t){this.debug&&this.logger.debug(`Event dropped by destination pipeline: ${e.type}`);return}this.dispatcher.dispatch(t)}async handleEventAsync(e){if(!this.active)return[];e.type==="PAGE_VIEW"&&this.metrics.recordPageViewReceived();let t=this.pipeline.process(e);return t?this.dispatcher.dispatch(t):[]}registerDestination(e){this.registry.register(e),this.metrics.setRegisteredCount(this.registry.size())}removeDestination(e){let t=this.registry.remove(e);return this.metrics.setRegisteredCount(this.registry.size()),t}getRegistry(){return this.registry}getMemoryRecords(){return this.memoryDestination?.getRecords()??[]}getDebugState(){return{active:this.active,destinationNames:this.registry.getAll().map(e=>e.name),metrics:this.metrics.getSnapshot(),lastResults:this.dispatcher.getLastResults()}}};var Yt=class{constructor(){this.name="integrations";this.engine=null;this.subscriber=null;this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Integrations module already initialized");return}if(!e.config.modules.integrations.enabled){e.logger.debug("[Pixel] Integrations module disabled");return}let t=e.config.modules.integrations;this.engine=new jt(e.logger,{moduleConfig:{...t,debug:t.debug||e.config.app.debug===!0},getSessionId:()=>e.services.session.getSessionId()??`anon_${e.config.identity.pixelId||"pixel"}`}),this.engine.init(),this.subscriber=new Vt(e.services.dispatcher,i=>this.engine?.handleEvent(i)),this.subscriber.subscribe(),this.active=!0,e.logger.debug("[Pixel] Integrations module initialized")}destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}registerDestination(e){this.engine?.registerDestination(e)}removeDestination(e){return this.engine?.removeDestination(e)??!1}getMemoryRecords(){return this.engine?.getMemoryRecords()??[]}handleEventAsync(e){return this.engine?.handleEventAsync(e)??Promise.resolve([])}};var Xt=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var yi=class{constructor(e,t){this.unsubscribe=null;this.dispatcher=e,this.onEvent=t}subscribe(){this.unsubscribe||(this.unsubscribe=this.dispatcher.subscribe(e=>this.onEvent(e)))}unsubscribeAll(){this.unsubscribe?.(),this.unsubscribe=null}isSubscribed(){return this.unsubscribe!==null}};var vi=class{constructor(){this.buffer=[];this.oldestAt=null}add(e){e.length!==0&&(this.buffer.length===0&&(this.oldestAt=Date.now()),this.buffer.push(...e))}takeBatch(e){if(this.buffer.length===0)return[];let t=e??this.buffer.length,i=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),i}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1:!e.enabled||this.buffer.length>=e.batchSize||this.oldestAt!==null&&Date.now()-this.oldestAt>=e.maxWaitMs}getState(){return{bufferSize:this.buffer.length,oldestEventAt:this.oldestAt,pendingBatches:this.buffer.length}}};var Ne=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function xn(r){return!r.enabled||r.strategy==="identity"?new Ne:new Ne}function ls(r,e,t){return{enabled:r.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Zt=class{constructor(e,t){this.channel=null;this.isLeader=!1;this.leaderTabId=null;this.tabCount=1;this.heartbeatTimer=null;this.onLeaderChange=null;this.storageListener=null;this.transport="none";this.config=e,this.tabId=`tab_${t}_${crypto.randomUUID().slice(0,8)}`,this.channelName=e.channelName??`pixel_transport_coordination_${t}`,this.storageKey=`${this.channelName}:leader`}init(e){if(!this.config.enabled||typeof window>"u"){this.isLeader=!0,this.leaderTabId=this.tabId;return}this.onLeaderChange=e??null,typeof BroadcastChannel<"u"?(this.transport="broadcastChannel",this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=t=>this.handleMessage(t.data)):(this.transport="storageEvents",this.storageListener=t=>{if(!(t.key!==this.storageKey||!t.newValue))try{this.handleMessage(JSON.parse(t.newValue))}catch{}},window.addEventListener("storage",this.storageListener)),this.claimLeadership(),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),2e3)}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.isLeader&&this.releaseLeadership(),this.channel&&(this.channel.close(),this.channel=null),this.storageListener&&typeof window<"u"&&(window.removeEventListener("storage",this.storageListener),this.storageListener=null),this.onLeaderChange=null}canSend(){return this.config.enabled?this.isLeader:!0}shouldPersistOnly(){return this.config.enabled&&!this.isLeader}isTabLeader(){return this.isLeader}getDebugState(){return{enabled:this.config.enabled,tabId:this.tabId,isLeader:this.isLeader,leaderTabId:this.leaderTabId,tabCount:this.tabCount,transport:this.transport}}claimLeadership(){let e={type:"leader_claim",tabId:this.tabId,at:Date.now()};this.broadcast(e),this.leaderTabId||this.setLeader(this.tabId)}releaseLeadership(){let e={type:"leader_release",tabId:this.tabId};this.broadcast(e),this.isLeader&&this.setLeader(null)}sendHeartbeat(){this.isLeader&&this.broadcast({type:"heartbeat",tabId:this.tabId,at:Date.now()})}handleMessage(e){switch(e.type){case"leader_claim":(!this.leaderTabId||e.at<Date.now())&&this.setLeader(e.tabId);break;case"leader_release":this.leaderTabId===e.tabId&&(this.setLeader(null),this.isLeader||this.claimLeadership());break;case"heartbeat":this.tabCount=Math.max(this.tabCount,1),this.leaderTabId===e.tabId&&(this.leaderTabId=e.tabId);break;default:break}}setLeader(e){let t=this.isLeader;this.leaderTabId=e,this.isLeader=e===this.tabId,t!==this.isLeader&&this.onLeaderChange?.(this.isLeader)}broadcast(e){if(this.channel){this.channel.postMessage(e);return}if(typeof window<"u"&&window.localStorage)try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}};var Jt=class{constructor(e){this.entries=[];this.config=e}move(e,t,i=0,n){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:i,lastError:n};return this.entries.push(o),this.entries.length>this.config.maxEntries&&(this.entries=this.entries.slice(-this.config.maxEntries)),o}replayEntry(e){let t=this.entries.findIndex(n=>n.id===e);if(t<0)return null;let[i]=this.entries.splice(t,1);return i?.events??null}replayAll(){let e=this.entries.flatMap(t=>[...t.events]);return this.entries=[],e}clear(){this.entries=[]}getEntries(){return[...this.entries]}getCount(){return this.entries.length}getDebugState(){return{enabled:this.config.enabled,count:this.entries.length,maxEntries:this.config.maxEntries,entries:this.getEntries()}}};var bi=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=null;this.maxWaitTimer=null;this.batchManager=e.batchManager,this.flushManager=e.flushManager,this.retryEngine=e.retryEngine,this.offlineDetector=e.offlineDetector,this.sender=e.sender,this.config=e.config,this.logger=e.logger,this.abortPending=e.abortPending??null,this.onPermanentFailure=e.onPermanentFailure??null}init(){this.active||(this.offlineDetector.init(()=>{this.logger.debug("[TransportDelivery] Online \u2014 resuming"),this.flush()},()=>{this.logger.debug("[TransportDelivery] Offline \u2014 paused")}),this.flushManager.init(()=>this.flush()),this.active=!0)}destroy(){this.active&&(this.abortPending?.(),this.retryEngine.cancelAll(),this.flushManager.destroy(),this.offlineDetector.destroy(),this.clearMaxWaitTimer(),this.batchManager.clear(),this.active=!1,this.inFlight=!1)}ingest(e){!this.active||e.length===0||(this.batchManager.add(e),this.batchManager.shouldFlush(this.config.batch)?this.flush():this.scheduleMaxWaitFlush())}flush(){!this.active||!this.offlineDetector.isOnline()||(this.clearMaxWaitTimer(),this.processBatch())}getDebugState(){return{batch:this.batchManager.getState(),retry:this.retryEngine.getState(),offline:this.offlineDetector.getState(),flush:this.flushManager.getState(),timeoutMs:this.config.timeoutMs,inFlight:this.inFlight,ackCount:this.ackCount}}getOfflineDetector(){return this.offlineDetector}async processBatch(){if(this.inFlight||!this.offlineDetector.isOnline())return;let e=this.batchManager.takeBatch(this.config.batch.enabled?this.config.batch.batchSize:1);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e,{deliveryMode:this.config.batch.enabled&&e.length>1?"batch":"single"});if(!t.ack)throw new Error("[TransportDelivery] Send not acknowledged");this.ackCount+=t.eventCount},`delivery-${Date.now()}`)}catch(t){this.logger.error("[TransportDelivery] Delivery failed after retries",t),this.onPermanentFailure?this.onPermanentFailure(e,t):this.batchManager.add(e)}finally{this.inFlight=!1,this.batchManager.size()>0&&this.offlineDetector.isOnline()&&this.flush()}}}scheduleMaxWaitFlush(){if(!this.config.batch.enabled||this.maxWaitTimer!==null||this.config.batch.maxWaitMs<=0){this.config.batch.maxWaitMs<=0&&this.flush();return}this.maxWaitTimer=setTimeout(()=>{this.maxWaitTimer=null,this.flush()},this.config.batch.maxWaitMs)}clearMaxWaitTimer(){this.maxWaitTimer!==null&&(clearTimeout(this.maxWaitTimer),this.maxWaitTimer=null)}};var Si=class{constructor(e){this.onFlush=null;this.intervalId=null;this.flushCount=0;this.lastFlushAt=null;this.listeners=[];this.config=e}init(e){this.onFlush=e,this.config.flushIntervalMs>0&&(this.intervalId=setInterval(()=>this.flush(),this.config.flushIntervalMs)),this.config.prepareUnloadHooks&&this.registerUnloadHooks()}flush(){this.onFlush&&(this.flushCount+=1,this.lastFlushAt=Date.now(),this.onFlush())}destroy(){this.config.flushOnDestroy&&this.flush(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.removeListeners(),this.onFlush=null}getState(){return{flushCount:this.flushCount,lastFlushAt:this.lastFlushAt,intervalActive:this.intervalId!==null}}registerUnloadHooks(){if(typeof window>"u")return;let e=()=>this.flush();for(let t of["pagehide","beforeunload"])window.addEventListener(t,e),this.listeners.push({target:"window",type:t,handler:e});typeof document<"u"&&(document.addEventListener("visibilitychange",e),this.listeners.push({target:"document",type:"visibilitychange",handler:e}))}removeListeners(){for(let e of this.listeners)e.target==="window"&&typeof window<"u"?window.removeEventListener(e.type,e.handler):e.target==="document"&&typeof document<"u"&&document.removeEventListener(e.type,e.handler);this.listeners.length=0}};var Ei=class{constructor(){this.online=!0;this.paused=!1;this.simulatedOffline=!1;this.onOnline=null;this.onOffline=null;this.listeners=[]}init(e,t){if(this.onOnline=e,this.onOffline=t,typeof window>"u")return;this.online=typeof navigator>"u"?!0:navigator.onLine;let i=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},n=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",i),window.addEventListener("offline",n),this.listeners.push({type:"online",handler:i},{type:"offline",handler:n})}isOnline(){return this.online&&!this.simulatedOffline}isPaused(){return this.paused||this.simulatedOffline}destroy(){if(typeof window<"u")for(let e of this.listeners)window.removeEventListener(e.type,e.handler);this.listeners.length=0,this.onOnline=null,this.onOffline=null}simulateOffline(e){this.simulatedOffline=e,e?(this.paused=!0,this.onOffline?.()):(this.paused=!1,this.online=!0,this.onOnline?.())}getState(){return{isOnline:this.isOnline(),paused:this.isPaused(),simulatedOffline:this.simulatedOffline}}};var er=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,i){return this.enabled&&(this.globalSequence+=1,this.sessionSequence+=1),t&&(this.lastCorrelationId=t),{id:crypto.randomUUID(),event:e,sequence:this.globalSequence,sessionSequence:this.sessionSequence,correlationId:t??this.lastCorrelationId??void 0,transactionGroup:i,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,i)=>t.sequence!==i.sequence?t.sequence-i.sequence:t.enqueuedAt-i.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),i=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,i);let n=[...e].reverse().find(o=>o.correlationId);n?.correlationId&&(this.lastCorrelationId=n.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var Ci=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var xi=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var Ti=class{constructor(){this.name="validate"}process(e){return!e.type||typeof e.type!="string"||typeof e.timestamp!="number"||Number.isNaN(e.timestamp)?null:e}};var Ii=class r{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new r([new Ti,new xi,new Ci(e)])}process(e){let t=[],i=e;for(let n of this.stages){if(t.push(n.name),!i)break;i=n.process(i)}return this.lastSteps=t,{event:i,steps:t}}getLastSteps(){return this.lastSteps}};var Ai=class{constructor(e,t,i){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=i}async init(){await this.storage.init();let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}destroy(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.flushPersist(),this.storage.destroy(),this.records=[],this.loaded=!1}enqueue(e){this.ensureLoaded();let t=this.backpressure.evaluateEnqueue(this.records.length);if(!t.accepted||(t.policy==="drop_oldest"&&this.records.length>0&&this.records.shift(),t.policy==="drop_newest"&&t.dropped>0))return;let i=this.ordering.assign(e),n=this.backpressure.applyPolicy(this.records,i);this.records=n.items,this.schedulePersist()}dequeue(){this.ensureLoaded();let e=this.records.shift();return this.schedulePersist(),e?.event}peek(){return this.ensureLoaded(),this.records[0]?.event}size(){return this.ensureLoaded(),this.records.length}clear(){this.records=[],this.schedulePersist()}remove(e){this.ensureLoaded();let t=this.records.length;this.records=this.records.filter(n=>!e(n.event));let i=t-this.records.length;return i>0&&this.schedulePersist(),i}isEmpty(){return this.size()===0}getAll(){return this.ensureLoaded(),this.records.map(e=>e.event)}getRecords(){return this.ensureLoaded(),[...this.records]}importRecords(e){this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.schedulePersist()}exportRecords(){return this.getRecords()}getStorageAdapterName(){return this.storage.getAdapterName()}async reload(){let e=await this.storage.load();this.records=this.ordering.sort(e),this.ordering.restoreFromRecords(this.records),this.loaded=!0}ensureLoaded(){this.loaded||(this.loaded=!0)}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.flushPersist()},0)}async flushPersist(){await this.storage.save(this.records)}};var Di=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.shift()}peek(){return this.items[0]}size(){return this.items.length}clear(){this.items.length=0}remove(e){let t=this.items.length,i=this.items.filter(n=>!e(n));return this.items.length=0,this.items.push(...i),t-i.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var Ee=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var tr=class{constructor(e){this.storageKey=e}init(){}destroy(){}load(){if(typeof window>"u"||!window.localStorage)return[];try{let e=window.localStorage.getItem(this.storageKey);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}save(e){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(this.storageKey,JSON.stringify(e))}catch{}}getAdapterName(){return"LocalStorageQueueStorage"}isAvailable(){if(typeof window>"u")return!1;try{let e=`${this.storageKey}__probe`;return window.localStorage.setItem(e,"1"),window.localStorage.removeItem(e),!0}catch{return!1}}};var Be="queue_records",rr=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let i=indexedDB.open(this.dbName,1);i.onupgradeneeded=()=>{let n=i.result;n.objectStoreNames.contains(Be)||n.createObjectStore(Be,{keyPath:"id"})},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error??new Error("IndexedDB open failed"))}))}destroy(){this.db?.close(),this.db=null}async load(){return this.db?new Promise((e,t)=>{let o=this.db.transaction(Be,"readonly").objectStore(Be).getAll();o.onsuccess=()=>{let s=o.result;e(Array.isArray(s)?s:[])},o.onerror=()=>t(o.error??new Error("IndexedDB load failed"))}):[]}async save(e){this.db&&await new Promise((t,i)=>{let n=this.db.transaction(Be,"readwrite"),o=n.objectStore(Be),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},n.oncomplete=()=>t(),n.onerror=()=>i(n.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function yu(r){let e=r.prefix??"__gmk",t=r.namespace||"pixel",i=r.pixelId||"default";return`${e}:${t}:${i}:transport-queue`}function vu(r){let e=r.namespace||"pixel",t=r.pixelId||"default";return`${e}_${t}_transport_queue`}function bu(r,e){let t=yu(e);switch(r){case"localStorage":return new tr(t);case"indexedDB":return new rr(vu(e));case"memory":default:return new Ee}}function Su(r){let e=["indexedDB","localStorage","memory"];if(!r||r==="memory")return e;let t=e.filter(i=>i!==r);return[r,...t]}function us(r){if(typeof window>"u")return new Ee;let e=Su(r.preferred);for(let t of e){let i=bu(t,r);if(i.isAvailable())return i}return new Ee}function Tn(r){return us({preferred:r.storage.queue?.persistence,namespace:r.storage.namespace,prefix:r.storage.prefix,pixelId:r.identity.pixelId})}var ir=class{constructor(e,t){this.lastTrigger=null;this.lastReplayAt=null;this.totalReplayed=0;this.onReplay=null;this.config=e,this.queue=t}setReplayHandler(e){this.onReplay=e}async replay(e){if(!this.config.enabled)return 0;await this.queue.reload();let t=this.queue.size();return this.lastTrigger=e,this.lastReplayAt=Date.now(),this.totalReplayed+=t,t>0&&this.onReplay?.(),t}getPendingEvents(){return this.queue.getAll()}getDebugState(){return{enabled:this.config.enabled,lastTrigger:this.lastTrigger,lastReplayAt:this.lastReplayAt,totalReplayed:this.totalReplayed,pendingCount:this.queue.size()}}};var nr=class{constructor(e){this.totalDropped=0;this.totalRejected=0;this.totalSampled=0;this.config=e}evaluateEnqueue(e){if(!this.config.enabled||this.config.policy==="none")return{accepted:!0,dropped:0,policy:this.config.policy};if(e<this.config.maxQueueSize)return{accepted:!0,dropped:0,policy:this.config.policy};switch(this.config.policy){case"reject_new":return this.totalRejected+=1,{accepted:!1,dropped:0,policy:this.config.policy,reason:"queue_full_reject_new"};case"sample":{let t=this.config.sampleRate??.5,i=Math.random()<t;return i||(this.totalSampled+=1),{accepted:i,dropped:i?0:1,policy:this.config.policy,reason:i?void 0:"sampled_out"}}case"drop_oldest":case"drop_newest":return{accepted:!0,dropped:1,policy:this.config.policy};default:return{accepted:!0,dropped:0,policy:"none"}}}applyPolicy(e,t){let i=this.evaluateEnqueue(e.length);return i.accepted?e.length<this.config.maxQueueSize?{items:[...e,t],dropped:0}:this.config.policy==="drop_oldest"?(this.totalDropped+=1,{items:[...e.slice(1),t],dropped:1}):this.config.policy==="drop_newest"?(this.totalDropped+=1,{items:e,dropped:1}):{items:[...e,t],dropped:0}:{items:e,dropped:i.dropped}}getDebugState(e){return{enabled:this.config.enabled,currentSize:e,maxQueueSize:this.config.maxQueueSize,policy:this.config.policy,totalDropped:this.totalDropped,totalRejected:this.totalRejected,totalSampled:this.totalSampled}}};var or=class{constructor(e){this.state="closed";this.consecutiveFailures=0;this.totalFailures=0;this.totalSuccesses=0;this.totalBlocked=0;this.halfOpenAttempts=0;this.lastFailureAt=null;this.lastSuccessAt=null;this.openedAt=null;this.config=e}canExecute(){return!this.config.enabled||this.state==="closed"?!0:this.state==="open"?this.openedAt!==null&&Date.now()-this.openedAt>=this.config.resetTimeoutMs?(this.state="half_open",this.halfOpenAttempts=0,!0):(this.totalBlocked+=1,!1):this.halfOpenAttempts<this.config.halfOpenMaxAttempts}recordSuccess(){this.config.enabled&&(this.totalSuccesses+=1,this.lastSuccessAt=Date.now(),this.consecutiveFailures=0,this.halfOpenAttempts=0,this.state="closed",this.openedAt=null)}recordFailure(){if(this.config.enabled){if(this.totalFailures+=1,this.lastFailureAt=Date.now(),this.consecutiveFailures+=1,this.state==="half_open"){this.halfOpenAttempts+=1,this.halfOpenAttempts>=this.config.halfOpenMaxAttempts&&this.open();return}this.consecutiveFailures>=this.config.failureThreshold&&this.open()}}forceOpen(){this.open()}forceClose(){this.state="closed",this.consecutiveFailures=0,this.halfOpenAttempts=0,this.openedAt=null}getMetrics(){return{state:this.state,consecutiveFailures:this.consecutiveFailures,totalFailures:this.totalFailures,totalSuccesses:this.totalSuccesses,totalBlocked:this.totalBlocked,lastFailureAt:this.lastFailureAt,lastSuccessAt:this.lastSuccessAt,openedAt:this.openedAt}}open(){this.state="open",this.openedAt=Date.now()}};var sr=class{constructor(e,t){this.circuitBreaker=e,this.inner=t}async send(e,t){if(!this.circuitBreaker.canExecute())throw new Error("[CircuitBreakerSender] Circuit is open \u2014 send blocked");try{let i=await this.inner.send(e,t);return i.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),i}catch(i){throw this.circuitBreaker.recordFailure(),i}}getCircuitBreaker(){return this.circuitBreaker}};function cs(r,e){let t=e.baseDelayMs*e.multiplier**(r-1);return Math.min(t,e.maxDelayMs)}var wi=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let i=t??`retry-${++this.idCounter}`;return new Promise((n,o)=>{let s=!1,a={id:i,task:e,attempt:0,status:"pending",nextRetryAt:null,timer:null,abort:()=>{s=!0,a.timer&&clearTimeout(a.timer),a.status="cancelled",a.timer=null,this.entries.delete(i),n()}};this.entries.set(i,a);let l=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(i),n()}catch(u){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(i),o(u);return}let c=cs(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+c,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${c}ms`),a.timer=setTimeout(()=>{a.timer=null,l()},c)}}};l()})}cancel(e){this.entries.get(e)?.abort()}cancelAll(){for(let e of this.entries.values())e.abort();this.entries.clear()}getState(){return{pendingCount:this.entries.size,attempts:Array.from(this.entries.values()).map(e=>({id:e.id,attempt:e.attempt,nextRetryAt:e.nextRetryAt,status:e.status}))}}};function ce(r){return r?Object.values(r).some(e=>typeof e=="string"&&e.trim().length>0):!1}function In(r){return{...r}}function Eu(r){return{source:String(r.app.source??""),target:String(r.app.target??""),platform:String(r.app.platform??""),environment:String(r.app.environment??"")}}function ds(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function Cu(r){if("category"in r&&r.category){if(r.category==="ENGAGEMENT")return"ENGAGEMENT";if(r.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function xu(r,e){let t;if("data"in r&&r.data&&typeof r.data=="object")t={...r.data};else{let{type:i,timestamp:n,category:o,path:s,url:a,hostname:l,language:u,timezone:c,identifiers:d,queryParams:m,urlContext:h,customer:p,...f}=r;t=Object.keys(f).length>0?f:void 0}return ce(e)?{...t??{},customer:{...e}}:t}function Tu(r){let e={fbp:r?.fbp??"",fbc:r?.fbc??"",ga:r?.ga??"",gcl_au:r?.gclAu??""};return r?{...e,fbclid:r.fbclid??"",gclid:r.gclid??"",gbraid:r.gbraid??"",wbraid:r.wbraid??"",gid:r.gid??"",ttclid:r.ttclid??"",ttp:r.ttp??"",msclkid:r.msclkid??"",li_fat_id:r.liFatId??"",epik:r.epik??"",customClickIds:r.customClickIds??{},landingUrl:r.landingUrl??"",referrer:r.referrer??"",firstCollectedAt:r.firstCollectedAt??0,lastCollectedAt:r.lastCollectedAt??0}:e}var ki=class{constructor(e){this.context=e}buildApiEvent(e,t){let i=this.context.config,n=this.context.services,o=n.browserMetadata.getMetadata(),s=n.visitor.getVisitorId()??n.visitor.ensureVisitorId(),a=n.session.getSessionId()??`session_${i.identity.pixelId||"anonymous"}_${Date.now()}`,l=n.fingerprint.getFingerprint()??n.fingerprint.ensureFingerprint(),u="identifiers"in e&&e.identifiers?e.identifiers:n.attribution?.getSnapshot(),c="customer"in e&&e.customer?e.customer:n.customerIdentity?.getSnapshot()??null;return{id:t??ds(),session_id:a,visitor_id:s,pixel_code:i.identity.pixelId,type:e.type,category:Cu(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:Tu(u),page:{url:e.url??o.url??"",title:typeof document<"u"?document.title:"",referrer:typeof document<"u"?document.referrer:"",path:e.path??o.path??"",hostname:e.hostname??o.hostname??""},device:{id:l,type:"desktop",os:{name:"Unknown",version:""},browser:{name:"Unknown",version:""},engine:{name:"Unknown",version:""},userAgent:o.userAgent??"",language:e.language??o.language??"",screen:{width:o.screenWidth??0,height:o.screenHeight??0,pixel_ratio:1}},...ce(c)?{customer:{...c}}:{},data:xu(e,c),..."queryParams"in e&&e.queryParams&&Object.keys(e.queryParams).length>0?{query_params:{...e.queryParams}}:{},..."urlContext"in e&&e.urlContext?{url_context:{...e.urlContext.managed?{managed:{...e.urlContext.managed}}:{},...e.urlContext.forwarded?{forwarded:{...e.urlContext.forwarded}}:{},...e.urlContext.source?{source:{...e.urlContext.source}}:{}}}:{},app:Eu(i),meta:{version:"2.0.0",pixel_source:"pixel-v2",source:String(i.app.source??""),target:String(i.app.target??""),platform:String(i.app.platform??""),environment:i.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:i.identity.projectId??"",pageId:i.identity.pageId??""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),i=e.map(n=>this.buildApiEvent(n));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:ds(),sent_at:Date.now(),app:t.app,meta:t.meta,events:i}}};async function ms(r,e={}){let{timeoutMs:t=1e4,signal:i,...n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);i&&(i.aborted?o.abort():i.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(r,{...n,signal:o.signal})}finally{clearTimeout(s)}}var Ve=class{constructor(e,t,i,n){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=i,this.logger=n}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(t?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let i=t?.deliveryMode??(e.length>1?"batch":"single");if(i==="single"&&e.length>1)return this.sendIndividually(e,t);if(i==="batch"&&!this.config.batchEndpoint){if(this.config.batchFallback==="single")return this.sendIndividually(e,t);throw new Error("[HttpSender] Batch endpoint is not configured.")}let n=i==="batch"&&e.length>1,o=n?this.config.batchEndpoint:this.config.eventEndpoint,s=JSON.stringify(n?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),a=this.compression.compress(s);this.lastCompression={originalSize:a.originalSize,compressedSize:a.compressedSize};try{let l=await ms(o,{method:"POST",headers:{...this.config.headers,"Content-Type":"application/json","Content-Encoding":a.encoding},body:a.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),u=await l.json().catch(()=>({})),c=l.ok;if(this.lastAck=c,c&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:ps(o),status:l.status,ack:c,eventCount:e.length,body:u}),!c)throw new Error(`[HttpSender] HTTP ${l.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(l){let u=l instanceof Error?l.message:String(l);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:ps(o),status:0,ack:!1,eventCount:e.length,error:u}),l}}getState(){return{sentCount:this.sentCount,logs:this.responseLogs.map(e=>`[HttpSender] ${e.status} ack=${e.ack} events=${e.eventCount}${e.error?` err=${e.error}`:""}`),lastAck:this.lastAck,responses:[...this.responseLogs],compression:this.lastCompression,mode:this.config.mode}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}async sendIndividually(e,t){let i=0;for(let n of e){let o=await this.send([n],{...t,deliveryMode:"single"});if(!o.ack)throw new Error("[HttpSender] Individual send not acknowledged.");i+=o.eventCount}return{ack:!0,eventCount:i}}};function ps(r){try{return new URL(r).origin}catch{return"[Present]"}}var Ue=class r{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.sentCount=0;this.lastAck=null;this.logger=e,this.options={capture:t.capture??!0,response:t.response??"success",delayMs:hs(t.delayMs),failUntilAttempt:t.failUntilAttempt,simulateTimeout:t.simulateTimeout}}static fromConfig(e,t){return new r(e,t)}async send(e,t){if(e.length===0)return{ack:!0,eventCount:0};if(Iu(t?.signal),this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw this.lastAck=!1,new Error(`[TestSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw this.lastAck=!1,new DOMException("The operation was aborted.","AbortError");if(await this.waitWithAbort(t?.signal),this.options.response==="failure")throw this.lastAck=!1,new Error("[TestSender] Simulated failure response");return this.options.capture&&this.sentBatches.push([...e]),this.sentCount+=e.length,this.lastAck=!0,this.logger.debug(`[TestSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentCount}getLogs(){return this.sentBatches.map(e=>`[TestSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck,mode:"test",capturedBatches:this.getSentBatches(),attempts:this.sendAttempts}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.sentCount=0,this.lastAck=null}configure(e){e.capture!==void 0&&(this.options.capture=e.capture),e.response!==void 0&&(this.options.response=e.response),e.delayMs!==void 0&&(this.options.delayMs=hs(e.delayMs)),"failUntilAttempt"in e&&(this.options.failUntilAttempt=e.failUntilAttempt),e.simulateTimeout!==void 0&&(this.options.simulateTimeout=e.simulateTimeout)}waitWithAbort(e){let t=this.options.delayMs??0;return t===0?Promise.resolve():new Promise((i,n)=>{let o=setTimeout(()=>{a(),i()},t),s=()=>{a(),n(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted)return s();e?.addEventListener("abort",s,{once:!0})})}};function hs(r){return Math.max(0,r??0)}function Iu(r){if(r?.aborted)throw new DOMException("The operation was aborted.","AbortError")}var Au="/pixels/public/event",Du="/pixels/public/event/batch";function gs(r,e){let t=An(r.baseUrl?.trim()||Rr,"transport.sender.baseUrl").replace(/\/+$/,"");return{mode:"internal",eventEndpoint:`${t}${Au}`,batchEndpoint:`${t}${Du}`,batchFallback:"error",headers:{},timeoutMs:e}}function fs(r,e,t){let i=An(r.endpoints.event,"transport.sender.endpoints.event"),n=r.endpoints.batch?An(r.endpoints.batch,"transport.sender.endpoints.batch"):void 0,o=r.batchFallback??"single";if(e.enabled&&!n&&o==="error")throw new Error('[Transport] Batch is enabled but transport.sender.endpoints.batch is missing. Provide endpoints.batch, disable batch, or use batchFallback: "single".');return{mode:"external",eventEndpoint:i,batchEndpoint:n,batchFallback:o,headers:wu(r.headers),timeoutMs:t}}function An(r,e){let t=r.trim();if(!t)throw new Error(`[Transport] ${e} must not be empty.`);let i;try{i=new URL(t)}catch{throw new Error(`[Transport] ${e} must be an absolute HTTP(S) URL.`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`[Transport] ${e} must use HTTP or HTTPS.`);return t}function wu(r){if(!r)return{};let e={};for(let[t,i]of Object.entries(r)){let n=t.toLowerCase();n==="content-type"||n==="content-encoding"||(e[t]=i)}return e}function ys(r){let{senderConfig:e}=r;if(e.mode==="test"){let n=Ue.fromConfig(r.logger,e);return{sender:n,mode:"test",testSender:n,httpSender:null}}let t=e.mode==="internal"?gs(e,r.timeoutMs):fs(e,r.batchConfig,r.timeoutMs),i=new Ve(t,r.payloadBuilder,r.compression,r.logger);return{sender:i,mode:e.mode,testSender:null,httpSender:i}}var Ri=class{constructor(e,t){this.abortController=null;this.inner=e,this.timeoutMs=t.timeoutMs}async send(e,t){this.abortController?.abort(),this.abortController=new AbortController;let i=this.abortController,n=[i.signal,t?.signal].filter(Boolean),o=ku(n),s=setTimeout(()=>i.abort(),this.timeoutMs);try{return await this.inner.send(e,{...t,signal:o})}finally{clearTimeout(s),this.abortController===i&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function ku(r){if(r.length===0)return;if(r.length===1)return r[0];let e=new AbortController;for(let t of r){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var Mi=class{constructor(e,t,i){this.active=!1;this.context=e;let n=e.config.transport;if(this.orderingManager=new er({enabled:n.ordering.enabled}),this.backpressureManager=new nr({enabled:n.backpressure.enabled,maxQueueSize:n.backpressure.maxQueueSize,policy:n.backpressure.policy,sampleRate:n.backpressure.sampleRate}),this.deadLetterManager=new Jt({enabled:n.deadLetter.enabled,maxEntries:n.deadLetter.maxEntries}),this.circuitBreaker=new or({enabled:n.circuitBreaker.enabled,failureThreshold:n.circuitBreaker.failureThreshold,resetTimeoutMs:n.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:n.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Zt({enabled:n.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(n.persistence.enabled){let p=Tn(e.config);this.persistentQueue=new Ai(p,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new Di;this.pipeline=Ii.createDefault(this.queue);let o=xn(n.compression),s=new ki(e),a=i?null:ys({senderConfig:n.sender,batchConfig:n.batch,timeoutMs:n.timeout.timeoutMs,payloadBuilder:s,compression:o,logger:e.logger});this.senderMode=i?"injected":a.mode,this.testSender=i instanceof Ue?i:a?.testSender??null,this.httpSender=i instanceof Ve?i:a?.httpSender??null;let l=i??a.sender;n.circuitBreaker.enabled&&(l=new sr(this.circuitBreaker,l));let u=null;n.timeout.enabled&&(u=new Ri(l,{timeoutMs:n.timeout.timeoutMs}),l=u),this.timedSender=u,this.sender=l,this.persistentQueue?(this.replayManager=new ir({enabled:n.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null;let c=new vi,d=new Si({flushIntervalMs:n.flush.enabled?n.flush.flushIntervalMs:0,flushOnDestroy:n.flush.flushOnDestroy,prepareUnloadHooks:n.flush.enabled&&n.flush.prepareUnloadHooks}),m=new wi({maxAttempts:n.retry.enabled?n.retry.maxAttempts:1,baseDelayMs:n.retry.baseDelayMs,maxDelayMs:n.retry.maxDelayMs,multiplier:n.retry.multiplier},e.logger),h=new Ei;this.delivery=new bi({batchManager:c,flushManager:d,retryEngine:m,offlineDetector:h,sender:this.sender,config:{batch:{...n.batch},timeoutMs:n.timeout.timeoutMs},logger:e.logger,abortPending:()=>u?.abortPending(),onPermanentFailure:n.deadLetter.enabled?(p,f)=>{this.deadLetterManager.move(p,"max_retries_exceeded",n.retry.enabled?n.retry.maxAttempts:1,f instanceof Error?f.message:String(f))}:void 0})}async init(){this.active||(this.persistentQueue&&await this.persistentQueue.init(),this.coordinationManager.init(e=>{e&&(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}),this.delivery?.init(),this.replayManager&&await this.replayManager.replay("init"),this.active=!0,this.context.logger.debug("[TransportEngine] Initialized"))}destroy(){this.active&&(this.timedSender?.abortPending(),this.delivery?.destroy(),this.coordinationManager.destroy(),this.persistentQueue?this.persistentQueue.destroy():this.queue.clear(),this.testSender?.clear(),this.httpSender?.clear(),this.active=!1,this.context.logger.debug("[TransportEngine] Destroyed"))}isActive(){return this.active}handleEvent(e){if(!this.active)return;if(!this.pipeline.process(e).event){this.context.logger.debug("[TransportEngine] Event dropped by pipeline");return}this.coordinationManager.shouldPersistOnly()||this.forwardQueuedEvents()}manualFlush(){this.delivery?.flush()}simulateOffline(e){this.delivery?.getOfflineDetector().simulateOffline(e),e||(this.replayManager?.replay("reconnect"),this.forwardQueuedEvents())}configureTestSender(e){this.testSender?.configure(e)}async simulateReload(){await this.replayManager?.replay("reload"),this.forwardQueuedEvents()}async simulateRestart(){await this.replayManager?.replay("restart"),this.forwardQueuedEvents()}forceCircuitOpen(){this.circuitBreaker.forceOpen()}forceCircuitClose(){this.circuitBreaker.forceClose()}async manualReplay(){let e=await this.replayManager?.replay("manual")??0;return this.forwardQueuedEvents(),e}replayDeadLetter(){let e=this.deadLetterManager.replayAll();if(e.length>0){for(let t of e)this.queue.enqueue(t);this.forwardQueuedEvents()}return e}clearDeadLetter(){this.deadLetterManager.clear()}exportQueue(){return this.persistentQueue?JSON.stringify(this.persistentQueue.exportRecords(),null,2):JSON.stringify(this.queue.getAll(),null,2)}importQueue(e){let t=JSON.parse(e);if(this.persistentQueue&&Array.isArray(t)&&t[0]?.event)return this.persistentQueue.importRecords(t),t.length;if(Array.isArray(t)){this.queue.clear();for(let i of t)this.queue.enqueue(i);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.testSender?.getState()??null;return{queueSize:this.queue.size(),queueContents:this.queue.getAll(),pipelineSteps:this.pipeline.getLastSteps(),senderLogs:e?.logs??[],sentCount:e?.sentCount??0,delivery:this.delivery?.getDebugState()??null,sender:e,advanced:{storage:{adapter:this.persistentQueue?.getStorageAdapterName()??"MemoryQueue",persistenceEnabled:this.persistentQueue!==null,recordCount:this.persistentQueue?.getRecords().length??this.queue.size()},replay:this.replayManager?.getDebugState()??{enabled:!1,lastTrigger:null,lastReplayAt:null,totalReplayed:0,pendingCount:0},ordering:this.orderingManager.getDebugState(this.queue.size()),coordination:this.coordinationManager.getDebugState(),circuitBreaker:this.circuitBreaker.getMetrics(),backpressure:this.backpressureManager.getDebugState(this.queue.size()),deadLetter:this.deadLetterManager.getDebugState(),compression:ls(this.context.config.transport.compression,xn(this.context.config.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let t=this.queue.dequeue();t&&e.push(t)}e.length!==0&&this.delivery.ingest(e)}};var ar=class{constructor(){this.name="transport";this.engine=null;this.subscriber=null;this.active=!1}async init(e){if(this.active){e.logger.debug("[Pixel] Transport module already initialized");return}if(!e.config.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new Mi(e),await this.engine.init(),this.subscriber=new yi(e.services.dispatcher,t=>this.engine?.handleEvent(t)),this.subscriber.subscribe(),this.active=!0}async destroy(){this.active&&(this.subscriber?.unsubscribeAll(),this.subscriber=null,this.engine?.destroy(),this.engine=null,this.active=!1)}getDebugState(){return this.engine?.getDebugState()??null}isEngineActive(){return this.engine?.isActive()??!1}manualFlush(){this.engine?.manualFlush()}simulateOffline(e){this.engine?.simulateOffline(e)}configureTestSender(e){this.engine?.configureTestSender(e)}simulateReload(){return this.engine?.simulateReload()??Promise.resolve()}simulateRestart(){return this.engine?.simulateRestart()??Promise.resolve()}forceCircuitOpen(){this.engine?.forceCircuitOpen()}forceCircuitClose(){this.engine?.forceCircuitClose()}manualReplay(){return this.engine?.manualReplay()??Promise.resolve(0)}replayDeadLetter(){return this.engine?.replayDeadLetter()??[]}clearDeadLetter(){this.engine?.clearDeadLetter()}exportQueue(){return this.engine?.exportQueue()??"[]"}importQueue(e){return this.engine?.importQueue(e)??0}};var lr=class{constructor(){this.modules=[]}register(e){if(this.modules.some(t=>t.name===e.name))throw new Error(`[Pixel] Module "${e.name}" is already registered`);this.modules.push(e)}getAll(){return this.modules}size(){return this.modules.length}};var ur=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[i,n]of Object.entries(e)){if(typeof n!="string")continue;let o=n.trim();o&&(t[i]=o)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return ce(this.snapshot)?In(this.snapshot):null}clear(){this.snapshot={}}};var Ru=200,cr=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new q}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},Ru)}};var dr=class{constructor(e,t,i,n){this.metadataService=e,this.attribution=t??null,this.urlContext=i??null,this.customerIdentity=n??null}build(e){let t=this.metadataService.getMetadata(),i=this.attribution?.getSnapshot(),n=i!==void 0&&Object.keys(i).some(d=>{let m=i[d];return m!=null&&m!==""}),o=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=o!==null&&Object.keys(o.queryParams).length>0,a=o!==null&&(o.urlContext.managed&&Object.keys(o.urlContext.managed).length>0||o.urlContext.forwarded&&Object.keys(o.urlContext.forwarded).length>0||o.urlContext.source&&Object.keys(o.urlContext.source).length>0),l=this.customerIdentity?.getSnapshot()??null,c=e.customer??l;return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...n?{identifiers:i}:{},...s?{queryParams:{...o.queryParams}}:{},...a?{urlContext:{...o.urlContext.managed?{managed:{...o.urlContext.managed}}:{},...o.urlContext.forwarded?{forwarded:{...o.urlContext.forwarded}}:{},...o.urlContext.source?{source:{...o.urlContext.source}}:{}}}:{},...ce(c)?{customer:{...c}}:{}}}};var mr=class{constructor(e){this.debugEnabled=e}debug(...e){this.debugEnabled&&(typeof console>"u"||console.debug(...e))}info(...e){typeof console>"u"||console.info(...e)}warn(...e){typeof console>"u"||console.warn(...e)}error(...e){typeof console>"u"||console.error(...e)}};var pr={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},Dn="attribution";var Mu=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],hr=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),i={},n={};for(let o of Mu){let s=t.get(o);s&&(o==="li_fat_id"?i.liFatId=s:i[o]=s)}for(let o of e){let s=t.get(o);s&&(n[o]=s)}return Object.keys(n).length>0&&(i.customClickIds=n),i}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var gr=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},i={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[n,o]of Object.entries(i)){let s=e[n];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[i,...n]=t.trim().split("=");return i&&(e[i]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var fr=class{constructor(e={}){this.clickIdParser=new hr;this.cookieCollector=new gr;this.customParams=e.customParams??[],this.captureUrlParams=e.captureUrlParams!==!1,this.captureCookies=e.captureCookies!==!1}collectFresh(){let e=this.captureUrlParams?this.clickIdParser.parse(this.customParams):{},t=this.captureCookies?this.cookieCollector.collectKnown():{},i={...t,...e},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(i.customClickIds=n),typeof i.fbclid=="string"&&i.fbclid){let o=this.clickIdParser.synthesizeFbc(i.fbclid,typeof i.fbc=="string"?i.fbc:void 0);o&&(i.fbc=o)}if(typeof window<"u")try{i.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(i.referrer=document.referrer)}catch{}return i}merge(e,t){let i={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){i.customClickIds={...e.customClickIds??{},...s};continue}i[o]=s}let n=Date.now();return e.firstCollectedAt||(i.firstCollectedAt=n),i.lastCollectedAt=n,i}};var yr=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??Dn}load(){if(!this.persist)return null;try{let e=this.storage.get(this.storageKey);return e?this.isExpired(e)?(this.clear(),null):e:null}catch{return null}}save(e){if(this.persist)try{this.storage.set(this.storageKey,e)}catch{}}clear(){try{this.storage.remove(this.storageKey)}catch{}}isExpired(e){let t=e.lastCollectedAt??e.firstCollectedAt;return t?Date.now()-t>this.ttlMs:!1}};var vr=class{constructor(e,t=pr){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new yr(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new fr({customParams:t.customClickIdParams??[],captureUrlParams:t.captureUrlParams!==!1,captureCookies:t.captureCookies!==!1})}init(){if(this.active||(this.active=!0,!this.enabled))return;let e=this.store.load();e&&(this.snapshot=e),this.collect()}destroy(){this.active&&(this.active=!1)}collect(){if(!this.enabled)return this.snapshot;let e=this.collector.collectFresh();return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.snapshot}getSnapshot(){return{...this.snapshot}}update(e){return this.snapshot=this.collector.merge(this.snapshot,e),this.store.save(this.snapshot),this.getSnapshot()}clear(){this.snapshot={},this.store.clear()}};var Pi=class{getMetadata(){if(typeof window>"u")return{};let e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}})();return{url:location.href,path:location.pathname,hostname:location.hostname,origin:location.origin,title:typeof document<"u"?document.title:void 0,referrer:typeof document<"u"?document.referrer:void 0,language:navigator.language,timezone:e,userAgent:navigator.userAgent,platform:navigator.platform,screenWidth:screen.width,screenHeight:screen.height,colorDepth:screen.colorDepth}}};var _i=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let i=0;i<t.length;i+=1){let n=t[i];if(n)try{n(e)}catch(o){this.logger?.warn(Pu(o,e.type,i))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function Pu(r,e,t){let i=r instanceof Error?r.name:typeof r=="object"&&r!==null&&"name"in r?String(r.name):"Error",n=r instanceof Error?r.message:typeof r=="string"?r:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:i,message:n,timestamp:Date.now()}}var _u="fingerprint";function Lu(r){let e=0;for(let n=0;n<r.length;n++)e=(e<<5)-e+r.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),i=0;for(let n=r.length-1;n>=0;n--)i=(i<<5)-i+r.charCodeAt(n),i|=0;return`fp_${t}${Math.abs(i).toString(16).padStart(8,"0")}`}function Ou(r){let e=r.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Lu(t.join("|"))}var Li=class{constructor(e,t,i){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??_u,this.metadataService=i}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Ou(this.metadataService);return this.storage.set(this.storageKey,t),t}};var Ce=class{constructor(e){this.memoryFallback=new Map;this.storage=typeof window>"u"?null:e}get(e){return this.storage?this.storage.getItem(e):this.memoryFallback.get(e)??null}set(e,t){if(this.storage){this.storage.setItem(e,t);return}this.memoryFallback.set(e,t)}remove(e){if(this.storage){this.storage.removeItem(e);return}this.memoryFallback.delete(e)}clear(){this.storage||this.memoryFallback.clear()}removeKeysMatching(e){if(this.storage){let t=[];for(let i=0;i<this.storage.length;i++){let n=this.storage.key(i);n&&e(n)&&t.push(n)}for(let i of t)this.storage.removeItem(i);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var Y=class{constructor(){this.store=new Map}get(e){return this.store.get(e)??null}set(e,t){this.store.set(e,t)}remove(e){this.store.delete(e)}clear(){this.store.clear()}removeKeysMatching(e){for(let t of this.store.keys())e(t)&&this.store.delete(t)}};function Fu(r){return"removeKeysMatching"in r&&typeof r.removeKeysMatching=="function"}var br=class{constructor(e,t,i){this.adapter=e,this.namespace=t,this.prefix=i}get(e){let t=this.adapter.get(this.createKey(e));if(t===null)return null;try{return JSON.parse(t)}catch{return null}}set(e,t){this.adapter.set(this.createKey(e),JSON.stringify(t))}remove(e){this.adapter.remove(this.createKey(e))}has(e){return this.adapter.get(this.createKey(e))!==null}clear(){let e=this.getNamespaceKeyPrefix();if(Fu(this.adapter)){this.adapter.removeKeysMatching(t=>t.startsWith(e));return}this.adapter.clear()}createKey(e){return this.prefix?`${this.prefix}:${this.namespace}:${e}`:`${this.namespace}:${e}`}getNamespaceKeyPrefix(){return this.prefix?`${this.prefix}:${this.namespace}:`:`${this.namespace}:`}};function wn(r){let e=r??"memory";if(typeof window>"u")return new Y;switch(e){case"memory":return new Y;case"localStorage":return new Ce(window.localStorage);case"sessionStorage":return new Ce(window.sessionStorage);case"cookie_localStorage":return new Ce(window.localStorage);case"cookie":return new Y;case"indexedDB":return new Y;default:return new Y}}function kn(r){switch(r??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function Nu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Oi(){return`ses_${Nu()}`}var Bu="session",Fi=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Bu}getSessionId(){return this.getSessionData()?.sessionId??null}getSessionData(){let e=this.storage.get(this.storageKey);if(!e)return null;if(typeof e=="string"){let t=Date.now();return{sessionId:e,lastActivityAt:t,createdAt:t}}return e}getLastActivityAt(){return this.getSessionData()?.lastActivityAt??null}isExpired(e){let t=this.getSessionData();return t?Date.now()-t.lastActivityAt>e:!0}ensureSession(e){let t=this.getSessionData(),i=Date.now();if(!t){let n=Oi();return this.writeSessionData({sessionId:n,lastActivityAt:i,createdAt:i}),{sessionId:n,expired:!1,created:!0}}if(i-t.lastActivityAt>e){let n=t.sessionId,o=Oi();return this.writeSessionData({sessionId:o,lastActivityAt:i,createdAt:i}),{sessionId:o,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=Oi();return this.writeSessionData({sessionId:t,lastActivityAt:e,createdAt:e}),t}clear(){this.storage.remove(this.storageKey)}writeSessionData(e){this.storage.set(this.storageKey,e)}};function Vu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function vs(){return`vst_${Vu()}`}var Uu="visitor",Ni=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Uu}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=vs();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Rn=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],Mn=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Pn=["[data-no-url-context]","[download]"],bs="[data-no-sid]";function X(r){return r.trim().toLowerCase()}function Sr(r){try{return decodeURIComponent(r)}catch{return r}}function Er(r,e){let t=new Set;if(e!==!1)for(let i of Rn)t.add(X(i));for(let i of r??[])typeof i=="string"&&i.trim()&&t.add(X(i));return t}function _n(r,e){let t=[];e!==!1&&t.push(...Mn);for(let i of r??[])typeof i=="string"&&i.trim()&&t.push(i.trim().toLowerCase());return Array.from(new Set(t.map(i=>i.toLowerCase())))}function Ln(r,e,t){let i=[];e!==!1&&i.push(...Pn),t&&i.push(bs);for(let n of r??[])typeof n=="string"&&n.trim()&&i.push(n.trim());return Array.from(new Set(i))}function Bi(r,e){return e.has(X(r))}function Ss(r,e){let i=r.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return i===n||i.endsWith(`.${n}`)}function On(r,e,t){if(!r)return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local");for(let i of t)if(Ss(r,i))return!1;return e===void 0||e==="*"?!0:e.some(i=>i.trim().toLowerCase()==="local"?!1:Ss(r,i))}function Fn(r="sid"){let e=(r||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),i=Math.random().toString(36).slice(2,10);return`${e}_${t}_${i}`}function A(){return typeof window<"u"&&typeof document<"u"}function Nn(r){if(A())try{History.prototype.replaceState.call(history,history.state,document.title,r)}catch{}}function Z(r){let e={};if(!r||r==="?")return e;let t=r.startsWith("?")?r.slice(1):r;if(!t)return e;for(let i of t.split("&")){if(!i)continue;let n=i.indexOf("="),o=Sr((n>=0?i.slice(0,n):i).replace(/\+/g," ")).trim();if(!o)continue;let s=n>=0?Sr(i.slice(n+1).replace(/\+/g," ")):"";e[o]=s}return e}function Cr(r){let e=[];for(let[t,i]of Object.entries(r))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(i??"")}`);return e.length>0?`?${e.join("&")}`:""}function D(r){return Object.freeze({...r})}function Bn(r,e){let t=r.trim(),i=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${i}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${i}${n}`:t.startsWith("#")?`${i}${n}`:`${t.split(/[?#]/)[0]??t}${i}${n}`}var xr=class{collect(e){if(!e||e.enabled===!1)return{};if(!A())return{};let t=Z(window.location.search),i=Er(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",o=new Set((e.allowlist??[]).map(X).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))Bi(a,i)||n==="allowlist"&&!o.has(X(a))||l!==""&&(s[a]=l);return s}};var Tr=class{constructor(e){this.store=e}resolve(e){let t={},i={},n={},o={},s=A()?Z(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let u=a.mode??"read_write",c=u==="read_only"||u==="read_write",d=u==="write_only"||u==="read_write",m=null,h=null;if(c){let p=s[l];p&&p.length>0&&(m=p,h="url")}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(p);f&&(m=f,h="cookie")}}if(!m&&c&&a.persistence?.enabled!==!1){let p=a.persistence?.storageKey?.trim()||l,f=this.store.getStorage(p);f&&(m=f,h="storage")}!m&&d&&a.generator?.type==="public_id"&&(m=Fn(a.generator.prefix??l),h="generated"),!(!m||!h)&&(t[l]=m,i[l]=h,a.decorateLinks!==!1&&(n[l]=m),a.persistence?.enabled!==!1&&this.persist(a,m),d&&(a.writeStrategy??"replaceState")==="replaceState"&&A()&&s[l]!==m&&(o[l]=m))}return Object.keys(o).length>0&&A()&&this.writeToUrl(o),{values:t,sources:i,decorateParams:n}}applyExternalValue(e,t){let i=t.trim();i&&(e.persistence?.enabled!==!1&&this.persist(e,i),(e.writeStrategy??"replaceState")==="replaceState"&&A()&&this.writeToUrl({[e.param]:i}))}persist(e,t){let i=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,o=e.persistence?.cookie,s=o?.name?.trim()||e.param;(i==="storage"||i==="localStorage_cookie")&&this.store.setStorage(n,t),(i==="cookie"||i==="localStorage_cookie")&&o?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:o?.path??"/",domain:o?.domain??"auto",sameSite:o?.sameSite??"Lax",secure:o?.secure??!0,maxAgeMs:o?.maxAgeMs})}writeToUrl(e){let i={...Z(window.location.search),...e},n=Cr(i),o=window.location.hash??"",s=window.location.pathname+n+o;Nn(s)}};var Ir=class{resolve(e){let{queryParams:t,managedValues:i,config:n}=e;if(!n||n.enabled===!1)return{};let o=Er(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(X).filter(Boolean)),l={};for(let[u,c]of Object.entries(t))c&&(Bi(u,o)||u in i||s==="allowlist"&&!a.has(X(u))||(l[u]=c));return l}};var zu=["mailto:","tel:","javascript:","data:","blob:"],ze=class{constructor(e,t,i){this.clickHandler=null;this.started=!1;if(Hu(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=_n(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=Ln(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let n=e,o=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...n}),this.config=o,this.excludedDomains=_n(o.excludedDomains,o.mergeDefaultExcludedDomains),this.excludeSelectors=Ln(o.excludeSelectors,o.mergeDefaultExcludeSelectors,i===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!A()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!A()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let i=qu(t.target);i&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let i=e.trim(),n=i.toLowerCase();for(let p of zu)if(n.startsWith(p))return p==="mailto:"&&this.config.decorateMailto===!0||p==="tel:"&&this.config.decorateTel===!0,null;if(i.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let o;try{let p=A()?window.location.href:`https://${t??"example.com"}/`;o=new URL(i,p)}catch{return null}if(!On(o.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=Z(o.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,u={...s},c=!1;for(let[p,f]of Object.entries(this.forwardedParams))p in u&&a&&!l||(u[p]!==f&&(c=!0),u[p]=f);for(let[p,f]of Object.entries(this.managedParams))u[p]!==f&&(c=!0),u[p]=f;let d=Z(i.includes("?")?i.slice(i.indexOf("?")).split("#")[0]??"":""),m=$u(i)>Object.keys(d).length;if(!c&&!m)return i;let h=Cr(u);return o.search=h.startsWith("?")?h.slice(1):h,Bn(i,o)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let i of t)i instanceof HTMLAnchorElement&&(this.isExcludedAnchor(i)||this.decorateAnchor(i))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let i=this.decorateHref(t);i!=null&&i!==t&&e.setAttribute("href",i)}};function Hu(r){return typeof r=="object"&&r!==null&&"config"in r&&typeof r.config=="object"&&r.config!==null}function qu(r){return r instanceof Element?r.closest("a[href]"):null}function $u(r){let e=r.indexOf("?");if(e<0)return 0;let t=r.indexOf("#",e),i=t>=0?r.slice(e+1,t):r.slice(e+1);return i?i.split("&").filter(Boolean).length:0}var Ar=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!A())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let i of t){let n=i.indexOf("=");if((n>=0?i.slice(0,n):i).trim()!==e)continue;let s=n>=0?i.slice(n+1).trim():"";return Sr(s)}}catch{return null}return null}setCookie(e){if(!A())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let i=Ku(e.domain);i&&t.push(`domain=${i}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let n=e.sameSite??"Lax";t.push(`SameSite=${n}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Ku(r){if(!r||r==="auto"){if(!A())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return r}var Cs={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},Gu={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Qu={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},ju={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function Vi(r){if(!r||r.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=r.managedParams!==void 0?r.managedParams.map(Es):[Es(Cs)];return{enabled:!0,queryParams:{...Gu,...r.queryParams,...r.queryParams?.allowlist?{allowlist:[...r.queryParams.allowlist]}:{},...r.queryParams?.denylist?{denylist:[...r.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Qu,...r.forwardParams,...r.forwardParams?.allowlist?{allowlist:[...r.forwardParams.allowlist]}:{},...r.forwardParams?.denylist?{denylist:[...r.forwardParams.denylist]}:{}},linkDecoration:{...ju,...r.linkDecoration,...r.linkDecoration?.allowedDomains&&r.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...r.linkDecoration.allowedDomains]}:{},...r.linkDecoration?.excludedDomains?{excludedDomains:[...r.linkDecoration.excludedDomains]}:{},...r.linkDecoration?.excludeSelectors?{excludeSelectors:[...r.linkDecoration.excludeSelectors]}:{}}}}function Es(r){return{...r,...r.generator?{generator:{...r.generator}}:{},...r.persistence?{persistence:{...r.persistence,...r.persistence.cookie?{cookie:{...r.persistence.cookie}}:{}}}:{}}}var He=class{constructor(e,t){this.collector=new xr;this.forwardResolver=new Ir;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Vn();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=Vi(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=Vn();return}this.store=new Ar(this.storage),this.managedResolver=new Tr(this.store);let t=this.collector.collect(e.queryParams),i=this.managedResolver.resolve(e.managedParams),n=Object.keys(i.values).length>0?this.collector.collect(e.queryParams):t,o=this.forwardResolver.resolve({queryParams:n,managedValues:i.values,config:e.forwardParams}),s={...i.sources};for(let c of Object.keys(o))s[c]||(s[c]="url");let a={...Object.keys(i.values).length>0?{managed:D(i.values)}:{},...Object.keys(o).length>0?{forwarded:D(o)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:D(n),urlContext:Object.freeze(a)};let l=D(o);this.decorateManaged={...i.decorateParams};let u=e.managedParams.some(c=>c.param==="sid"&&c.decorateLinks!==!1);this.decorator=new ze({forwardedParams:l,managedParams:D(this.decorateManaged),config:e.linkDecoration,includeSidExclude:u}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let i=e.trim(),n=t.trim();if(!i||!n)return!1;let o=this.managedConfigs.find(d=>d.param===i);if(!o)return!1;if(this.snapshot.urlContext.managed?.[i]===n)return!0;this.managedResolver.applyExternalValue(o,n);let a={...this.snapshot.urlContext.managed??{},[i]:n},l={...this.snapshot.urlContext.source??{},[i]:"manual"},u=Vi(this.rawConfig),c=this.collector.collect(u.queryParams);if(this.snapshot={queryParams:D(c),urlContext:Object.freeze({managed:D(a),...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...l})})},o.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[i]:n},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&u.enabled)){let d=this.managedConfigs.some(m=>m.param==="sid"&&m.decorateLinks!==!1);this.decorator=new ze({forwardedParams:D(this.snapshot.urlContext.forwarded??{}),managedParams:D(this.decorateManaged),config:u.linkDecoration,includeSidExclude:d}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=Vn()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:D(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:D(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:D(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function Vn(){return{queryParams:D({}),urlContext:Object.freeze({})}}var Dr=class{constructor(e){this.initialized=!1;this.customerObserver=null;this.initializedModules=[];this.context=null;this.config=e,this.registry=new lr,this.fallbackLogger=new mr(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init(),this.startCustomerObserver();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let i=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${i.name}`);try{await i.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${i.name}"`,n)}}this.customerObserver?.destroy(),this.customerObserver=null,this.context?.services.customerIdentity?.clear(),this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:i,persistence:n}=this.config.storage,o=this.createStorageService(t,i,n?.visitor),s=this.createStorageService(t,i,n?.session),a=this.createStorageService(t,i,n?.attribution),l=this.createStorageService(t,i,n?.attribution??"localStorage"),u=this.createStorageService(t,i,"memory"),c=new Pi,d=new vr(l,this.config.attribution??pr),m=this.createStorageService(t,i,n?.attribution??"localStorage"),h=new He(this.config.modules.core.urlContext,m),p=new ur,f=new dr(c,d,h,p),b=new Ni(o,this.config),S=new Fi(s,this.config),O=new Li(a,this.config,c),$e=new _i(e),zi=new Pe(this.config.commerce);return{storage:u,visitor:b,session:S,fingerprint:O,dispatcher:$e,browserMetadata:c,eventBuilder:f,attribution:d,commerce:zi,urlContext:h,customerIdentity:p}}startCustomerObserver(){let e=this.context?.services.customerIdentity;e&&(this.customerObserver=new cr(e,new q({fieldMappings:re(this.config.commerce.customer,this.config.commerce.mappings?.fields)})),this.customerObserver.start())}createStorageService(e,t,i){return new br(wn(i),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Ui="0.1.0-rc.13";var qe=class{constructor(e){let t=Xe(e);this.config=t,this.runtime=new Dr(t),this.conversionModule=new It,this.transportModule=new ar,this.integrationsModule=new Yt,this.behaviorModule=new bt,this.snapshotService=new Je({getSdkVersion:()=>Ui,getRuntime:()=>this.runtime,getTransportModule:()=>this.transportModule,getConversionModule:()=>this.conversionModule,getIntegrationsModule:()=>this.integrationsModule,getBehaviorModule:()=>this.behaviorModule,getConfig:()=>this.config,getRegisteredModules:()=>[{name:"privacy",configuredEnabled:t.modules.privacy.enabled===!0},{name:"transport",configuredEnabled:t.transport.enabled===!0},{name:"integrations",configuredEnabled:t.modules.integrations.enabled===!0},{name:"core",configuredEnabled:t.modules.core.enabled===!0},{name:"behavior",configuredEnabled:t.modules.behavior.enabled===!0},{name:"conversion",configuredEnabled:t.modules.conversion.enabled===!0},{name:"diagnostics",configuredEnabled:!0}]}),this.diagnosticsModule=new et(this.snapshotService),this.runtime.register(new Xt),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new Mt),this.runtime.register(this.behaviorModule),this.runtime.register(this.conversionModule),this.runtime.register(this.diagnosticsModule)}init(){return this.snapshotService.markAlive(),this.runtime.init()}destroy(){return this.runtime.destroy().then(()=>{this.snapshotService.markDestroyed()})}isInitialized(){return this.runtime.isInitialized()}getDebugSnapshot(){return this.snapshotService.getSnapshot()}setManagedUrlParam(e,t){let i=this.runtime.getDebugServices();return i?.urlContext?i.urlContext.setManagedParam(e,t):!1}purchase(e){this.conversionModule.purchase(e)}lead(e){this.conversionModule.lead(e)}addToCart(e){this.conversionModule.addToCart(e)}removeFromCart(e){this.conversionModule.removeFromCart(e)}initiateCheckout(e){this.conversionModule.initiateCheckout(e)}addPaymentInfo(e){this.conversionModule.addPaymentInfo(e)}viewContent(e){this.conversionModule.viewContent(e)}search(e){this.conversionModule.search(e)}getDebugDedupeKeys(){return this.conversionModule.getDebugDedupeKeys()}getDebugActiveDetectors(){return this.conversionModule.getDebugActiveDetectors()}getDebugTransportState(){return this.transportModule.getDebugState()}flushTransport(){this.transportModule.manualFlush?.()}simulateTransportOffline(e){this.transportModule.simulateOffline?.(e)}configureTransportTestSender(e){this.transportModule.configureTestSender?.(e)}simulateTransportReload(){return this.transportModule.simulateReload()}simulateTransportRestart(){return this.transportModule.simulateRestart()}forceTransportCircuitOpen(){this.transportModule.forceCircuitOpen()}forceTransportCircuitClose(){this.transportModule.forceCircuitClose()}manualTransportReplay(){return this.transportModule.manualReplay()}replayTransportDeadLetter(){return this.transportModule.replayDeadLetter()}clearTransportDeadLetter(){this.transportModule.clearDeadLetter()}exportTransportQueue(){return this.transportModule.exportQueue()}importTransportQueue(e){return this.transportModule.importQueue(e)}getDebugIntegrationState(){return this.integrationsModule.getDebugState()}getDebugIntegrationMemoryRecords(){return this.integrationsModule.getMemoryRecords()}getDebugAttributionSnapshot(){return this.runtime.getDebugServices()?.attribution.getSnapshot()??null}collectAttribution(){return this.runtime.getDebugServices()?.attribution.collect()??null}clearAttribution(){this.runtime.getDebugServices()?.attribution.clear()}getDebugServices(){return this.runtime.getDebugServices()}evaluateEngagement(){this.behaviorModule.evaluateEngagementNow()}debugPublishBehaviorSignal(e,t){this.behaviorModule.debugPublishSignal(e,t)}flushBehaviorBuffer(){this.behaviorModule.flushBufferNow()}emitBehaviorSessionSummary(e){return this.behaviorModule.emitSessionSummaryNow(e)}};async function xs(r){let e=new qe(r);try{return await e.init(),e}catch(t){try{await e.destroy()}catch{}throw t}}0&&(module.exports={DEFAULT_PIXEL_CONFIG,Pixel,PixelConfigurationError,SDK_VERSION,createPixel,resolvePixelConfig,resolveStorageAdapterName});
|
|
3
3
|
//# sourceMappingURL=index.cjs.js.map
|