@beworke/pixel 0.1.0-rc.1

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.
Files changed (123) hide show
  1. package/CHANGELOG.md +194 -0
  2. package/README.md +163 -0
  3. package/RELEASE_CANDIDATE.md +256 -0
  4. package/dist/PixelLogger-B21lEjep.d.mts +8 -0
  5. package/dist/PixelLogger-B21lEjep.d.ts +8 -0
  6. package/dist/StorageFactory-BhpbB6Jj.d.mts +8 -0
  7. package/dist/StorageFactory-CAkJJqVD.d.ts +8 -0
  8. package/dist/config/index.cjs.js +3 -0
  9. package/dist/config/index.cjs.js.map +1 -0
  10. package/dist/config/index.d.mts +19 -0
  11. package/dist/config/index.d.ts +19 -0
  12. package/dist/config/index.esm.js +3 -0
  13. package/dist/config/index.esm.js.map +1 -0
  14. package/dist/events/index.cjs.js +3 -0
  15. package/dist/events/index.cjs.js.map +1 -0
  16. package/dist/events/index.d.mts +1 -0
  17. package/dist/events/index.d.ts +1 -0
  18. package/dist/events/index.esm.js +3 -0
  19. package/dist/events/index.esm.js.map +1 -0
  20. package/dist/examples/html-script/README.md +71 -0
  21. package/dist/examples/html-script/RELEASE_CANDIDATE.md +121 -0
  22. package/dist/examples/html-script/add-payment-info/README.md +46 -0
  23. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +494 -0
  24. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +478 -0
  25. package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +486 -0
  26. package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +479 -0
  27. package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +492 -0
  28. package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +495 -0
  29. package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +469 -0
  30. package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +489 -0
  31. package/dist/examples/html-script/add-to-cart/README.md +36 -0
  32. package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +517 -0
  33. package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +512 -0
  34. package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +519 -0
  35. package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +514 -0
  36. package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +517 -0
  37. package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +527 -0
  38. package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +524 -0
  39. package/dist/examples/html-script/example-basic.html +350 -0
  40. package/dist/examples/html-script/example-behavior.html +435 -0
  41. package/dist/examples/html-script/example-conversion.html +479 -0
  42. package/dist/examples/html-script/example-integration.html +709 -0
  43. package/dist/examples/html-script/example-transport.html +748 -0
  44. package/dist/examples/html-script/initiate-checkout/README.md +38 -0
  45. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +485 -0
  46. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +491 -0
  47. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +493 -0
  48. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +494 -0
  49. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +497 -0
  50. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +502 -0
  51. package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +496 -0
  52. package/dist/examples/html-script/lead/README.md +25 -0
  53. package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +594 -0
  54. package/dist/examples/html-script/lead/example-lead-trigger-auto.html +431 -0
  55. package/dist/examples/html-script/lead/example-lead-trigger-click.html +587 -0
  56. package/dist/examples/html-script/release-candidate.html +726 -0
  57. package/dist/examples/html-script/remove-from-cart/README.md +36 -0
  58. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +532 -0
  59. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +524 -0
  60. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +540 -0
  61. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +533 -0
  62. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +557 -0
  63. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +539 -0
  64. package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +524 -0
  65. package/dist/examples/html-script/search/README.md +41 -0
  66. package/dist/examples/html-script/search/example-search-attribute.html +454 -0
  67. package/dist/examples/html-script/search/example-search-button-sync.html +455 -0
  68. package/dist/examples/html-script/search/example-search-dedupe.html +466 -0
  69. package/dist/examples/html-script/search/example-search-input.html +456 -0
  70. package/dist/examples/html-script/search/example-search-manual.html +473 -0
  71. package/dist/examples/html-script/search/example-search-submit.html +450 -0
  72. package/dist/examples/html-script/search/example-search-text.html +441 -0
  73. package/dist/examples/html-script/view-content/README.md +48 -0
  74. package/dist/examples/html-script/view-content/example-view-content-attribute.html +488 -0
  75. package/dist/examples/html-script/view-content/example-view-content-css.html +467 -0
  76. package/dist/examples/html-script/view-content/example-view-content-dedupe.html +485 -0
  77. package/dist/examples/html-script/view-content/example-view-content-empty.html +469 -0
  78. package/dist/examples/html-script/view-content/example-view-content-manual.html +496 -0
  79. package/dist/examples/html-script/view-content/example-view-content-product-card.html +478 -0
  80. package/dist/examples/html-script/view-content/example-view-content-text.html +473 -0
  81. package/dist/examples/release-candidate/README.md +14 -0
  82. package/dist/examples/v2/README.md +33 -0
  83. package/dist/index-DUfFzniE.d.mts +274 -0
  84. package/dist/index-DUfFzniE.d.ts +274 -0
  85. package/dist/index.cjs.js +3 -0
  86. package/dist/index.cjs.js.map +1 -0
  87. package/dist/index.d.mts +364 -0
  88. package/dist/index.d.ts +364 -0
  89. package/dist/index.esm.js +3 -0
  90. package/dist/index.esm.js.map +1 -0
  91. package/dist/logger/index.cjs.js +3 -0
  92. package/dist/logger/index.cjs.js.map +1 -0
  93. package/dist/logger/index.d.mts +12 -0
  94. package/dist/logger/index.d.ts +12 -0
  95. package/dist/logger/index.esm.js +3 -0
  96. package/dist/logger/index.esm.js.map +1 -0
  97. package/dist/pixel-CbeF25mD.d.mts +555 -0
  98. package/dist/pixel-CbeF25mD.d.ts +555 -0
  99. package/dist/pixel-default-config-1VgLFOiL.d.mts +5 -0
  100. package/dist/pixel-default-config-Bxb-Vdd8.d.ts +5 -0
  101. package/dist/runtime/index.cjs.js +3 -0
  102. package/dist/runtime/index.cjs.js.map +1 -0
  103. package/dist/runtime/index.d.mts +48 -0
  104. package/dist/runtime/index.d.ts +48 -0
  105. package/dist/runtime/index.esm.js +3 -0
  106. package/dist/runtime/index.esm.js.map +1 -0
  107. package/dist/services/index.cjs.js +3 -0
  108. package/dist/services/index.cjs.js.map +1 -0
  109. package/dist/services/index.d.mts +169 -0
  110. package/dist/services/index.d.ts +169 -0
  111. package/dist/services/index.esm.js +3 -0
  112. package/dist/services/index.esm.js.map +1 -0
  113. package/dist/types-CTpRvFKZ.d.ts +71 -0
  114. package/dist/types-DGlBdsAy.d.mts +71 -0
  115. package/dist/v2/global.global.js +3 -0
  116. package/dist/v2/global.global.js.map +1 -0
  117. package/dist/v2/index.cjs.js +3 -0
  118. package/dist/v2/index.cjs.js.map +1 -0
  119. package/dist/v2/index.d.mts +7 -0
  120. package/dist/v2/index.d.ts +7 -0
  121. package/dist/v2/index.esm.js +3 -0
  122. package/dist/v2/index.esm.js.map +1 -0
  123. package/package.json +101 -0
@@ -0,0 +1,3 @@
1
+ /* Pixel v2 — SDK de analytics e conversão */
2
+ "use strict";var Gt=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var $r=Object.getOwnPropertyNames;var Hr=Object.prototype.hasOwnProperty;var Kr=(n,e)=>{for(var t in e)Gt(n,t,{get:e[t],enumerable:!0})},Qr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $r(e))!Hr.call(n,i)&&i!==t&&Gt(n,i,{get:()=>e[i],enumerable:!(r=zr(e,i))||r.enumerable});return n};var Gr=n=>Qr(Gt({},"__esModule",{value:!0}),n);var bn={};Kr(bn,{DEFAULT_PIXEL_CONFIG:()=>Ur,Pixel:()=>Qt,resolveStorageAdapterName:()=>lr});module.exports=Gr(bn);var C=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,r){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,r),this.managedListeners.push({target:"window",type:e,handler:i,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,r),this.managedListeners.push({target:"document",type:e,handler:i,options:r})}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 Wr=100,W=class extends C{constructor(t){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}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,r=document.body?document.body.scrollHeight:0,i=Math.max(t.scrollHeight,r),o=t.clientHeight;if(i<=o)return 100;let s=i-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)},Wr))}updateScrollState(){if(!this.isWindowAvailable())return;let t=Date.now(),r=window.scrollY||window.pageYOffset,i=this.getMaxScrollPercent();if(i>this.state.maxScrollPercent&&(this.state.maxScrollPercent=i),this.state.scrollEvents+=1,this.state.lastScrollAt=t,this.state.scrollEvents>1&&this.lastScrollTime>0){let o=(t-this.lastScrollTime)/1e3,s=Math.abs(r-this.lastScrollY);if(o>0){let a=s/o;this.velocitySum+=a,this.state.scrollVelocityAvg=this.velocitySum/(this.state.scrollEvents-1)}}this.lastScrollY=r,this.lastScrollTime=t}maybeDispatchOnThresholdCrossing(t){let{thresholds:r}=this.context.config.modules.behavior.trackers.scroll,i=this.state.maxScrollPercent,o=!1;for(let s of r)i>=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.lastDispatchedMaxPercent=this.state.maxScrollPercent,this.lastDispatchAt=Date.now()}};function Wt(n){if(!n)return;let e=n,t=n.classList?.length?Array.from(n.classList):void 0,r,i=e.innerText?.trim()??e.textContent?.trim();i&&(r=i.length>80?`${i.slice(0,80)}\u2026`:i);let o={};if(e.dataset)for(let[s,a]of Object.entries(e.dataset))a!==void 0&&(o[s]=a);return{tagName:n.tagName?.toLowerCase(),id:n.id||void 0,classes:t,text:r,role:e.getAttribute("role")??void 0,name:e.getAttribute("name")??void 0,dataset:Object.keys(o).length>0?o:void 0}}function cr(n){if(!n||!(n instanceof Element))return"unknown";let e=n.tagName.toLowerCase(),t=n.id?`#${n.id}`:"",r=n.className&&typeof n.className=="string"?`.${n.className.trim().split(/\s+/).slice(0,3).join(".")}`:"",i=[];return typeof n.getAttributeNames=="function"&&n.getAttributeNames().filter(o=>o.startsWith("data-")).slice(0,5).sort().forEach(o=>{let s=n.getAttribute(o);s!=null&&i.push(`${o}=${s.slice(0,50)}`)}),[e,t,r,i.join("|")].filter(Boolean).join("")}var Y=class extends C{constructor(t){super(t);this.state={clickCount:0,rageClickCount:0,lastClickAt:0};this.clickHistory=new Map;this.rageCooldownUntil=new Map}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 r=Date.now(),{rageClick:i}=this.context.config.modules.behavior.trackers.click;this.state.clickCount+=1,this.state.lastClickAt=r;let o=t.target instanceof Element?t.target:null,s=t.currentTarget instanceof Element?t.currentTarget:null,a=Wt(o),l=Wt(s);if(this.dispatchEngagement({type:"PAGE_CLICK",category:"ENGAGEMENT",clickCount:this.state.clickCount,rageClickCount:this.state.rageClickCount,lastClickAt:r,target:a,currentTarget:l,clientX:t.clientX,clientY:t.clientY,pageX:t.pageX,pageY:t.pageY,offsetX:t.offsetX,offsetY:t.offsetY}),!o||!i.enabled)return;let c=cr(o),u=this.rageCooldownUntil.get(c)??0;if(r<u)return;let d=(this.clickHistory.get(c)??[]).filter(p=>r-p<i.windowMs);d.push(r),this.clickHistory.set(c,d),d.length>=i.threshold&&(this.state.rageClickCount+=1,this.dispatchEngagement({type:"RAGE_CLICK",category:"ENGAGEMENT",threshold:i.threshold,windowMs:i.windowMs,clickCount:d.length,target:a}),this.clickHistory.delete(c),this.rageCooldownUntil.set(c,r+i.windowMs))}};var j=class extends C{constructor(t){super(t);this.state={isVisible:!0,visibleSince:0,hiddenAt:null}}onInit(){if(!this.isDocumentAvailable())return;let t=Date.now(),r=document.visibilityState==="visible";this.state={isVisible:r,visibleSince:t,hiddenAt:r?null:t},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.emitVisibilityEvent()}emitVisibilityEvent(){this.dispatchEngagement({type:"VISIBILITY_CHANGE",category:"ENGAGEMENT",isVisible:this.state.isVisible,visibleSince:this.state.visibleSince,hiddenAt:this.state.hiddenAt})}};var Yr=["mousemove","scroll","keydown","touchstart"],X=class extends C{constructor(t){super(t);this.isIdle=!1;this.idleSince=0;this.idleTimer=null}onInit(){if(this.isWindowAvailable()){this.isIdle=!1,this.idleSince=0,this.scheduleIdleCheck();for(let t of Yr)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.isIdle){let r=Math.max(0,t-this.idleSince);this.isIdle=!1,this.dispatchEngagement({type:"USER_ACTIVE",category:"ENGAGEMENT",activeAt:t,previousIdleDurationMs:r})}this.scheduleIdleCheck()}enterIdle(){if(this.isIdle)return;let t=Date.now();this.isIdle=!0,this.idleSince=t,this.dispatchEngagement({type:"USER_IDLE",category:"ENGAGEMENT",idleSince:t,thresholdMs:this.thresholdMs})}};var jr=5,J=class extends C{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>jr)return;this.fired=!0;let r=Date.now();this.dispatchEngagement({type:"EXIT_INTENT",category:"ENGAGEMENT",triggeredAt:r,clientY:t.clientY})}};var Z=class{constructor(){this.name="behavior";this.trackers=[];this.active=!1}init(e){if(this.active){e.logger.debug("[Pixel] Behavior module already initialized");return}let{enabled:t,trackers:r}=e.config.modules.behavior;if(!t){e.logger.debug("[Pixel] Behavior module disabled");return}e.logger.debug("[Pixel] Behavior module initialized");let i=[];r.scroll.enabled&&i.push(new W(e)),r.click.enabled&&i.push(new Y(e)),r.visibility.enabled&&i.push(new j(e)),r.idle.enabled&&i.push(new X(e)),r.exitIntent.enabled&&i.push(new J(e));for(let o of i)o.init();this.trackers=i,this.active=!0}destroy(){if(this.active){for(let e=this.trackers.length-1;e>=0;e-=1)this.trackers[e]?.destroy();this.trackers=[],this.active=!1}}};var v=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,r){if(!this.isWindowAvailable())return;let i=t;window.addEventListener(e,i,r),this.managedListeners.push({target:"window",type:e,handler:i,options:r})}addDocumentListener(e,t,r){if(!this.isDocumentAvailable())return;let i=t;document.addEventListener(e,i,r),this.managedListeners.push({target:"document",type:e,handler:i,options:r})}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}};var ee=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 r of e){if(!r||typeof r!="object")continue;let i=typeof r.id=="string"?r.id.trim():"";if(!i||this.productsById.has(i))continue;let o=this.normalizeProduct(r,i,t);this.productsById.set(i,o),this.orderedIds.push(i);let s=typeof o.sku=="string"?o.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,o)}}normalizeProduct(e,t,r){let i=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,o=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,s=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...i!==void 0?{sku:i}:{},...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 te=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 r=this.normalizeQuantity(e.quantity);if(r<=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:r,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 r=this.normalizeQuantity(t);if(r<=0){this.itemsByProductId.delete(e);return}let i=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...i,quantity:r})}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 r=this.normalizeQuantity(e.quantity);r<=0||this.itemsByProductId.has(t)||this.itemsByProductId.set(t,{...e,productId:t,quantity:r,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 Xr=/\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 w(n){return typeof Element<"u"&&n instanceof Element}function x(n){return typeof HTMLFormElement<"u"&&n instanceof HTMLFormElement}function re(n){return typeof HTMLInputElement<"u"&&n instanceof HTMLInputElement}function y(n){if(n==null)return;let e=String(n).trim();return e.length>0?e:void 0}function Yt(n){let e=y(n);if(!e)return;let t=e.replace(/[^\d.,\-]/g,"");if(!t||t==="-"||t==="."||t===",")return;let r=t.includes(","),i=t.includes(".");r&&i?t.lastIndexOf(",")>t.lastIndexOf(".")?t=t.replace(/\./g,"").replace(",","."):t=t.replace(/,/g,""):r&&(t=t.replace(",","."));let o=Number(t);if(Number.isFinite(o))return o}function jt(n){let e=y(n);if(!e)return;let t=Number(e.replace(",","."));if(!(!Number.isFinite(t)||t<=0))return t}function ur(n){if(re(n)&&n.type==="password")return!0;let e=[n.getAttribute("name"),n.getAttribute("id"),n.getAttribute("autocomplete"),n.getAttribute("placeholder"),n.getAttribute("aria-label")].filter(Boolean).join(" ");return Xr.test(e)}function b(n,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),i=y(n.getAttribute(r));if(i)return i}}function A(n){if(!ur(n)&&(re(n)||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement))return y(n.value)}function S(n,e){for(let r of e){if(!r)continue;let i=n.querySelector(`input[name="${rt(r)}"], textarea[name="${rt(r)}"], select[name="${rt(r)}"], input[id="${rt(r)}"]`);if(i){let o=A(i);if(o)return o}}let t=[];(re(n)||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement)&&t.push(n),t.push(...Array.from(n.querySelectorAll("input, textarea, select")));for(let r of e){let i=r.toLowerCase();for(let o of t){if(ur(o))continue;let s=(o.getAttribute("name")??"").toLowerCase(),a=(o.getAttribute("id")??"").toLowerCase();if(!Jr(s,a,i))continue;let l=A(o);if(l)return l}}}function Jr(n,e,t){return n===t||e===t?!0:t.length<4?!1:n.includes(t)||e.includes(t)}function rt(n){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function U(...n){let e={};for(let t of n)if(t)for(let[r,i]of Object.entries(t))i==null||i===""||e[r]===void 0&&(e[r]=i);return e}function ie(n,e){let t=new Set,r=[];for(let i of[...n??[],...e]){let o=i?.trim();!o||t.has(o)||(t.add(o),r.push(o))}return r}var Zr=["email","customerEmail","customer_email","e-mail"],ei=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],ti=["name","nome","fullName","full_name"],ri=["firstName","first_name","primeiro","primeiro_nome","given-name"],ii=["lastName","last_name","sobrenome","family-name"],ni=["data-email"],oi=["data-phone","data-telefone"],si=["data-name","data-nome"],ai=["data-first-name","data-firstname"],li=["data-last-name","data-lastname"],_=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!w(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),i=x(r)?this.extractFromScope(r):{},o=this.findCustomerContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return U(t,i,s)}extractFromForm(e){return x(e)?this.extractFromScope(e):{}}extractFromContainer(e){return w(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.readTypedInput(e,"email")??this.readAutocomplete(e,"email")??b(e,ni)??S(e,this.fieldsFor("email",Zr)),r=this.readTypedInput(e,"tel")??this.readAutocomplete(e,"tel")??b(e,oi)??S(e,this.fieldsFor("phone",ei)),i=this.readAutocomplete(e,"name")??b(e,si)??S(e,this.fieldsFor("name",ti)),o=this.readAutocomplete(e,"given-name")??b(e,ai)??S(e,this.fieldsFor("firstName",ri)),s=this.readAutocomplete(e,"family-name")??b(e,li)??S(e,this.fieldsFor("lastName",ii));return U({email:y(t),phone:y(r),name:y(i),firstName:y(o),lastName:y(s)})}fieldsFor(e,t){return ie(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,i=e.matches(r)?e:e.querySelector(r);return i?A(i):void 0}readAutocomplete(e,t){let r=`input[autocomplete="${t}"]`,i=e.matches(r)?e:e.querySelector(r);return i?A(i):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form")}};var ci=["data-product-id","data-product","data-sku","data-item-id","data-id"],ui=["data-product-name","data-name","data-item-name"],di=["data-product-price","data-price","data-value","data-amount"],pi=["data-quantity","data-qty"],mi=["data-currency"],gi=["productId","product_id","product","sku","item_id","id"],hi=["productName","product_name","item_name","name"],fi=["price","amount","value","product_price"],yi=["quantity","qty"],vi=["currency"],bi=["[data-product-id]","[data-sku]","[data-product]","[data-item-id]","[data-track]",".product-card",".product","[data-product-card]"].join(", "),L=class{constructor(e={}){this.attributeMappings=e.attributeMappings??{},this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!w(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),i=x(r)?this.extractFromScope(r):{},o=this.findProductContainer(e),s=o&&o!==e&&o!==r?this.extractFromScope(o):{};return U(t,i,s)}extractFromForm(e){return x(e)?this.extractFromScope(e):{}}extractFromContainer(e){return w(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=b(e,this.attrsFor("productId",ci))??S(e,this.fieldsFor("productId",gi)),r=b(e,this.attrsFor("productName",ui))??S(e,this.fieldsFor("productName",hi)),i=b(e,this.attrsFor("price",di))??S(e,this.fieldsFor("price",fi)),o=b(e,this.attrsFor("quantity",pi))??S(e,this.fieldsFor("quantity",yi)),s=b(e,this.attrsFor("currency",mi))??S(e,this.fieldsFor("currency",vi));return U({productId:y(t),productName:y(r),price:Yt(i),quantity:jt(o),currency:y(s)})}attrsFor(e,t){return ie(this.attributeMappings[e],t)}fieldsFor(e,t){return ie(this.fieldMappings[e],t)}findProductContainer(e){return e.parentElement?.closest(bi)??null}};var dr="all",pr="auto",Si=["input","change","submit","click","auto"],Ei={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"]}},ne=class{constructor(e){this.hasConfig=e!=null,this.normalized=this.hasConfig?gr(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 r=this.resolveScope(e,t);if(r==="missing_form_selector")return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});if(!r)return this.result({matched:!1,reason:"no_form",fields:[...t.fields],filledFields:[],missingFields:[...t.fields],values:{},config:t});let i={},o=[],s=[];for(let c of t.fields){let u=Di(r,c);u?(i[c]=u,o.push(c)):s.push(c)}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:i,config:t})}matchesRequirement(e,t,r){if(e.minRequired!=null){let i=Math.max(0,e.minRequired);return t>=i}return e.mode==="any"?t>=1:t===r&&r>0}isTriggerCompatible(e,t){return e==="auto"?!0:t==null?!1:t===e}resolveScope(e,t){if(x(e.form))return e.form;let r=w(e.element)?e.element:null;if(r){let i=Ci(r);if(i)return i;let o=r.closest("form");if(x(o))return o}if(t.formSelector){let i=xi(t.formSelector);return i||"missing_form_selector"}return w(e.container)?e.container:r||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 gr(n){if(n==null)return null;if(Array.isArray(n))return{fields:mr(n),mode:dr,trigger:pr};if(typeof n!="object")return null;let e=mr(n.fields??[]),t=n.mode==="any"||n.mode==="all"?n.mode:dr,r=Si.includes(n.trigger)?n.trigger:pr,i={fields:e,mode:t,trigger:r};typeof n.minRequired=="number"&&Number.isFinite(n.minRequired)&&(i.minRequired=n.minRequired);let o=y(n.formSelector);return o&&(i.formSelector=o),typeof n.debounceMs=="number"&&Number.isFinite(n.debounceMs)&&(i.debounceMs=n.debounceMs),typeof n.fireOnce=="boolean"&&(i.fireOnce=n.fireOnce),i}function mr(n){let e=new Set,t=[];for(let r of n){let i=typeof r=="string"?r.trim():"";!i||e.has(i)||(e.add(i),t.push(i))}return t}function Ci(n){if(re(n)||n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement){let e=n.form;return x(e)?e:null}return null}function xi(n){if(typeof document>"u")return null;try{return document.querySelector(n)}catch{return null}}function Di(n,e){let t=e.trim();if(!t)return;let r=Ei[t];if(r?.type){let s=Ti(n,r.type);if(s)return s}if(r?.autocomplete){let s=wi(n,r.autocomplete);if(s)return s}if(r){let s=b(n,r.attrs);if(s)return s;let a=S(n,r.fields);if(a)return a}let i=Ii(t),o=b(n,[`data-${i}`,`data-${t}`]);return o||S(n,[t,i])}function Ti(n,e){let t=`input[type="${e}"]`;try{let r=n.matches(t)?n:n.querySelector(t);return r?A(r):void 0}catch{return}}function wi(n,e){let t=`input[autocomplete="${e}"]`;try{let r=n.matches(t)?n:n.querySelector(t);return r?A(r):void 0}catch{return}}function Ii(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}var oe=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(s=>this.cloneItem(s));for(let s of r)(s.quantity==null||!Number.isFinite(s.quantity))&&(s.quantity=1);let i=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),o=this.resolveCurrency(e,r);return{items:r,...i!==void 0?{value:i}:{},...o!==void 0?{currency:o}:{}}}sumValue(e){let t=0,r=!1;for(let i of e){if(typeof i.price!="number"||!Number.isFinite(i.price))continue;let o=typeof i.quantity=="number"&&Number.isFinite(i.quantity)?i.quantity:1;t+=i.price*o,r=!0}return r?t:void 0}resolveCurrency(e,t){if(typeof e.currency=="string"&&e.currency.trim())return e.currency.trim();for(let r of t)if(typeof r.currency=="string"&&r.currency.trim())return r.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=ki(e.defaultCurrency),this.calculateValueFrom=e.calculateValueFrom??"selected_items"}resolve(e){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);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},i=h(t.productId)??h(r.productId)??this.lookupIdBySku(h(t.sku)??h(r.sku)),o=i?this.catalog.getById(i):this.lookupProductBySku(h(t.sku)??h(r.sku)),s=i??o?.id,a=s?this.state.getItem(s):null,l=h(t.productName)??h(r.productName)??o?.name,c=D(t.price)??D(r.price)??D(a?.price)??o?.price,u=D(t.quantity)??D(r.quantity)??D(a?.quantity)??o?.quantity??1,m=h(t.currency)??h(r.currency)??h(a?.currency)??o?.currency??this.defaultCurrency,d={};s&&(d.productId=s),l&&(d.productName=l),c!==void 0&&(d.price=c),m&&(d.currency=m),u!==void 0&&(d.quantity=u);for(let[p,g]of Object.entries(t))g!==void 0&&(p in d||(d[p]=g));return{data:d}}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},i=h(t.productId)??h(r.productId)??this.lookupIdBySku(h(t.sku)??h(r.sku)),o=i?this.catalog.getById(i):null,s=i??o?.id,a=s?this.state.getItem(s):null,l=D(t.quantity)??D(r.quantity)??D(a?.quantity)??1,c={};s&&(c.productId=s),l!==void 0&&(c.quantity=l);for(let[u,m]of Object.entries(t))m!==void 0&&(u in c||(c[u]=m));return{data:c}}resolveCheckoutLike(e,t){let r={...e.payload??{}},i=D(r.value),o=h(r.currency),s=this.readPayloadItems(e),a=this.resolveItemsSource(s),l=a.map(g=>this.toPixelItem(g)),c=i===void 0&&this.calculateValueFrom!=="manual",u=this.calculator.calculate({items:a,value:c?void 0:i,currency:o,defaultCurrency:this.defaultCurrency}),m=i!==void 0?i:this.calculateValueFrom==="manual"?void 0:u.value,d=o??u.currency??this.defaultCurrency,p={...r};return l.length>0?p.items=l:s===null&&delete p.items,m!==void 0?p.value=m:delete p.value,d&&(p.currency=d),{data:p,items:u.items,...m!==void 0?{value:m}:{},...d?{currency:d}:{}}}readPayloadItems(e){if(e.items)return e.items.map(r=>this.normalizeLooseItem(r));let t=e.payload?.items;return t===void 0||!Array.isArray(t)?null:t.map(r=>this.normalizeLooseItem(r&&typeof r=="object"?r:{}))}resolveItemsSource(e){return e!==null?e.map(t=>this.enrichItem(t)):this.calculateValueFrom==="selected_items"?this.state.getSelectedItems().map(t=>this.enrichItem({productId:t.productId,price:t.price,quantity:t.quantity,currency:t.currency})):[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),i=t??r?.id;return{...e,...i?{productId:i}:{},productName:e.productName??r?.name,sku:e.sku??r?.sku,price:e.price??r?.price,quantity:e.quantity??r?.quantity??1,currency:e.currency??r?.currency??this.defaultCurrency,category:e.category??r?.category,variant:e.variant??r?.variant,brand:e.brand??r?.brand,type:e.type??r?.type,metadata:e.metadata??r?.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:h(e.productId)??h(e.id),sku:h(e.sku),productName:h(e.productName)??h(e.name),price:D(e.price),quantity:D(e.quantity),currency:h(e.currency),category:h(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function h(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function D(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function ki(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Ai(n){return n.trim().replace(/\s+/g," ")}function hr(n,e){let t=Ai(n);return e?t:t.toLowerCase()}function fr(n,e){let t=n.textContent;if(t==null)return!1;let r=e.caseSensitive===!0,i=hr(t,r),o=hr(e.value,r);return o?e.exact===!0?i===o:i.includes(o):!1}function Xt(n,e){if(!fr(n,e))return!1;let t=n.querySelectorAll("*");for(let r=0;r<t.length;r+=1){let i=t[r];if(i&&fr(i,e))return!1}return!0}function vr(n,e){if(typeof document>"u")return[];let t=e??document;if(n.closest)try{let r=[];t instanceof Element&&t.matches(n.closest)&&r.push(t),r.push(...Array.from(t.querySelectorAll(n.closest)));let i=[];for(let o of r)i.push(...yr(o,n));return Array.from(new Set(i))}catch{return[]}return yr(t,n)}function yr(n,e){let t=[],r=Array.from(n.querySelectorAll("*"));n instanceof Element&&r.unshift(n);for(let i of r)Xt(i,e)&&t.push(i);return t}var Pi={css:"css",id:"id",class:"class",attr:"attribute",attribute:"attribute",text:"text"},P=class{constructor(e){this.logger=e??null}hasEntries(e){return this.normalize(e).length>0}normalize(e,t="css"){if(e==null)return[];let r=Array.isArray(e)?e:[e],i=[];for(let o of r){let s=this.normalizeInput(o,t);s&&i.push(s)}return i}queryAll(e,t="css",r){if(typeof document>"u")return[];let i=r??document,o=[];for(let s of this.normalize(e,t))o.push(...this.queryNormalized(s,i));return Array.from(new Set(o))}matches(e,t,r="css"){for(let i of this.normalize(t,r))if(this.matchesNormalized(e,i))return!0;return!1}normalizeInput(e,t){if(typeof e!="string")return this.fromDescriptor(e);let r=e.trim();if(!r)return null;let i=this.parsePrefix(r);return i?this.fromDescriptor({type:i.type,value:i.value}):this.fromDescriptor({type:t,value:r})}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 r=e.slice(0,t).toLowerCase(),i=Pi[r];if(!i)return null;let o=e.slice(t+1).trim();return o?{type:i,value:o}:null}queryNormalized(e,t){if(e.type==="text")return vr({value:e.value,exact:e.exact,caseSensitive:e.caseSensitive,closest:e.closest},t);let r=this.toCssSelector(e);if(!r)return[];try{let i=Array.from(t.querySelectorAll(r));return e.closest?i.filter(o=>{try{return o.closest(e.closest)!=null}catch{return!1}}):i}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,i),[]}}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 Xt(e,{value:t.value,exact:t.exact,caseSensitive:t.caseSensitive});let r=this.toCssSelector(t);if(!r)return!1;try{return e.matches(r)}catch(i){return this.logger?.debug(`[SelectorResolver] Invalid CSS selector ignored: ${r}`,i),!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`#${br(t)}`;case"class":return`.${br(t)}`;case"attribute":return`[data-track="${Ri(t)}"]`;case"css":return t;default:return t}}};function br(n){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function Ri(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var it=class extends v{constructor(t,r,i){super(t);this.debounceTimer=null;this.hasFired=!1;this.destroyed=!1;this.factory=r,this.options=i,this.formEvaluator=new ne(i.selectorForm),this.selectorResolver=new P(t.logger),this.hasSelector=this.selectorResolver.hasEntries(i.selector),this.selectorType=i.selectorType??"css";let o=t.config.modules.conversion.commerce;this.customerExtractor=new _({fieldMappings:o?.mappings?.fields}),this.productExtractor=new L({attributeMappings:o?.mappings?.attributes,fieldMappings:o?.mappings?.fields});let s=this.formEvaluator.getConfig();this.debounceMs=typeof s?.debounceMs=="number"&&s.debounceMs>0?s.debounceMs:0,this.fireOnce=s?.fireOnce===!0}get name(){return`ConfiguredForm(${this.options.eventType})`}onInit(){if(this.destroyed=!1,this.hasFired=!1,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer),!this.isDocumentAvailable())return;let t=this.formEvaluator.getConfig()?.trigger??"auto",r=this.resolveDomEvents(t);for(let i of r)this.addDocumentListener(i,o=>this.handleDomEvent(o,i),!0)}onDestroy(){this.destroyed=!0,this.debounceTimer=this.clearManagedTimeout(this.debounceTimer)}resolveDomEvents(t){return t==="auto"?["input","change","submit","click"]:[t]}handleDomEvent(t,r){if(this.destroyed||this.fireOnce&&this.hasFired)return;let i=r,o=t.target instanceof Element?t.target:null;if(this.hasSelector&&i==="click"&&!this.matchesSelector(o))return;let s=this.formEvaluator.evaluate({element:o,trigger:i});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)}matchesSelector(t){if(!t||!this.options.selector)return!1;let r=t;for(;r&&r!==document.body;){if(this.selectorResolver.matches(r,this.options.selector,this.selectorType))return!0;r=r.parentElement}return!1}resolveCustomerRoot(t){let r=this.formEvaluator.getConfig()?.formSelector;if(r&&typeof document<"u")try{let i=document.querySelector(r);if(i)return i}catch{}return t}buildPayload(t){let{eventType:r}=this.options;if(r==="LEAD"){let i=this.resolveCustomerRoot(t),o=x(i)?this.customerExtractor.extractFromForm(i):this.customerExtractor.extractFromElement(i);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(r==="ADD_TO_CART"){let i=this.productExtractor.extractFromElement(t);return{...i.productId?{productId:i.productId}:{},...i.productName?{productName:i.productName}:{},...i.price!=null?{price:i.price}:{},...i.currency?{currency:i.currency}:{},...i.quantity!=null?{quantity:i.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.options.origin}),this.fireOnce&&(this.hasFired=!0))}};var nt=class extends v{constructor(e,t,r){super(e),this.factory=t,this.config=r,this.selectorType=r.selectorType??"css",this.resolver=new P(e.logger);let i=e.config.modules.conversion.commerce;this.customerExtractor=new _({fieldMappings:i?.mappings?.fields}),this.productExtractor=new L({attributeMappings:i?.mappings?.attributes,fieldMappings:i?.mappings?.fields})}get name(){return`ConfiguredSelector(${this.config.eventType})`}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",e=>this.handleEvent(e),!0),this.addDocumentListener("submit",e=>this.handleEvent(e),!0))}onDestroy(){}handleEvent(e){try{let t=this.findMatchedElement(e);if(!t)return;let r=this.extractData(t);if(r===null)return;this.factory.trackAuto(this.config.eventType,r,{origin:this.config.origin})}catch(t){this.context.logger.debug(`[ConfiguredSelectorDetector] ${this.config.eventType} ignored:`,t)}}findMatchedElement(e){let t=[];e.type==="submit"&&e.target instanceof Element&&t.push(e.target);let r=e.target instanceof Element?e.target:null;for(;r&&r!==document.documentElement;)t.push(r),r=r.parentElement;for(let i of t)if(this.resolver.matches(i,this.config.selector,this.selectorType))return i;return null}extractData(e){let{eventType:t}=this.config;if(t==="LEAD"){let r=this.customerExtractor.extractFromElement(e);return!r.email&&!r.phone&&!r.name?(this.context.logger.debug("[ConfiguredSelectorDetector] LEAD skipped: no email/phone/name"),null):{...r.email?{email:r.email}:{},...r.phone?{phone:r.phone}:{},...r.name?{name:r.name}:{}}}if(t==="ADD_TO_CART"||t==="REMOVE_FROM_CART"){let r=this.productExtractor.extractFromElement(e);return t==="REMOVE_FROM_CART"?{...r.productId?{productId:r.productId}:{},...r.quantity!=null?{quantity:r.quantity}:{}}:{...r.productId?{productId:r.productId}:{},...r.productName?{productName:r.productName}:{},...r.price!=null?{price:r.price}:{},...r.currency?{currency:r.currency}:{},...r.quantity!=null?{quantity:r.quantity}:{}}}if(t==="SEARCH"){let r=e.getAttribute("data-query")??(typeof HTMLInputElement<"u"&&e instanceof HTMLInputElement?e.value:"");return r.trim()?{query:r.trim()}:null}if(t==="INITIATE_CHECKOUT"||t==="PURCHASE")return{};if(t==="VIEW_CONTENT"){let r=this.productExtractor.extractFromElement(e);return{...r.productId?{contentId:r.productId}:{},...r.price!=null?{value:r.price}:{},...r.currency?{currency:r.currency}:{}}}return{}}};var Mi=["card_number","cardNumber","card-number","cc_number"],Fi=["card_number","cardNumber","cc_number"],_i=["cvv","cvc","security_code"],Li=["cvv","cvc","security_code"];function Jt(n){return n.type!=="hidden"&&!n.disabled}function Zt(n){return n.value.length>0}function Sr(n,e){if(typeof document>"u")return!1;for(let t of n){let r=document.getElementById(t);if(r instanceof HTMLInputElement&&Jt(r)&&Zt(r))return!0}for(let t of e){let r=document.querySelectorAll(`input[name="${t}"]`);for(let i of r)if(i instanceof HTMLInputElement&&Jt(i)&&Zt(i))return!0}return!1}function ae(n){if(typeof document>"u")return!1;let e=document.querySelectorAll(`input[autocomplete="${n}"]`);for(let t of e)if(t instanceof HTMLInputElement&&Jt(t)&&Zt(t))return!0;return!1}function Er(){return ae("cc-number")||Sr(Mi,Fi)||ae("cc-exp")||ae("cc-exp-month")||ae("cc-exp-year")||ae("cc-csc")||Sr(_i,Li)}var Oi=["input","change","focusin"],le=class extends v{constructor(t,r){super(t);this.name="CardDetector";this.checkTimer=null;this.tracked=!1;this.factory=r}onInit(){if(this.isDocumentAvailable()){for(let t of Oi)this.addDocumentListener(t,()=>this.scheduleCheck(),!0);this.observeDom(()=>this.scheduleCheck()),this.scheduleCheck()}}onDestroy(){this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.tracked=!1}scheduleCheck(){this.tracked||(this.checkTimer=this.clearManagedTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.evaluate()},300))}evaluate(){this.tracked||!this.isDocumentAvailable()||Er()&&(this.tracked=!0,this.factory.trackAuto("ADD_PAYMENT_INFO",{paymentMethod:"CREDIT_CARD"},{origin:"auto:card"}))}};var Ni=['form[action*="checkout"]',"[data-checkout]",'[name="checkout"]','button[name="checkout"]','a[href*="checkout"]'],ot=class extends v{constructor(t,r){super(t);this.name="CheckoutDetector";this.factory=r}onInit(){this.isDocumentAvailable()&&(this.addDocumentListener("click",t=>this.handleClick(t),!0),this.addDocumentListener("submit",t=>this.handleSubmit(t),!0))}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r)return;let i=r.textContent?.toLowerCase()??"",o=r.href?.toLowerCase()??"";(Ni.some(a=>r.matches(a))||i.includes("checkout")&&!i.includes("continue shopping")||i.includes("finalizar")&&i.includes("compra")||o.includes("/checkout"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}handleSubmit(t){let r=t.target instanceof HTMLFormElement?t.target:null;if(!r)return;((r.getAttribute("action")?.toLowerCase()??"").includes("checkout")||r.matches("[data-checkout]"))&&this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:checkout"})}};var Bi={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 er(n){let e=n.trim().toLowerCase().replace(/\s+/g,"_");return Bi[e]??null}function Cr(n){return n.startsWith("[")||n.startsWith(".")||n.startsWith("#")?n:`[data-track="${n}"]`}var st=class extends v{constructor(t,r,i=[]){super(t);this.name="SelectorDetector";this.factory=r,this.selectors=i.length>0?i:["[data-track]","[data-track-event]"]}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target:null;for(;r&&r!==document.body;){let i=this.matchElement(r);if(i){this.factory.trackAuto(i.type,i.data,{origin:"auto:selector"});return}r=r.parentElement}}matchElement(t){for(let i of this.selectors){let o=Cr(i);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=er(s);if(!a)continue;let l={},c=t.getAttribute("data-track-value");return c&&a==="PURCHASE"&&Object.assign(l,{value:Number(c)||void 0}),{type:a,data:l}}let r=t.getAttribute("data-track");if(r){let i=er(r);if(i)return{type:i,data:{}}}return null}};var qi=[{keyword:"comprar agora",type:"INITIATE_CHECKOUT"},{keyword:"finalizar compra",type:"INITIATE_CHECKOUT"},{keyword:"checkout",type:"INITIATE_CHECKOUT"},{keyword:"comprar",type:"ADD_TO_CART"}],at=class extends v{constructor(t,r,i=[]){super(t);this.name="TextDetector";this.factory=r,this.keywords=i}onInit(){this.isDocumentAvailable()&&this.addDocumentListener("click",t=>this.handleClick(t),!0)}onDestroy(){}handleClick(t){let r=t.target instanceof Element?t.target.closest('a,button,[role="button"],input[type="submit"]'):null;if(!r?.textContent)return;let i=r.textContent.trim().toLowerCase();if(i){for(let o of qi)if(this.keywords.some(s=>s.toLowerCase()===o.keyword)&&i.includes(o.keyword)){this.factory.trackAuto(o.type,{},{origin:"auto:text"});return}for(let o of this.keywords){let s=o.toLowerCase();if(i.includes(s)){this.factory.trackAuto("INITIATE_CHECKOUT",{},{origin:"auto:text"});return}}}}};var I=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()}};I.refCount=0,I.listeners=new Set,I.originalPushState=null,I.originalReplaceState=null,I.installed=!1;var lt=class extends v{constructor(t,r,i=[]){super(t);this.name="UrlDetector";this.unsubscribeHistory=null;this.factory=r,this.patterns=i.map(o=>new RegExp(o,"i"))}onInit(){this.isWindowAvailable()&&(this.checkUrl(),this.addWindowListener("popstate",()=>this.checkUrl()),this.unsubscribeHistory=I.subscribe(()=>this.checkUrl()))}onDestroy(){this.unsubscribeHistory?.(),this.unsubscribeHistory=null}checkUrl(){if(!this.isWindowAvailable())return;let t=window.location.href,r=window.location.pathname;for(let i of this.patterns)if(i.test(t)||i.test(r)){let o=/thank|success|order|obrigado/i.test(i.source);this.factory.trackAuto(o?"PURCHASE":"INITIATE_CHECKOUT",{},{origin:"auto:url"});return}}};var Vi=[{configKey:"purchase",eventType:"PURCHASE",origin:"auto:purchase"},{configKey:"lead",eventType:"LEAD",origin:"auto:lead"},{configKey:"addToCart",eventType:"ADD_TO_CART",origin:"auto:addToCart"},{configKey:"removeFromCart",eventType:"REMOVE_FROM_CART",origin:"auto:removeFromCart"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT",origin:"auto:initiateCheckout"},{configKey:"search",eventType:"SEARCH",origin:"auto:search"},{configKey:"viewContent",eventType:"VIEW_CONTENT",origin:"auto:viewContent"}],Ui=[{configKey:"lead",eventType:"LEAD",origin:"auto:lead"},{configKey:"addToCart",eventType:"ADD_TO_CART",origin:"auto:addToCart"},{configKey:"initiateCheckout",eventType:"INITIATE_CHECKOUT",origin:"auto:initiateCheckout"}],ct=class{static create(e,t){let{auto:r,rules:i}=e.config.modules.conversion,o=[],s=e.logger;if(!r.enabled)return s.debug("[AutoTrackerFactory] Auto detection disabled"),o;o.push(...this.createConfiguredDetectors(e,t,r)),i.enabled&&(i.selectors.length>0&&(o.push(new st(e,t,i.selectors)),s.debug("[AutoTrackerFactory] SelectorDetector registered")),i.texts.length>0&&(o.push(new at(e,t,i.texts)),s.debug("[AutoTrackerFactory] TextDetector registered")),i.urlPatterns.length>0&&(o.push(new lt(e,t,i.urlPatterns)),s.debug("[AutoTrackerFactory] UrlDetector registered")),i.checkout.enabled&&(o.push(new ot(e,t)),s.debug("[AutoTrackerFactory] CheckoutDetector registered")),i.card.enabled&&(o.push(new le(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (rules)")));let a=r.detectors.addPaymentInfo;return a.enabled&&a.cardDetection&&!i.card.enabled&&(o.push(new le(e,t)),s.debug("[AutoTrackerFactory] CardDetector registered (addPaymentInfo)")),s.debug(`[AutoTrackerFactory] Created ${o.length} detector(s)`),o}static createConfiguredDetectors(e,t,r){let i=[],o=new P(e.logger),s=e.logger,a=new Set;for(let l of Ui){let c=r.detectors[l.configKey];if(!c.enabled){s.debug(`[AutoTrackerFactory] Skipped disabled detector: ${l.configKey}`);continue}c.selectorForm&&(i.push(new it(e,t,{eventType:l.eventType,selector:c.selector,selectorType:c.selectorType,selectorForm:c.selectorForm,origin:l.origin})),a.add(l.configKey),s.debug(`[AutoTrackerFactory] ConfiguredFormDetector registered for ${l.eventType}`))}for(let l of Vi){let c=r.detectors[l.configKey];if(c.enabled&&"selector"in c){if(a.has(l.configKey)){s.debug(`[AutoTrackerFactory] Skipped ConfiguredSelectorDetector for ${l.configKey}: selectorForm configured`);continue}if(!o.hasEntries(c.selector)){s.debug(`[AutoTrackerFactory] Skipped ConfiguredSelectorDetector for ${l.configKey}: empty selector`);continue}i.push(new nt(e,t,{eventType:l.eventType,selector:c.selector,selectorType:c.selectorType,origin:l.origin})),s.debug(`[AutoTrackerFactory] ConfiguredSelectorDetector registered for ${l.eventType}`)}}return i}};var ut=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 xr(n,e=Date.now(),t=500){let r=tr(e,t),i=typeof n?.productId=="string"?n.productId.trim():"",o=zi(n?.quantity),s=typeof n?.productName=="string"?n.productName.trim():"";return i?`ADD_TO_CART:product:${i}:qty:${o}:bucket:${r}`:s?`ADD_TO_CART:name:${s}:qty:${o}:bucket:${r}`:`ADD_TO_CART:interaction:${r}`}function tr(n=Date.now(),e=500){let t=e>0?e:500;return Math.floor(n/t)}function zi(n){return typeof n=="number"&&Number.isFinite(n)?n:1}var $i=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 Hi(n=Date.now()){return Math.floor(n/1e3)}function Tr(){return typeof window>"u"?"":window.location.pathname}function rr(n,e,t,r,i=Date.now()){let o=e??{},s=tr(i,500);switch(n){case"PURCHASE":{let a=o;return a.orderId?`PURCHASE:order:${a.orderId}`:t==="auto:url"?`PURCHASE:url:${Tr()}`:$i.has(t)?`PURCHASE:interaction:${s}`:`PURCHASE:manual:${Hi(i)}`}case"LEAD":{let a=o,l=`${a.email??""}:${a.phone??""}`;return l!==":"?`LEAD:identity:${l}`:`LEAD:interaction:${s}`}case"ADD_TO_CART":return xr(o,i,500);case"REMOVE_FROM_CART":{let a=o;return a.productId?`REMOVE_FROM_CART:product:${a.productId}`:`REMOVE_FROM_CART:interaction:${s}`}case"INITIATE_CHECKOUT":return t==="auto:url"?`INITIATE_CHECKOUT:url:${Tr()}`:`INITIATE_CHECKOUT:interaction:${s}`;case"ADD_PAYMENT_INFO":return`ADD_PAYMENT_INFO:session:${r}`;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`${n}:interaction:${s}`}}var f=class{constructor(e){this.factory=e}};var dt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addPaymentInfo")&&this.factory.dispatchManual("ADD_PAYMENT_INFO",e)}};var pt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("addToCart")&&this.factory.dispatchManual("ADD_TO_CART",e)}};var mt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("initiateCheckout")&&this.factory.dispatchManual("INITIATE_CHECKOUT",e)}};var gt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("lead")&&this.factory.dispatchManual("LEAD",e)}};var ht=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("purchase")&&this.factory.dispatchManual("PURCHASE",e)}};var ft=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("removeFromCart")&&this.factory.dispatchManual("REMOVE_FROM_CART",e)}};var yt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("search")&&this.factory.dispatchManual("SEARCH",e)}};var vt=class extends f{constructor(e){super(e)}track(e){this.factory.isManualEnabled("viewContent")&&this.factory.dispatchManual("VIEW_CONTENT",e)}};var Ki=["ADD_TO_CART","REMOVE_FROM_CART","INITIATE_CHECKOUT","PURCHASE"],bt=class{constructor(e,t,r,i){if(this.context=e,this.trackFn=t,this.dedupeSessionId=r,this.commerceState=i?.state??null,i){let o=e.config.modules.conversion.commerce;this.resolver=new se({catalog:i.catalog,state:i.state,calculator:new oe,defaultCurrency:o?.currency,calculateValueFrom:o?.checkout?.calculateValueFrom??"selected_items"})}else this.resolver=null;this.purchase=new ht(this),this.lead=new gt(this),this.addToCart=new pt(this),this.removeFromCart=new ft(this),this.initiateCheckout=new mt(this),this.addPaymentInfo=new dt(this),this.viewContent=new vt(this),this.search=new yt(this)}trackAuto(e,t,r){this.dispatch(e,t,r?.origin??"auto:selector")}dispatchManual(e,t){this.dispatch(e,t,"manual")}normalize(e,t){switch(e){case"SEARCH":{let r=t,i=r?.query??r?.searchTerm??"";if(!i.trim())throw new Error("[Conversion] SEARCH requires query");return{query:i.trim()}}case"PURCHASE":{let r=t;if(r?.value!=null&&r.value<0)throw new Error("[Conversion] PURCHASE value cannot be negative");return r??{}}case"LEAD":{let r=t;if(!r?.email&&!r?.phone&&!r?.name)throw new Error("[Conversion] LEAD requires email, phone or name");return r}default:return t??{}}}buildDedupeKey(e,t,r){return rr(e,t,r,this.dedupeSessionId)}isManualEnabled(e){return this.context.config.modules.conversion.manual[e].enabled}dispatch(e,t,r){let i=this.enrichCommerce(e,t),o=this.normalize(e,i);this.syncCommerceState(e,o);let s=rr(e,o,r,this.dedupeSessionId);this.trackFn(e,o,{dedupeKey:s,origin:r})}enrichCommerce(e,t){return!this.resolver||!Qi(e)?t:this.resolver.resolve({eventType:e,payload:t??{}}).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 r=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:1;this.commerceState.upsertItem({productId:t,quantity:r,...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 Qi(n){return Ki.includes(n)}var St=class{constructor(e){this.deduper=new ut;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.config.modules.conversion.commerce;this.catalog=new ee(t?.catalog?.products,{defaultCurrency:t?.currency}),this.commerceState=new te(t?.checkout?.selectedItems,{allowDynamicItems:t?.checkout?.allowDynamicItems!==!1}),this.factory=new bt(e,(r,i,o)=>{this.dispatch(r,i,o?.dedupeKey)},this.dedupeSessionId,{catalog:this.catalog,state:this.commerceState})}init(){if(!this.active){this.detectors=ct.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.commerceState.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,r){let i=r??this.factory.buildDedupeKey(e,t,"manual");if(this.deduper.has(i)){this.context.logger.debug(`[ConversionEngine] Deduped ${e} (${i})`);return}this.deduper.add(i);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 ce=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 St(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 ue=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 Et=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 Ct=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 de=class{constructor(e){this.navigationObserver=null;this.context=e,this.deduper=new Ct(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 Et(()=>{this.trackPageView()}),this.navigationObserver.start()))}trackPageView(){let t=this.context.services.browserMetadata.getMetadata().path??"",r=Date.now();if(!this.deduper.shouldDispatch(t,r)){this.context.logger.debug("[PageViewEngine] Page view deduplicated");return}let i=this.context.services.eventBuilder.build({type:"PAGE_VIEW"});this.context.logger.debug("[PageViewEngine] Dispatching PAGE_VIEW"),this.context.services.dispatcher.dispatch(i)}destroy(){this.navigationObserver?.destroy(),this.navigationObserver=null,this.deduper.reset()}};var pe=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:r}=this.context.services;if(r.isExpired(e)){this.applySessionLifecycle(e);return}t&&(r.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 r=this.context.services.eventBuilder.build({type:"SESSION_EXPIRED",sessionId:t.previousSessionId});this.context.logger.debug("[SessionEngine] Dispatching SESSION_EXPIRED"),this.context.services.dispatcher.dispatch(r);let i=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(i)}}};var me=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 ge=class{constructor(){this.name="core";this.visitorEngine=null;this.sessionEngine=null;this.fingerprintEngine=null;this.pageViewEngine=null}init(e){e.logger.debug("[Pixel] Core module initialized"),this.visitorEngine=new me(e),this.sessionEngine=new pe(e),this.fingerprintEngine=new ue(e),this.pageViewEngine=new de(e),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.pageViewEngine=null,this.fingerprintEngine=null,this.sessionEngine=null,this.visitorEngine=null}};var he=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 Gi(){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 fe=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=Gi(),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,r=this.getDestinationCounters(t);if(this.lastExecutionAt=e.timestamp,this.totalDuration+=e.duration,e.status==="success"?(this.eventsSent+=1,r.sent+=1):e.status==="failed"?(this.eventsFailed+=1,r.failed+=1,this.lastErrorAt=e.timestamp,this.lastErrorMessage=e.error??"Unknown error",r.lastError=this.lastErrorMessage):e.status==="ignored"?(this.eventsIgnored+=1,r.ignored+=1):e.status==="skipped"&&(this.eventsSkipped+=1,r.skipped+=1),r.totalDuration+=e.duration,e.metadata){let i=Number(e.metadata.sent??0),o=Number(e.metadata.deduped??0),s=Number(e.metadata.failed??0);i>0&&(this.pageViewSent+=i,r.pageViewSent+=i),o>0&&(this.pageViewDeduped+=o,r.pageViewDeduped+=o),s>0&&(this.pageViewFailed+=s,r.pageViewFailed+=s);let a=e.metadata.pixelIds,l=e.metadata.tagIds,c=a??l;if(c&&i>0)for(let u of c.slice(0,i))this.recordDestinationId(t,u,"sent",i/c.length)}e.status==="failed"&&e.error&&(this.pageViewFailed+=1,r.pageViewFailed+=1)}recordDestinationId(e,t,r,i){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)),r==="sent"?(s.sent+=i,s.pageViewSent+=i):(s.failed+=i,s.pageViewFailed+=i)}getSnapshot(){let e=this.eventsSent+this.eventsFailed,t={};for(let[r,i]of this.perDestination){let o=i.sent+i.failed;t[r]={sent:i.sent,failed:i.failed,ignored:i.ignored,skipped:i.skipped,averageDuration:o>0?i.totalDuration/o:0,successRate:o>0?i.sent/o:0,pageViewSent:i.pageViewSent,pageViewDeduped:i.pageViewDeduped,pageViewFailed:i.pageViewFailed,scriptLoadAttempts:i.scriptLoadAttempts,scriptLoadSuccess:i.scriptLoadSuccess,scriptLoadFailure:i.scriptLoadFailure,initAttempts:i.initAttempts,initSuccess:i.initSuccess,initFailure:i.initFailure,lastError:i.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 ye=class n{constructor(e,t="Integration"){this.logger=e,this.scope=t}forAdapter(e){return new n(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 ve=class{constructor(e,t){this.logger=e,this.continueOnError=t}toFailedResult(e,t,r){let i=t instanceof Error?t.message:String(t);return this.logger.forAdapter(e.name).error(`Execution failed: ${i}`),{status:"failed",adapter:e.name,duration:r,timestamp:Date.now(),error:i}}shouldContinue(){return this.continueOnError}};var be=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 r=Date.now(),i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs),s={event:t,signal:i.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()-r,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()-r);return await this.hooks.onFailure?.(e,t,l),await this.hooks.afterExecute?.(e,t,l),l}finally{clearTimeout(o)}}};var Se=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 r=[];for(let i=0;i<t.length;i+=this.concurrency){let o=t.slice(i,i+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],c=o[a];if(l.status==="fulfilled")r.push(l.value),this.metrics.record(l.value);else{let u={status:"failed",adapter:c.name,duration:0,timestamp:Date.now(),error:l.reason instanceof Error?l.reason.message:String(l.reason)};r.push(u),this.metrics.record(u),this.logger.error(`Unhandled destination error: ${c.name}`,l.reason)}}}return this.lastResults=r,r}getLastResults(){return this.lastResults}clearLastResults(){this.lastResults=[]}};var Ee=class n{constructor(e=[]){this.lastSteps=[];this.stages=e}static identity(){return new n([{name:"identity",process(e){return e}}])}process(e){let t=[],r=e;for(let i of this.stages){if(t.push(i.name),!r)break;r=i.process(r)}return this.lastSteps=t,r}getLastSteps(){return this.lastSteps}};var Ce=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 R=new Set(["PAGE_VIEW","PAGE_CLICK","SEARCH","LEAD","INITIATE_CHECKOUT","PURCHASE","ADD_PAYMENT_INFO","ADD_TO_CART","REMOVE_FROM_CART","VIEW_CONTENT"]),E=class{constructor(e){this.name=e.name,this.version=e.version??"1.0.0",this.supportedTypes=e.supportedTypes??R}supports(e){return this.supportedTypes.has(e.type)}createResult(e,t,r){return{status:e,adapter:this.name,duration:t,timestamp:Date.now(),...r}}};var xe=class extends E{constructor(t={}){super({name:"console",version:"1.0.0",supportedTypes:R});this.sent=0;this.log=t.log??((r,i)=>{console.log(r,i)})}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let i={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}`,i),this.sent+=1,this.createResult("success",Date.now()-r,{metadata:{sent:this.sent}})}getSentCount(){return this.sent}};var De=class extends E{constructor(){super({name:"memory",version:"1.0.0",supportedTypes:R});this.records=[]}async execute(t){let r=Date.now();if(t.signal.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});let i=this.transform(t.event);return this.records.push({at:Date.now(),type:t.event.type,payload:i}),this.createResult("success",Date.now()-r,{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 Te=class extends E{constructor(t={}){super({name:"mock",version:"1.0.0",supportedTypes:t.supportedTypes??R});this.executions=0;this.failOnTypes=t.failOnTypes??new Set,this.ignoreTypes=t.ignoreTypes??new Set,this.delayMs=t.delayMs??0}async execute(t){let r=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()-r,{error:"Aborted"});if(this.ignoreTypes.has(t.event.type))return this.createResult("ignored",Date.now()-r,{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()-r,{metadata:{executions:this.executions}})}getExecutionCount(){return this.executions}wait(t,r){return new Promise((i,o)=>{let s=setTimeout(()=>{l(),i()},t),a=()=>{l(),o(new DOMException("The operation was aborted.","AbortError"))},l=()=>{clearTimeout(s),r.removeEventListener("abort",a)};if(r.aborted){l(),o(new DOMException("The operation was aborted.","AbortError"));return}r.addEventListener("abort",a)})}};var wr=new Set;function M(n,e,t,r,i){return`${n}:${e}:${t}:${r}:${i}`}function F(n){return wr.has(n)?!0:(wr.add(n),!1)}var z=new Map;function N(n){if(typeof document>"u"||typeof window>"u")return Promise.reject(new Error("[ScriptLoader] Browser APIs unavailable"));let e=z.get(n.src);if(e)return e.refCount+=1,e.promise;let t=n.timeoutMs??1e4,r=new Promise((i,o)=>{let s=document.createElement("script");if(s.async=!0,s.src=n.src,n.id&&(s.id=n.id),n.attributes)for(let[c,u]of Object.entries(n.attributes))s.setAttribute(c,u);let a=setTimeout(()=>{l(),o(new Error(`[ScriptLoader] Timeout loading ${n.src}`))},t),l=()=>{clearTimeout(a),s.onload=null,s.onerror=null};s.onload=()=>{l();let c=z.get(n.src);c&&(c.loaded=!0),i()},s.onerror=()=>{l(),z.delete(n.src),o(new Error(`[ScriptLoader] Failed to load ${n.src}`))},document.head.appendChild(s)});return z.set(n.src,{promise:r,refCount:1,loaded:!1}),r}function B(n){let e=z.get(n);e&&(e.refCount=Math.max(0,e.refCount-1),e.refCount===0&&!e.loaded&&z.delete(n))}var xt="https://connect.facebook.net/en_US/fbevents.js";function Wi(){return typeof window<"u"?window:null}function Yi(){let n=Wi();if(!n)throw new Error("[MetaScriptLoader] window unavailable");if(n.fbq)return n.fbq;let e=function(...t){let r=e;r.callMethod?r.callMethod(...t):(r.queue=r.queue||[]).push(t)};return e.push=e,e.loaded=!1,e.version="2.0",e.queue=[],n.fbq=e,n._fbq||(n._fbq=e),e}var we=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=Yi();return this.loaded&&t.loaded||(await N({src:xt,id:"pixel-v2-meta-fbevents",timeoutMs:e}),t.loaded=!0,this.loaded=!0),t}release(){B(xt)}};var Ie=class extends E{constructor(t){super({name:"meta",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new we;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 r=this.fbq;if(!r)throw this.metrics?.recordInitFailure("meta"),new Error("[MetaBrowser] fbq unavailable");let i=!1;for(let o of this.pixelIds)try{r("init",o)}catch(s){i=!0,this.metrics?.recordInitFailure("meta"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("meta"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(d){return this.createResult("failed",Date.now()-r,{error:d instanceof Error?d.message:String(d)})}let a=this.fbq??(typeof window<"u"?window.fbq??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"fbq unavailable"});let l=i.path??i.url??"/",c=this.getSessionId(),u=0,m=0;for(let d of this.pixelIds){let p=M("meta",d,"PAGE_VIEW",l,c);if(F(p)){m+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${d}`);continue}try{if(typeof a=="function")try{a("trackSingle",d,"PageView")}catch{a("track","PageView")}u+=1,this.debug&&this.logger.debug(`pageview_sent id=${d}`)}catch(g){this.logger.error(`destination_execute_failure id=${d}`,g)}}return u===0&&m>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:u,deduped:m}}):this.createResult("success",Date.now()-r,{metadata:{sent:u,deduped:m,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.fbq=null}};var ir="https://www.googletagmanager.com/gtag/js";function ji(){return typeof window<"u"?window:null}function Xi(){let n=ji();if(!n)throw new Error("[GoogleScriptLoader] window unavailable");return n.dataLayer=n.dataLayer||[],n.gtag||(n.gtag=function(...t){n.dataLayer?.push(t)}),n.gtag}var ke=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 r=Xi(),i=`${ir}?id=${encodeURIComponent(e)}`;return await N({src:i,id:"pixel-v2-google-gtag",timeoutMs:t}),this.loadedSrc=i,r("js",new Date),r}release(){this.loadedSrc&&(B(this.loadedSrc),this.loadedSrc=null)}};var Ae=class extends E{constructor(t){super({name:"google",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new ke;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 r=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(r,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 i=this.gtag;if(!i)throw this.metrics?.recordInitFailure("google"),new Error("[GoogleBrowser] gtag unavailable");let o=!1;for(let s of this.tagIds)try{i("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 r=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(g){return this.createResult("failed",Date.now()-r,{error:g instanceof Error?g.message:String(g)})}let a=this.gtag??(typeof window<"u"?window.gtag??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"gtag unavailable"});let l=i.path??"/",c=i.url??(typeof window<"u"?window.location?.href:void 0)??l,u=typeof document<"u"?document.title:void 0,m=this.getSessionId(),d=0,p=0;for(let g of this.tagIds){let T=M("google",g,"PAGE_VIEW",l,m);if(F(T)){p+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${g}`);continue}try{a("event","page_view",{send_to:g,page_location:c,page_path:l,page_title:u}),d+=1,this.debug&&this.logger.debug(`pageview_sent id=${g}`)}catch(G){this.logger.error(`destination_execute_failure id=${g}`,G)}}return d===0&&p>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:d,deduped:p}}):this.createResult("success",Date.now()-r,{metadata:{sent:d,deduped:p,tagIds:this.tagIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.gtag=null}};var Dt="https://analytics.tiktok.com/i18n/pixel/events.js";function Ir(){return typeof window<"u"?window:null}function Ji(){let n=Ir();if(!n)throw new Error("[TikTokScriptLoader] window unavailable");if(n.ttq)return n.ttq;let e={load(){},page(){},track(){}};return n.TiktokAnalyticsObject="ttq",n.ttq=e,e}var Pe=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=Ji();return this.loaded?t:(await N({src:Dt,id:"pixel-v2-tiktok-analytics",timeoutMs:e}),this.loaded=!0,Ir()?.ttq??t)}release(){B(Dt)}};var Re=class extends E{constructor(t){super({name:"tiktok",version:"1.0.0",supportedTypes:new Set(["PAGE_VIEW"])});this.scriptLoader=new Pe;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 r=this.ttq;if(!r)throw this.metrics?.recordInitFailure("tiktok"),new Error("[TikTokBrowser] ttq unavailable");let i=!1;for(let o of this.pixelIds)try{r.load(o)}catch(s){i=!0,this.metrics?.recordInitFailure("tiktok"),this.logger.error(`destination_init_failure id=${o}`,s)}this.initialized=!0,i||this.metrics?.recordInitSuccess("tiktok"),this.debug&&this.logger.debug("destination_init_success")}async execute(t){let r=Date.now(),{event:i,signal:o,timeoutMs:s}=t;if(i.type!=="PAGE_VIEW")return this.createResult("ignored",Date.now()-r,{ignored:!0});if(o.aborted)return this.createResult("failed",Date.now()-r,{error:"Aborted"});this.debug&&this.logger.debug("pageview_received");try{await this.ensureInit(s)}catch(p){return this.createResult("failed",Date.now()-r,{error:p instanceof Error?p.message:String(p)})}let a=this.ttq??(typeof window<"u"?window.ttq??null:null);if(!a)return this.createResult("failed",Date.now()-r,{error:"ttq unavailable"});let l=i.path??i.url??"/",c=this.getSessionId(),u=0,m=0;if(typeof a.instance=="function")for(let p of this.pixelIds){let g=M("tiktok",p,"PAGE_VIEW",l,c);if(F(g)){m+=1,this.debug&&this.logger.debug(`pageview_skipped_dedupe id=${p}`);continue}try{a.instance(p).page(),u+=1,this.debug&&this.logger.debug(`pageview_sent id=${p}`)}catch(T){this.logger.error(`destination_execute_failure id=${p}`,T)}}else{let p=this.pixelIds[0]??"global",g=M("tiktok",p,"PAGE_VIEW",l,c);if(F(g))m=1,this.debug&&this.logger.debug("pageview_skipped_dedupe global");else try{a.page(),u=1,this.debug&&this.logger.debug("pageview_sent global")}catch(T){this.logger.error("destination_execute_failure global",T)}}return u===0&&m>0?this.createResult("skipped",Date.now()-r,{skipped:!0,metadata:{sent:u,deduped:m}}):this.createResult("success",Date.now()-r,{metadata:{sent:u,deduped:m,pixelIds:this.pixelIds}})}destroy(){this.scriptLoader.release(),this.initialized=!1,this.ttq=null}};var Me=class{constructor(e,t,r,i=[]){this.memoryDestination=null;this.active=!1;this.registry=new he,this.metrics=new fe,this.logger=new ye(e),this.pipeline=Ee.identity(),this.debug=t.moduleConfig.debug;let o=new ve(this.logger,t.moduleConfig.continueOnError),s=new be({logger:this.logger,errorHandler:o,hooks:r,timeoutMs:t.moduleConfig.timeoutMs,debug:t.moduleConfig.debug});this.dispatcher=new Se({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 xe({log:l?(c,u)=>this.logger.debug(c,u):()=>{}})),a.memory.enabled&&(this.memoryDestination=new De,this.registry.register(this.memoryDestination)),a.mock.enabled&&this.registry.register(new Te),a.meta.enabled&&a.meta.pixelIds.length>0&&this.registry.register(new Ie({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 Ae({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 Re({config:a.tiktok,getSessionId:t.getSessionId,logger:this.logger,metrics:this.metrics,debug:l}));for(let c of i)this.registry.register(c);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 Fe=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 Me(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 Ce(e.services.dispatcher,r=>this.engine?.handleEvent(r)),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 _e=class{constructor(){this.name="privacy"}init(e){e.logger.debug("[Pixel] Privacy module initialized")}destroy(){}};var Tt=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 wt=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,r=this.buffer.splice(0,t);return this.buffer.length===0&&(this.oldestAt=null),r}peek(){return[...this.buffer]}size(){return this.buffer.length}clear(){this.buffer=[],this.oldestAt=null}shouldFlush(e){return this.buffer.length===0?!1: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 $=class{constructor(){this.name="identity"}compress(e){return{encoding:"identity",body:e,originalSize:e.length,compressedSize:e.length}}};function nr(n){return!n.enabled||n.strategy==="identity"?new $:new $}function kr(n,e,t){return{enabled:n.enabled,strategy:e.name,lastOriginalSize:t?.originalSize??null,lastCompressedSize:t?.compressedSize??null}}var Le=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 Oe=class{constructor(e){this.entries=[];this.config=e}move(e,t,r=0,i){if(!this.config.enabled||e.length===0)return null;let o={id:crypto.randomUUID(),events:[...e],reason:t,failedAt:Date.now(),attempts:r,lastError:i};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(i=>i.id===e);if(t<0)return null;let[r]=this.entries.splice(t,1);return r?.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 It=class{constructor(e){this.active=!1;this.inFlight=!1;this.ackCount=0;this.abortPending=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.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())}flush(){!this.active||!this.offlineDetector.isOnline()||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.batchSize);if(e.length!==0){this.inFlight=!0;try{await this.retryEngine.retry(async()=>{let t=await this.sender.send(e);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()}}}};var kt=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 At=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 r=()=>{this.simulatedOffline||(this.online=!0,this.paused=!1,this.onOnline?.())},i=()=>{this.simulatedOffline||(this.online=!1,this.paused=!0,this.onOffline?.())};window.addEventListener("online",r),window.addEventListener("offline",i),this.listeners.push({type:"online",handler:r},{type:"offline",handler:i})}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 Ne=class{constructor(e){this.globalSequence=0;this.sessionSequence=0;this.lastCorrelationId=null;this.enabled=e.enabled}assign(e,t,r){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:r,enqueuedAt:Date.now()}}sort(e){return this.enabled?[...e].sort((t,r)=>t.sequence!==r.sequence?t.sequence-r.sequence:t.enqueuedAt-r.enqueuedAt):[...e]}restoreFromRecords(e){if(!this.enabled||e.length===0)return;let t=e.reduce((o,s)=>Math.max(o,s.sequence),0),r=e.reduce((o,s)=>Math.max(o,s.sessionSequence),0);this.globalSequence=Math.max(this.globalSequence,t),this.sessionSequence=Math.max(this.sessionSequence,r);let i=[...e].reverse().find(o=>o.correlationId);i?.correlationId&&(this.lastCorrelationId=i.correlationId)}resetSessionSequence(){this.sessionSequence=0}getDebugState(e=0){return{enabled:this.enabled,globalSequence:this.globalSequence,sessionSequence:this.sessionSequence,lastCorrelationId:this.lastCorrelationId,recordCount:e}}};var Pt=class{constructor(e){this.name="enqueue";this.queue=e}process(e){return this.queue.enqueue(e),e}};var Rt=class{constructor(){this.name="normalize"}process(e){return{...e,timestamp:e.timestamp??Date.now()}}};var Mt=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 Ft=class n{constructor(e){this.lastSteps=[];this.stages=e}static createDefault(e){return new n([new Mt,new Rt,new Pt(e)])}process(e){let t=[],r=e;for(let i of this.stages){if(t.push(i.name),!r)break;r=i.process(r)}return this.lastSteps=t,{event:r,steps:t}}getLastSteps(){return this.lastSteps}};var _t=class{constructor(e,t,r){this.records=[];this.loaded=!1;this.persistTimer=null;this.storage=e,this.ordering=t,this.backpressure=r}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 r=this.ordering.assign(e),i=this.backpressure.applyPolicy(this.records,r);this.records=i.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(i=>!e(i.event));let r=t-this.records.length;return r>0&&this.schedulePersist(),r}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 Lt=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,r=this.items.filter(i=>!e(i));return this.items.length=0,this.items.push(...r),t-r.length}isEmpty(){return this.items.length===0}getAll(){return[...this.items]}};var q=class{constructor(){this.records=[]}init(){}destroy(){this.records=[]}load(){return[...this.records]}save(e){this.records=[...e]}getAdapterName(){return"MemoryQueueStorage"}isAvailable(){return!0}};var Be=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 H="queue_records",qe=class{constructor(e){this.db=null;this.dbName=e}async init(){typeof indexedDB>"u"||(this.db=await new Promise((e,t)=>{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let i=r.result;i.objectStoreNames.contains(H)||i.createObjectStore(H,{keyPath:"id"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.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(H,"readonly").objectStore(H).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,r)=>{let i=this.db.transaction(H,"readwrite"),o=i.objectStore(H),s=o.clear();s.onsuccess=()=>{for(let a of e)o.put(a)},i.oncomplete=()=>t(),i.onerror=()=>r(i.error??new Error("IndexedDB save failed"))})}getAdapterName(){return"IndexedDBQueueStorage"}isAvailable(){return typeof indexedDB<"u"}};function Zi(n){let e=n.prefix??"__gmk",t=n.namespace||"pixel",r=n.pixelId||"default";return`${e}:${t}:${r}:transport-queue`}function en(n){let e=n.namespace||"pixel",t=n.pixelId||"default";return`${e}_${t}_transport_queue`}function tn(n,e){let t=Zi(e);switch(n){case"localStorage":return new Be(t);case"indexedDB":return new qe(en(e));case"memory":default:return new q}}function rn(n){let e=["indexedDB","localStorage","memory"];if(!n||n==="memory")return e;let t=e.filter(r=>r!==n);return[n,...t]}function Ar(n){if(typeof window>"u")return new q;let e=rn(n.preferred);for(let t of e){let r=tn(t,n);if(r.isAvailable())return r}return new q}function or(n){return Ar({preferred:n.storage.queue?.persistence,namespace:n.storage.namespace,prefix:n.storage.prefix,pixelId:n.identity.pixelId})}var Ve=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 Ue=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,r=Math.random()<t;return r||(this.totalSampled+=1),{accepted:r,dropped:r?0:1,policy:this.config.policy,reason:r?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 r=this.evaluateEnqueue(e.length);return r.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:r.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 ze=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 $e=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 r=await this.inner.send(e,t);return r.ack?this.circuitBreaker.recordSuccess():this.circuitBreaker.recordFailure(),r}catch(r){throw this.circuitBreaker.recordFailure(),r}}getCircuitBreaker(){return this.circuitBreaker}};function Pr(n,e){let t=e.baseDelayMs*e.multiplier**(n-1);return Math.min(t,e.maxDelayMs)}var Ot=class{constructor(e,t){this.entries=new Map;this.idCounter=0;this.config=e,this.logger=t}async retry(e,t){let r=t??`retry-${++this.idCounter}`;return new Promise((i,o)=>{let s=!1,a={id:r,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(r),i()}};this.entries.set(r,a);let l=async()=>{if(!s){a.attempt+=1,a.status="running",a.nextRetryAt=null;try{await e(),a.status="completed",this.entries.delete(r),i()}catch(c){if(s)return;if(a.attempt>=this.config.maxAttempts){a.status="failed",this.entries.delete(r),o(c);return}let u=Pr(a.attempt,this.config);a.status="scheduled",a.nextRetryAt=Date.now()+u,this.logger.debug(`[RetryEngine] Attempt ${a.attempt} failed, retry in ${u}ms`),a.timer=setTimeout(()=>{a.timer=null,l()},u)}}};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 Rr(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`evt_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function nn(n){if("category"in n&&n.category){if(n.category==="ENGAGEMENT")return"ENGAGEMENT";if(n.category==="CONVERSION")return"CONVERSION"}return"OTHER"}function on(n){if("data"in n&&n.data&&typeof n.data=="object")return n.data;let{type:e,timestamp:t,category:r,path:i,url:o,hostname:s,language:a,timezone:l,identifiers:c,...u}=n;if(Object.keys(u).length!==0)return u}function sn(n){let e={fbp:n?.fbp??"",fbc:n?.fbc??"",ga:n?.ga??"",gcl_au:n?.gclAu??""};return n?{...e,fbclid:n.fbclid??"",gclid:n.gclid??"",gbraid:n.gbraid??"",wbraid:n.wbraid??"",gid:n.gid??"",ttclid:n.ttclid??"",ttp:n.ttp??"",msclkid:n.msclkid??"",li_fat_id:n.liFatId??"",epik:n.epik??"",customClickIds:n.customClickIds??{},landingUrl:n.landingUrl??"",referrer:n.referrer??"",firstCollectedAt:n.firstCollectedAt??0,lastCollectedAt:n.lastCollectedAt??0}:e}var Nt=class{constructor(e){this.context=e}buildApiEvent(e,t){let r=this.context.config,i=this.context.services,o=i.browserMetadata.getMetadata(),s=i.visitor.getVisitorId()??i.visitor.ensureVisitorId(),a=i.session.getSessionId()??`session_${r.identity.pixelId||"anonymous"}_${Date.now()}`,l=i.fingerprint.getFingerprint()??i.fingerprint.ensureFingerprint(),c="identifiers"in e&&e.identifiers?e.identifiers:i.attribution?.getSnapshot();return{id:t??Rr(),session_id:a,visitor_id:s,pixel_code:r.identity.pixelId,type:e.type,category:nn(e),timestamp:String(e.timestamp??Date.now()),fingerprint:l,identifiers:sn(c),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}},data:on(e),meta:{version:"2.0.0",pixel_source:"pixel-v2",environment:r.app.environment,script_url:typeof document<"u"&&document.currentScript?String(document.currentScript.src??""):"",projectId:"",pageId:""}}}buildBatchPayload(e){let t=this.buildApiEvent(e[0]??{}),r=e.map(i=>this.buildApiEvent(i));return{pixel_code:this.context.config.identity.pixelId,visitor_id:t.visitor_id,session_id:t.session_id,batch_id:Rr(),sent_at:Date.now(),meta:t.meta,events:r}}};async function Mr(n,e={}){let{timeoutMs:t=1e4,signal:r,...i}=e,o=new AbortController,s=setTimeout(()=>o.abort(),t);r&&(r.aborted?o.abort():r.addEventListener("abort",()=>o.abort(),{once:!0}));try{return await fetch(n,{...i,signal:o.signal})}finally{clearTimeout(s)}}var an="/pixels/public/event",ln="/pixels/public/event/batch",K=class{constructor(e,t,r,i){this.sentCount=0;this.lastAck=null;this.responseLogs=[];this.lastCompression=null;this.config=e,this.payloadBuilder=t,this.compression=r,this.logger=i}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 r=e.length>1,i=`${this.config.apiEndpoint.replace(/\/$/,"")}${r?ln:an}`,o=JSON.stringify(r?this.payloadBuilder.buildBatchPayload(e):this.payloadBuilder.buildApiEvent(e[0])),s=this.compression.compress(o);this.lastCompression={originalSize:s.originalSize,compressedSize:s.compressedSize};try{let a=await Mr(i,{method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":s.encoding},body:s.body,keepalive:!0,timeoutMs:this.config.timeoutMs,signal:t?.signal}),l=await a.json().catch(()=>({})),c=a.ok;if(this.lastAck=c,c&&(this.sentCount+=e.length),this.responseLogs.push({at:Date.now(),url:i,status:a.status,ack:c,eventCount:e.length,body:l}),!c)throw new Error(`[HttpSender] HTTP ${a.status}`);return this.logger.debug(`[HttpSender] Sent ${e.length} event(s) \u2014 ACK`),{ack:!0,eventCount:e.length}}catch(a){let l=a instanceof Error?a.message:String(a);throw this.lastAck=!1,this.responseLogs.push({at:Date.now(),url:i,status:0,ack:!1,eventCount:e.length,error:l}),a}}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:"http"}}clear(){this.sentCount=0,this.lastAck=null,this.responseLogs.length=0,this.lastCompression=null}};var Q=class{constructor(e,t={}){this.sentBatches=[];this.sendAttempts=0;this.lastAck=null;this.logger=e,this.options=t}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");if(this.sendAttempts+=1,this.options.failUntilAttempt!==void 0&&this.sendAttempts<this.options.failUntilAttempt)throw new Error(`[MockSender] Simulated failure (attempt ${this.sendAttempts})`);if(this.options.simulateTimeout)throw new DOMException("The operation was aborted.","AbortError");return await this.waitWithAbort(t?.signal),this.sentBatches.push([...e]),this.lastAck=!0,this.logger.debug(`[MockSender] Simulated send of ${e.length} event(s)`),{ack:!0,eventCount:e.length}}getSentBatches(){return this.sentBatches.map(e=>[...e])}getSentCount(){return this.sentBatches.reduce((e,t)=>e+t.length,0)}getLogs(){return this.sentBatches.map(e=>`[MockSender] ${e.map(t=>t.type).join(", ")}`)}getState(){return{sentCount:this.getSentCount(),logs:this.getLogs(),lastAck:this.lastAck}}clear(){this.sentBatches.length=0,this.sendAttempts=0,this.lastAck=null}configure(e){e.delayMs!==void 0&&(this.options.delayMs=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((r,i)=>{let o=setTimeout(()=>{a(),r()},t),s=()=>{a(),i(new DOMException("The operation was aborted.","AbortError"))},a=()=>{clearTimeout(o),e?.removeEventListener("abort",s)};if(e?.aborted){a(),i(new DOMException("The operation was aborted.","AbortError"));return}e?.addEventListener("abort",s)})}};var Bt=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 r=this.abortController,i=[r.signal,t?.signal].filter(Boolean),o=cn(i),s=setTimeout(()=>r.abort(),this.timeoutMs);try{return await this.inner.send(e,{signal:o})}finally{clearTimeout(s),this.abortController===r&&(this.abortController=null)}}abortPending(){this.abortController?.abort(),this.abortController=null}};function cn(n){if(n.length===0)return;if(n.length===1)return n[0];let e=new AbortController;for(let t of n){if(t.aborted)return e.abort(),e.signal;t.addEventListener("abort",()=>e.abort(),{once:!0})}return e.signal}var qt=class{constructor(e,t,r){this.active=!1;this.context=e;let i=e.config.modules.transport;if(this.orderingManager=new Ne({enabled:i.ordering.enabled}),this.backpressureManager=new Ue({enabled:i.backpressure.enabled,maxQueueSize:i.backpressure.maxQueueSize,policy:i.backpressure.policy,sampleRate:i.backpressure.sampleRate}),this.deadLetterManager=new Oe({enabled:i.deadLetter.enabled,maxEntries:i.deadLetter.maxEntries}),this.circuitBreaker=new ze({enabled:i.circuitBreaker.enabled,failureThreshold:i.circuitBreaker.failureThreshold,resetTimeoutMs:i.circuitBreaker.resetTimeoutMs,halfOpenMaxAttempts:i.circuitBreaker.halfOpenMaxAttempts}),this.coordinationManager=new Le({enabled:i.coordination.enabled},e.config.identity.pixelId||"pixel"),t)this.queue=t,this.persistentQueue=null;else if(i.persistence.enabled){let m=or(e.config);this.persistentQueue=new _t(m,this.orderingManager,this.backpressureManager),this.queue=this.persistentQueue}else this.persistentQueue=null,this.queue=new Lt;this.pipeline=Ft.createDefault(this.queue);let o=nr(i.compression),s=new Nt(e),a=r===void 0&&(i.sender?.mode==="http"||!i.mockSender.enabled&&i.sender?.mode!=="mock");this.senderMode=r instanceof K||a?"http":"mock";let l=r instanceof Q?r:new Q(e.logger);this.mockSender=r instanceof Q||!r?l:null,this.httpSender=r instanceof K?r:a?new K({apiEndpoint:e.config.transport.apiEndpoint,timeoutMs:i.timeout.timeoutMs},s,o,e.logger):null;let c=r??this.httpSender??l;i.circuitBreaker.enabled&&(c=new $e(this.circuitBreaker,c));let u=null;if(i.timeout.enabled&&(u=new Bt(c,{timeoutMs:i.timeout.timeoutMs}),c=u),this.timedSender=u,this.persistentQueue?(this.replayManager=new Ve({enabled:i.replay.enabled},this.persistentQueue),this.replayManager.setReplayHandler(()=>this.forwardQueuedEvents())):this.replayManager=null,i.retry.enabled||i.batch.enabled||i.offline.enabled||i.flush.enabled){let m=new wt,d=new kt({flushIntervalMs:i.flush.enabled?i.flush.flushIntervalMs:0,flushOnDestroy:i.flush.flushOnDestroy,prepareUnloadHooks:i.flush.prepareUnloadHooks}),p=new Ot({maxAttempts:i.retry.maxAttempts,baseDelayMs:i.retry.baseDelayMs,maxDelayMs:i.retry.maxDelayMs,multiplier:i.retry.multiplier},e.logger),g=new At;this.delivery=new It({batchManager:m,flushManager:d,retryEngine:p,offlineDetector:g,sender:c,config:{batch:{batchSize:i.batch.batchSize,flushIntervalMs:i.batch.flushIntervalMs,maxWaitMs:i.batch.maxWaitMs},timeoutMs:i.timeout.timeoutMs},logger:e.logger,abortPending:()=>u?.abortPending(),onPermanentFailure:i.deadLetter.enabled?(T,G)=>{this.deadLetterManager.move(T,"max_retries_exceeded",i.retry.maxAttempts,G instanceof Error?G.message:String(G))}:void 0})}else this.delivery=null}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.mockSender?.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())}configureMockSender(e){this.mockSender?.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 r of t)this.queue.enqueue(r);return t.length}return 0}getQueue(){return this.queue}getPipelineSteps(){return this.pipeline.getLastSteps()}getDebugState(){let e=this.httpSender?.getState()??this.mockSender?.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:kr(this.context.config.modules.transport.compression,nr(this.context.config.modules.transport.compression),this.httpSender?.getState().compression??null),senderMode:this.senderMode}}}forwardQueuedEvents(){if(!this.coordinationManager.canSend())return;let e=[];for(;!this.queue.isEmpty();){let r=this.queue.dequeue();r&&e.push(r)}if(e.length===0)return;if(this.delivery){this.delivery.ingest(e);return}(this.httpSender??this.mockSender)?.send(e).catch(r=>{for(let i of e)this.queue.enqueue(i);this.context.logger.error("[TransportEngine] Direct send failed",r)})}};var He=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.modules.transport.enabled){e.logger.debug("[Pixel] Transport module disabled");return}e.logger.debug("[Pixel] Transport module initialized"),this.engine=new qt(e),await this.engine.init(),this.subscriber=new Tt(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)}configureMockSender(e){this.engine?.configureMockSender(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 Ke=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 Qe=class{constructor(e,t){this.metadataService=e,this.attribution=t??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),i=r!==void 0&&Object.keys(r).some(o=>{let s=r[o];return s!=null&&s!==""});return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...i?{identifiers:r}:{}}}};var Ge=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 We={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},sr="attribution";var un=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],Ye=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},i={};for(let o of un){let s=t.get(o);s&&(o==="li_fat_id"?r.liFatId=s:r[o]=s)}for(let o of e){let s=t.get(o);s&&(i[o]=s)}return Object.keys(i).length>0&&(r.customClickIds=i),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var je=class{collectKnown(){if(typeof document>"u")return{};let e=this.parseCookies(),t={},r={_fbp:"fbp",_fbc:"fbc",_ga:"ga",_gid:"gid",_gcl_au:"gclAu",_ttp:"ttp",li_fat_id:"liFatId",epik:"epik"};for(let[i,o]of Object.entries(r)){let s=e[i];s&&(t[o]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...i]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(i.join("=")||"")),e},{})}catch{return{}}}};var Xe=class{constructor(e={}){this.clickIdParser=new Ye;this.cookieCollector=new je;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():{},r={...t,...e},i={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(i).length>0&&(r.customClickIds=i),typeof r.fbclid=="string"&&r.fbclid){let o=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);o&&(r.fbc=o)}if(typeof window<"u")try{r.landingUrl=window.location.href}catch{}if(typeof document<"u")try{document.referrer&&(r.referrer=document.referrer)}catch{}return r}merge(e,t){let r={...e};for(let[o,s]of Object.entries(t))if(!(s==null||s==="")){if(o==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[o]=s}let i=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=i),r.lastCollectedAt=i,r}};var Je=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??sr}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 Ze=class{constructor(e,t=We){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new Je(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new Xe({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 Vt=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 Ut=class{constructor(){this.listeners=new Set;this.lastEvent=null}dispatch(e){this.lastEvent=e;for(let t of this.listeners)t(e)}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}};var dn="fingerprint";function pn(n){let e=0;for(let i=0;i<n.length;i++)e=(e<<5)-e+n.charCodeAt(i),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let i=n.length-1;i>=0;i--)r=(r<<5)-r+n.charCodeAt(i),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function mn(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return pn(t.join("|"))}var zt=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??dn,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=mn(this.metadataService);return this.storage.set(this.storageKey,t),t}};var V=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 r=0;r<this.storage.length;r++){let i=this.storage.key(r);i&&e(i)&&t.push(i)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var k=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 gn(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var et=class{constructor(e,t,r){this.adapter=e,this.namespace=t,this.prefix=r}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(gn(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 ar(n){let e=n??"memory";if(typeof window>"u")return new k;switch(e){case"memory":return new k;case"localStorage":return new V(window.localStorage);case"sessionStorage":return new V(window.sessionStorage);case"cookie_localStorage":return new V(window.localStorage);case"cookie":return new k;case"indexedDB":return new k;default:return new k}}function lr(n){switch(n??"memory"){case"localStorage":case"sessionStorage":case"cookie_localStorage":return"BrowserStorageAdapter";default:return"MemoryStorageAdapter"}}function hn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function $t(){return`ses_${hn()}`}var fn="session",Ht=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??fn}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(),r=Date.now();if(!t){let i=$t();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let i=t.sessionId,o=$t();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!0,previousSessionId:i,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=$t();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 yn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Fr(){return`vst_${yn()}`}var vn="visitor",Kt=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??vn}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Fr();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var tt=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new Ke,this.fallbackLogger=new Ge(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();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 r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(i){e.error(`[Pixel] Failed to destroy module "${r.name}"`,i)}}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}createServices(){let{namespace:e,prefix:t,persistence:r}=this.config.storage,i=this.createStorageService(e,t,r?.visitor),o=this.createStorageService(e,t,r?.session),s=this.createStorageService(e,t,r?.attribution),a=this.createStorageService(e,t,r?.attribution??"localStorage"),l=this.createStorageService(e,t,"memory"),c=new Vt,u=new Ze(a,this.config.attribution??We),m=new Qe(c,u),d=new Kt(i,this.config),p=new Ht(o,this.config),g=new zt(s,this.config,c),T=new Ut;return{storage:l,visitor:d,session:p,fingerprint:g,dispatcher:T,browserMetadata:c,eventBuilder:m,attribution:u}}createStorageService(e,t,r){return new et(ar(r),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices()}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return{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.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};var Qt=class{constructor(e){this.runtime=new tt(e),this.conversionModule=new ce,this.transportModule=new He,this.integrationsModule=new Fe,this.runtime.register(new _e),this.runtime.register(this.transportModule),this.runtime.register(this.integrationsModule),this.runtime.register(new ge),this.runtime.register(new Z),this.runtime.register(this.conversionModule)}init(){return this.runtime.init()}destroy(){return this.runtime.destroy()}isInitialized(){return this.runtime.isInitialized()}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)}configureTransportMockSender(e){this.transportModule.configureMockSender?.(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()}};var _r={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]};var Lr={enabled:!1,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,selector:"",selectorType:"attribute",visibilityThreshold:.5},heartbeat:{enabled:!1,intervalMs:5e3,hiddenIntervalMs:3e4},engagement:{enabled:!1,weights:{scroll:.3,click:.3,time:.25},thresholds:{low:30,medium:70}}}};var Or={enabled:!1,commerce:{catalog:{products:[]},checkout:{selectedItems:[],allowDynamicItems:!0,calculateValueFrom:"selected_items"},mappings:{attributes:{},fields:{}}},manual:{pageView:{enabled:!1},purchase:{enabled:!1},lead:{enabled:!1},addToCart:{enabled:!1},removeFromCart:{enabled:!1},initiateCheckout:{enabled:!1},addPaymentInfo:{enabled:!1},search:{enabled:!1},viewContent:{enabled:!1}},auto:{enabled:!1,detectors:{lead:{enabled:!1},purchase:{enabled:!1},addToCart:{enabled:!1},removeFromCart:{enabled:!1},initiateCheckout:{enabled:!1},addPaymentInfo:{enabled:!1,paymentMethod:"CREDIT_CARD",cardDetection:!0,autoDispatch:!0},search:{enabled:!1},viewContent:{enabled:!1}}},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 Nr={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}};var Br={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 qr={enabled:!1,consent:{enabled:!1,required:!1},pii:{enabled:!1,hashEmail:!0,hashPhone:!0},anonymization:{enabled:!1,anonymizeIp:!0}};var Vr={enabled:!1,mockSender:{enabled:!0},sender:{mode:"mock"},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,flushIntervalMs:2e3,maxWaitMs:5e3},timeout:{enabled:!0,timeoutMs:1e4},offline:{enabled:!0},flush:{enabled:!0,flushIntervalMs:2e3,flushOnDestroy:!0,prepareUnloadHooks:!0}};var Ur={app:{source:"custom",target:"custom",environment:"production",debug:!1},identity:{pixelId:""},transport:{apiEndpoint:"",timeoutMs:1e4},storage:{prefix:"__gmk",namespace:"pixel",queue:{enabled:!0,persistence:"memory",index:!0}},attribution:{..._r},modules:{core:Nr,behavior:Lr,conversion:Or,transport:Vr,integrations:Br,privacy:qr}};0&&(module.exports={DEFAULT_PIXEL_CONFIG,Pixel,resolveStorageAdapterName});
3
+ //# sourceMappingURL=index.cjs.js.map