@beworke/pixel 0.1.0-rc.11 → 0.1.0-rc.13

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 (71) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{Pixel-BnN86r4X.d.ts → Pixel-BKTvqIwz.d.ts} +4 -4
  3. package/dist/{Pixel-BoUGqCbP.d.mts → Pixel-DgVo0j7D.d.mts} +4 -4
  4. package/dist/{StorageFactory-C0prtNR7.d.mts → StorageFactory-BRtmy983.d.mts} +2 -2
  5. package/dist/{StorageFactory-BfCArzMM.d.ts → StorageFactory-BcOX0fsg.d.ts} +2 -2
  6. package/dist/browser/index.cjs.js +1 -1
  7. package/dist/browser/index.cjs.js.map +1 -1
  8. package/dist/browser/index.d.mts +6 -6
  9. package/dist/browser/index.d.ts +6 -6
  10. package/dist/browser/index.esm.js +1 -1
  11. package/dist/browser/index.esm.js.map +1 -1
  12. package/dist/browser/pixel.buygoods-checkout.global.js +1 -1
  13. package/dist/browser/pixel.buygoods-checkout.global.js.map +1 -1
  14. package/dist/browser/pixel.buygoods-landing.global.js +1 -1
  15. package/dist/browser/pixel.buygoods-landing.global.js.map +1 -1
  16. package/dist/browser/pixel.global.js +1 -1
  17. package/dist/browser/pixel.global.js.map +1 -1
  18. package/dist/browser/pixel.internal-checkout.global.js +1 -1
  19. package/dist/browser/pixel.internal-checkout.global.js.map +1 -1
  20. package/dist/config/index.cjs.js +1 -1
  21. package/dist/config/index.cjs.js.map +1 -1
  22. package/dist/config/index.d.mts +4 -4
  23. package/dist/config/index.d.ts +4 -4
  24. package/dist/config/index.esm.js +1 -1
  25. package/dist/config/index.esm.js.map +1 -1
  26. package/dist/events/index.cjs.js +1 -1
  27. package/dist/events/index.cjs.js.map +1 -1
  28. package/dist/events/index.d.mts +1 -1
  29. package/dist/events/index.d.ts +1 -1
  30. package/dist/events/index.esm.js +1 -1
  31. package/dist/events/index.esm.js.map +1 -1
  32. package/dist/{index-BxT2d-TK.d.mts → index-CKZeennc.d.mts} +36 -2
  33. package/dist/{index-B8u_3PGG.d.ts → index-YlvQBRzR.d.ts} +36 -2
  34. package/dist/index.cjs.js +1 -1
  35. package/dist/index.cjs.js.map +1 -1
  36. package/dist/index.d.mts +9 -9
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.esm.js +1 -1
  39. package/dist/index.esm.js.map +1 -1
  40. package/dist/{pixel-_BSDpx4M.d.mts → pixel-CCHv_ror.d.mts} +17 -1
  41. package/dist/{pixel-DNGbAN5C.d.ts → pixel-CgKoaWS3.d.ts} +17 -1
  42. package/dist/{pixel-default-config-DLRya1tl.d.mts → pixel-default-config-CTtkGKh1.d.mts} +2 -2
  43. package/dist/{pixel-default-config-BMYaqs7i.d.ts → pixel-default-config-D0NZVzDZ.d.ts} +2 -2
  44. package/dist/{pixel-settings-DGxl0MVm.d.mts → pixel-settings-BlhqPyAS.d.mts} +1 -1
  45. package/dist/{pixel-settings-D-t9zQb4.d.ts → pixel-settings-CHyZHDO6.d.ts} +1 -1
  46. package/dist/runtime/index.cjs.js +1 -1
  47. package/dist/runtime/index.cjs.js.map +1 -1
  48. package/dist/runtime/index.d.mts +7 -5
  49. package/dist/runtime/index.d.ts +7 -5
  50. package/dist/runtime/index.esm.js +1 -1
  51. package/dist/runtime/index.esm.js.map +1 -1
  52. package/dist/services/index.cjs.js +1 -1
  53. package/dist/services/index.cjs.js.map +1 -1
  54. package/dist/services/index.d.mts +46 -7
  55. package/dist/services/index.d.ts +46 -7
  56. package/dist/services/index.esm.js +1 -1
  57. package/dist/services/index.esm.js.map +1 -1
  58. package/dist/{types-B-Nzagpk.d.mts → types-9Uo3slwh.d.mts} +2 -2
  59. package/dist/{types-D3kJ9bfT.d.ts → types-CN1t3kwE.d.mts} +3 -2
  60. package/dist/{types-Dfi9C49l.d.ts → types-DaSPqzo_.d.ts} +2 -2
  61. package/dist/{types-D0KVsgzs.d.mts → types-DexAGG5B.d.ts} +3 -2
  62. package/dist/v2/global.global.js +1 -1
  63. package/dist/v2/global.global.js.map +1 -1
  64. package/dist/v2/index.cjs.js +1 -1
  65. package/dist/v2/index.cjs.js.map +1 -1
  66. package/dist/v2/index.d.mts +11 -11
  67. package/dist/v2/index.d.ts +11 -11
  68. package/dist/v2/index.esm.js +1 -1
  69. package/dist/v2/index.esm.js.map +1 -1
  70. package/docs/public/configuration/commerce.md +20 -1
  71. package/package.json +1 -1
@@ -1,13 +1,14 @@
1
- import { P as PixelModule } from '../types-B-Nzagpk.mjs';
2
- export { M as ModuleName, a as PixelRuntimeContext } from '../types-B-Nzagpk.mjs';
3
- import { P as PixelConfig } from '../pixel-_BSDpx4M.mjs';
4
- import { P as PixelRuntimeServices } from '../types-D0KVsgzs.mjs';
1
+ import { P as PixelModule } from '../types-9Uo3slwh.mjs';
2
+ export { M as ModuleName, a as PixelRuntimeContext } from '../types-9Uo3slwh.mjs';
3
+ import { P as PixelConfig } from '../pixel-CCHv_ror.mjs';
4
+ import { P as PixelRuntimeServices } from '../types-CN1t3kwE.mjs';
5
5
  import '../PixelLogger-B21lEjep.mjs';
6
6
  import '../url-context-Ck2LK18V.mjs';
7
- import '../index-BxT2d-TK.mjs';
7
+ import '../index-CKZeennc.mjs';
8
8
 
9
9
  declare class PixelRuntime {
10
10
  private initialized;
11
+ private customerObserver;
11
12
  private readonly initializedModules;
12
13
  private readonly registry;
13
14
  private readonly config;
@@ -25,6 +26,7 @@ declare class PixelRuntime {
25
26
  /** @internal Registered module names (all registered, regardless of enabled). */
26
27
  getRegisteredModuleNames(): readonly string[];
27
28
  private createServices;
29
+ private startCustomerObserver;
28
30
  private createStorageService;
29
31
  private createContext;
30
32
  private getLogger;
@@ -1,13 +1,14 @@
1
- import { P as PixelModule } from '../types-Dfi9C49l.js';
2
- export { M as ModuleName, a as PixelRuntimeContext } from '../types-Dfi9C49l.js';
3
- import { P as PixelConfig } from '../pixel-DNGbAN5C.js';
4
- import { P as PixelRuntimeServices } from '../types-D3kJ9bfT.js';
1
+ import { P as PixelModule } from '../types-DaSPqzo_.js';
2
+ export { M as ModuleName, a as PixelRuntimeContext } from '../types-DaSPqzo_.js';
3
+ import { P as PixelConfig } from '../pixel-CgKoaWS3.js';
4
+ import { P as PixelRuntimeServices } from '../types-DexAGG5B.js';
5
5
  import '../PixelLogger-B21lEjep.js';
6
6
  import '../url-context-Ck2LK18V.js';
7
- import '../index-B8u_3PGG.js';
7
+ import '../index-YlvQBRzR.js';
8
8
 
9
9
  declare class PixelRuntime {
10
10
  private initialized;
11
+ private customerObserver;
11
12
  private readonly initializedModules;
12
13
  private readonly registry;
13
14
  private readonly config;
@@ -25,6 +26,7 @@ declare class PixelRuntime {
25
26
  /** @internal Registered module names (all registered, regardless of enabled). */
26
27
  getRegisteredModuleNames(): readonly string[];
27
28
  private createServices;
29
+ private startCustomerObserver;
28
30
  private createStorageService;
29
31
  private createContext;
30
32
  private getLogger;
@@ -1,3 +1,3 @@
1
1
  /* Pixel v2 — SDK de analytics e conversão */
2
- var R=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 A=class{constructor(e,t,r){this.metadataService=e,this.attribution=t??null,this.urlContext=r??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),o=r!==void 0&&Object.keys(r).some(l=>{let c=r[l];return c!=null&&c!==""}),i=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,a=i!==null&&Object.keys(i.queryParams).length>0,s=i!==null&&(i.urlContext.managed&&Object.keys(i.urlContext.managed).length>0||i.urlContext.forwarded&&Object.keys(i.urlContext.forwarded).length>0||i.urlContext.source&&Object.keys(i.urlContext.source).length>0);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...o?{identifiers:r}:{},...a?{queryParams:{...i.queryParams}}:{},...s?{urlContext:{...i.urlContext.managed?{managed:{...i.urlContext.managed}}:{},...i.urlContext.forwarded?{forwarded:{...i.urlContext.forwarded}}:{},...i.urlContext.source?{source:{...i.urlContext.source}}:{}}}:{}}}};var _=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 D={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ce="attribution";var we=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],U=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},o={};for(let i of we){let a=t.get(i);a&&(i==="li_fat_id"?r.liFatId=a:r[i]=a)}for(let i of e){let a=t.get(i);a&&(o[i]=a)}return Object.keys(o).length>0&&(r.customClickIds=o),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var T=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[o,i]of Object.entries(r)){let a=e[o];a&&(t[i]=a)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...o]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(o.join("=")||"")),e},{})}catch{return{}}}};var M=class{constructor(e={}){this.clickIdParser=new U;this.cookieCollector=new T;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},o={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(o).length>0&&(r.customClickIds=o),typeof r.fbclid=="string"&&r.fbclid){let i=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);i&&(r.fbc=i)}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[i,a]of Object.entries(t))if(!(a==null||a==="")){if(i==="customClickIds"&&typeof a=="object"){r.customClickIds={...e.customClickIds??{},...a};continue}r[i]=a}let o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var L=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??ce}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 O=class{constructor(e,t=D){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new L(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new M({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 Z=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 ee=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let o=t[r];if(o)try{o(e)}catch(i){this.logger?.warn(Re(i,e.type,r))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function Re(n,e,t){let r=n instanceof Error?n.name:typeof n=="object"&&n!==null&&"name"in n?String(n.name):"Error",o=n instanceof Error?n.message:typeof n=="string"?n:"unknown";return o=o.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),o.length>200&&(o=`${o.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:o,timestamp:Date.now()}}var Ae="fingerprint";function _e(n){let e=0;for(let o=0;o<n.length;o++)e=(e<<5)-e+n.charCodeAt(o),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let o=n.length-1;o>=0;o--)r=(r<<5)-r+n.charCodeAt(o),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function De(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return _e(t.join("|"))}var te=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Ae,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=De(this.metadataService);return this.storage.set(this.storageKey,t),t}};var k=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 o=this.storage.key(r);o&&e(o)&&t.push(o)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var I=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 Ue(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var N=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(Ue(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 le(n){let e=n??"memory";if(typeof window>"u")return new I;switch(e){case"memory":return new I;case"localStorage":return new k(window.localStorage);case"sessionStorage":return new k(window.sessionStorage);case"cookie_localStorage":return new k(window.localStorage);case"cookie":return new I;case"indexedDB":return new I;default:return new I}}var F=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 o=typeof r.id=="string"?r.id.trim():"";if(!o||this.productsById.has(o))continue;let i=this.normalizeProduct(r,o,t);this.productsById.set(o,i),this.orderedIds.push(o);let a=typeof i.sku=="string"?i.sku.trim():"";a&&!this.productsBySku.has(a)&&this.productsBySku.set(a,i)}}normalizeProduct(e,t,r){let o=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=typeof e.currency=="string"&&e.currency.trim()?e.currency.trim():r,a=typeof e.quantity=="number"&&Number.isFinite(e.quantity)?e.quantity:void 0;return{...e,id:t,...o!==void 0?{sku:o}:{},...i!==void 0?{currency:i}:{},...a!==void 0?{quantity:a}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var B=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 i=this.itemsByProductId.get(t),a=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,s={...i,...e,productId:t,quantity:r,selected:!0,...a?{metadata:a}:{}};this.itemsByProductId.set(t,s)}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 o=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...o,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 q=class{calculate(e){let r=(Array.isArray(e.items)?e.items:[]).map(a=>this.cloneItem(a));for(let a of r)(a.quantity==null||!Number.isFinite(a.quantity))&&(a.quantity=1);let o=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...o!==void 0?{value:o}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let o of e){if(typeof o.price!="number"||!Number.isFinite(o.price))continue;let i=typeof o.quantity=="number"&&Number.isFinite(o.quantity)?o.quantity:1;t+=o.price*i,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 re={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},de={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...re}};function z(n){switch(n){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var K=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=Me(e.defaultCurrency),this.calculateValueFrom=z(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},o=e.enrichmentSource??"event_or_cart",i=o==="cart"||o==="event_or_cart",a=o==="catalog"||o==="cart"||o==="event_or_cart",s=d(t.priceId)??d(t.productId)??d(r.productId)??(a?this.lookupIdBySku(d(t.sku)??d(r.sku)):void 0),l=!s&&i?this.resolvePrimaryCartItem():null;!s&&l&&(s=l.productId);let c=a&&s?this.catalog.getById(s):a?this.lookupProductBySku(d(t.sku)??d(r.sku)):null,u=s??c?.id,y=i&&u?this.state.getItem(u)??l:null;if(o==="catalog"&&!u&&!c)return{data:{...t}};let g=d(t.productName)??d(r.productName)??c?.name,p=v(t.price)??v(r.price)??(i?v(y?.price):void 0)??c?.price,m=v(t.quantity)??v(r.quantity)??(i?v(y?.quantity):void 0)??c?.quantity??1,f=d(t.currency)??d(r.currency)??(i?d(y?.currency):void 0)??c?.currency??this.defaultCurrency,S=Te(c,{priceId:d(t.priceId),productId:u,offerId:d(t.offerId),id:d(t.id)}),x={};S.id&&(x.id=S.id),S.priceId&&(x.priceId=S.priceId),S.productId&&(x.productId=S.productId),S.offerId&&(x.offerId=S.offerId),g&&(x.productName=g),p!==void 0&&(x.price=p),f&&(x.currency=f),m!==void 0&&(x.quantity=m);for(let[Y,J]of Object.entries(t))J!==void 0&&(Y in x||(x[Y]=J));return{data:x}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},o=d(t.productId)??d(r.productId)??this.lookupIdBySku(d(t.sku)??d(r.sku)),i=o?this.catalog.getById(o):null,a=o??i?.id,s=a?this.state.getItem(a):null,l=v(t.quantity)??v(r.quantity)??v(s?.quantity)??1,c={};a&&(c.productId=a),l!==void 0&&(c.quantity=l);for(let[u,y]of Object.entries(t))y!==void 0&&(u in c||(c[u]=y));return{data:c}}resolveCheckoutLike(e,t){let r={...e.payload??{}},o=v(r.value),i=d(r.currency),a=this.readPayloadItems(e),s=e.enrichmentSource,l=this.resolveItemsSource(a,s),c=l.map(S=>this.toPixelItem(S)),u=s!=="catalog"&&this.calculateValueFrom!=="manual",y=o===void 0&&u,g=this.calculator.calculate({items:l,value:y?void 0:o,currency:i,defaultCurrency:this.defaultCurrency}),p=o!==void 0?o:u?g.value:void 0,m=i??g.currency??this.defaultCurrency,f={...r};return c.length>0?f.items=c:a===null&&delete f.items,p!==void 0?f.value=p:delete f.value,m&&(f.currency=m),{data:f,items:g.items,...p!==void 0?{value:p}:{},...m?{currency:m}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),a={...t},s=d(t.contentId)??d(o.data.productId)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].id=="string"?i.data.items[0].id:void 0),l=d(t.contentName)??d(o.data.productName)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].name=="string"?i.data.items[0].name:void 0);return s&&(a.contentId=s),l&&(a.contentName=l),v(t.value)===void 0&&i.value!==void 0&&(a.value=i.value),!d(t.currency)&&i.currency&&(a.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(a.items=i.data.items),{data:a,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let o=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return o.data.productId&&!d(t.contentId)&&(i.contentId=o.data.productId),o.data.productName&&!d(t.contentName)&&(i.contentName=o.data.productName),o.data.price!==void 0&&v(t.value)===void 0&&(i.value=o.data.price),o.data.currency&&!d(t.currency)&&(i.currency=o.data.currency),{data:i}}return{data:t}}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,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(o=>this.enrichItem({productId:o.productId,price:o.price,quantity:o.quantity,currency:o.currency})):this.catalog.list().map(o=>this.enrichItem({productId:o.id,price:o.price,quantity:o.quantity??1,currency:o.currency,productName:o.name,sku:o.sku,category:o.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),o=t??r?.id;return{...e,...o?{productId:o}:{},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:d(e.productId)??d(e.id),sku:d(e.sku),productName:d(e.productName)??d(e.name),price:v(e.price),quantity:v(e.quantity),currency:d(e.currency),category:d(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function Te(n,e){let t=n?.metadata??{},r=d(t.priceId),o=d(t.productId),i=d(t.offerId),a=e.priceId??r;if(!a){let s=e.productId??n?.id;return{...e.id?{id:e.id}:{},...s?{productId:s}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??a,priceId:a,productId:o??e.productId??a,offerId:i??e.offerId??a}}function d(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function v(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function Me(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var V=class{constructor(e){this.config={...de,...e,catalog:{products:e?.catalog?.products??[]},cart:{...de.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...re,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new F(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new B(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new K({catalog:this.catalog,state:this.state,calculator:new q,defaultCurrency:this.config.currency,calculateValueFrom:z(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=re[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],o=r[0],i=o&&typeof o.id=="string"?o.id:void 0,a=o&&typeof o.name=="string"?o.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...i?{contentId:i}:{},...a?{contentName:a}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return z(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Le(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function oe(){return`ses_${Le()}`}var Oe="session",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Oe}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 o=oe();return this.writeSessionData({sessionId:o,lastActivityAt:r,createdAt:r}),{sessionId:o,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let o=t.sessionId,i=oe();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:o,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=oe();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 Ne(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ie(){return`vst_${Ne()}`}var Fe="visitor",ie=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Fe}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ie();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var ue=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],me=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],ge=["[data-no-url-context]","[download]"],be="[data-no-sid]";function b(n){return n.trim().toLowerCase()}function $(n){try{return decodeURIComponent(n)}catch{return n}}function j(n,e){let t=new Set;if(e!==!1)for(let r of ue)t.add(b(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(b(r));return t}function fe(n,e){let t=[];e!==!1&&t.push(...me);for(let r of n??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function pe(n,e,t){let r=[];e!==!1&&r.push(...ge),t&&r.push(be);for(let o of n??[])typeof o=="string"&&o.trim()&&r.push(o.trim());return Array.from(new Set(r))}function ae(n,e){return e.has(b(n))}function Pe(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function ye(n,e,t){if(!n)return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local");for(let r of t)if(Pe(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local"?!1:Pe(n,r))}function he(n="sid"){let e=(n||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),r=Math.random().toString(36).slice(2,10);return`${e}_${t}_${r}`}function h(){return typeof window<"u"&&typeof document<"u"}function Ce(n){if(h())try{History.prototype.replaceState.call(history,history.state,document.title,n)}catch{}}function P(n){let e={};if(!n||n==="?")return e;let t=n.startsWith("?")?n.slice(1):n;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let o=r.indexOf("="),i=$((o>=0?r.slice(0,o):r).replace(/\+/g," ")).trim();if(!i)continue;let a=o>=0?$(r.slice(o+1).replace(/\+/g," ")):"";e[i]=a}return e}function H(n){let e=[];for(let[t,r]of Object.entries(n))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function C(n){return Object.freeze({...n})}function ve(n,e){let t=n.trim(),r=e.search||"",o=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${o}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${o}`:t.startsWith("#")?`${r}${o}`:`${t.split(/[?#]/)[0]??t}${r}${o}`}var X=class{collect(e){if(!e||e.enabled===!1)return{};if(!h())return{};let t=P(window.location.search),r=j(e.denylist,e.mergeDefaultDenylist),o=e.mode??"all_except",i=new Set((e.allowlist??[]).map(b).filter(Boolean)),a={};for(let[s,l]of Object.entries(t))ae(s,r)||o==="allowlist"&&!i.has(b(s))||l!==""&&(a[s]=l);return a}};var W=class{constructor(e){this.store=e}resolve(e){let t={},r={},o={},i={},a=h()?P(window.location.search):{};for(let s of e){let l=s.param?.trim();if(!l)continue;let c=s.mode??"read_write",u=c==="read_only"||c==="read_write",y=c==="write_only"||c==="read_write",g=null,p=null;if(u){let m=a[l];m&&m.length>0&&(g=m,p="url")}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.cookie?.name?.trim()||l;if(s.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(m);f&&(g=f,p="cookie")}}if(!g&&u&&s.persistence?.enabled!==!1){let m=s.persistence?.storageKey?.trim()||l,f=this.store.getStorage(m);f&&(g=f,p="storage")}!g&&y&&s.generator?.type==="public_id"&&(g=he(s.generator.prefix??l),p="generated"),!(!g||!p)&&(t[l]=g,r[l]=p,s.decorateLinks!==!1&&(o[l]=g),s.persistence?.enabled!==!1&&this.persist(s,g),y&&(s.writeStrategy??"replaceState")==="replaceState"&&h()&&a[l]!==g&&(i[l]=g))}return Object.keys(i).length>0&&h()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:o}}applyExternalValue(e,t){let r=t.trim();r&&(e.persistence?.enabled!==!1&&this.persist(e,r),(e.writeStrategy??"replaceState")==="replaceState"&&h()&&this.writeToUrl({[e.param]:r}))}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",o=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,a=i?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(o,t),(r==="cookie"||r==="localStorage_cookie")&&i?.enabled!==!1&&this.store.setCookie({name:a,value:t,path:i?.path??"/",domain:i?.domain??"auto",sameSite:i?.sameSite??"Lax",secure:i?.secure??!0,maxAgeMs:i?.maxAgeMs})}writeToUrl(e){let r={...P(window.location.search),...e},o=H(r),i=window.location.hash??"",a=window.location.pathname+o+i;Ce(a)}};var G=class{resolve(e){let{queryParams:t,managedValues:r,config:o}=e;if(!o||o.enabled===!1)return{};let i=j(o.denylist,o.mergeDefaultDenylist),a=o.mode??"all_except",s=new Set((o.allowlist??[]).map(b).filter(Boolean)),l={};for(let[c,u]of Object.entries(t))u&&(ae(c,i)||c in r||a==="allowlist"&&!s.has(b(c))||(l[c]=u));return l}};var Be=["mailto:","tel:","javascript:","data:","blob:"],E=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;if(qe(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=fe(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=pe(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let o=e,i=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...o}),this.config=i,this.excludedDomains=fe(i.excludedDomains,i.mergeDefaultExcludedDomains),this.excludeSelectors=pe(i.excludeSelectors,i.mergeDefaultExcludeSelectors,r===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!h()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!h()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let r=ze(t.target);r&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let r=e.trim(),o=r.toLowerCase();for(let m of Be)if(o.startsWith(m))return m==="mailto:"&&this.config.decorateMailto===!0||m==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let i;try{let m=h()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!ye(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let a=P(i.search),s=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,c={...a},u=!1;for(let[m,f]of Object.entries(this.forwardedParams))m in c&&s&&!l||(c[m]!==f&&(u=!0),c[m]=f);for(let[m,f]of Object.entries(this.managedParams))c[m]!==f&&(u=!0),c[m]=f;let y=P(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),g=Ke(r)>Object.keys(y).length;if(!u&&!g)return r;let p=H(c);return i.search=p.startsWith("?")?p.slice(1):p,ve(r,i)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let r of t)r instanceof HTMLAnchorElement&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let r=this.decorateHref(t);r!=null&&r!==t&&e.setAttribute("href",r)}};function qe(n){return typeof n=="object"&&n!==null&&"config"in n&&typeof n.config=="object"&&n.config!==null}function ze(n){return n instanceof Element?n.closest("a[href]"):null}function Ke(n){let e=n.indexOf("?");if(e<0)return 0;let t=n.indexOf("#",e),r=t>=0?n.slice(e+1,t):n.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var Q=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!h())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let o=r.indexOf("=");if((o>=0?r.slice(0,o):r).trim()!==e)continue;let a=o>=0?r.slice(o+1).trim():"";return $(a)}}catch{return null}return null}setCookie(e){if(!h())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Ve(e.domain);r&&t.push(`domain=${r}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let o=e.sameSite??"Lax";t.push(`SameSite=${o}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Ve(n){if(!n||n==="auto"){if(!h())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return n}var Ee={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},je={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},He={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Xe={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function se(n){if(!n||n.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=n.managedParams!==void 0?n.managedParams.map(ke):[ke(Ee)];return{enabled:!0,queryParams:{...je,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...He,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...Xe,...n.linkDecoration,...n.linkDecoration?.allowedDomains&&n.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...n.linkDecoration.allowedDomains]}:{},...n.linkDecoration?.excludedDomains?{excludedDomains:[...n.linkDecoration.excludedDomains]}:{},...n.linkDecoration?.excludeSelectors?{excludeSelectors:[...n.linkDecoration.excludeSelectors]}:{}}}}function ke(n){return{...n,...n.generator?{generator:{...n.generator}}:{},...n.persistence?{persistence:{...n.persistence,...n.persistence.cookie?{cookie:{...n.persistence.cookie}}:{}}}:{}}}var w=class{constructor(e,t){this.collector=new X;this.forwardResolver=new G;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=xe();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=se(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=xe();return}this.store=new Q(this.storage),this.managedResolver=new W(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),o=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,i=this.forwardResolver.resolve({queryParams:o,managedValues:r.values,config:e.forwardParams}),a={...r.sources};for(let u of Object.keys(i))a[u]||(a[u]="url");let s={...Object.keys(r.values).length>0?{managed:C(r.values)}:{},...Object.keys(i).length>0?{forwarded:C(i)}:{},...Object.keys(a).length>0?{source:Object.freeze({...a})}:{}};this.snapshot={queryParams:C(o),urlContext:Object.freeze(s)};let l=C(i);this.decorateManaged={...r.decorateParams};let c=e.managedParams.some(u=>u.param==="sid"&&u.decorateLinks!==!1);this.decorator=new E({forwardedParams:l,managedParams:C(this.decorateManaged),config:e.linkDecoration,includeSidExclude:c}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let r=e.trim(),o=t.trim();if(!r||!o)return!1;let i=this.managedConfigs.find(y=>y.param===r);if(!i)return!1;if(this.snapshot.urlContext.managed?.[r]===o)return!0;this.managedResolver.applyExternalValue(i,o);let s={...this.snapshot.urlContext.managed??{},[r]:o},l={...this.snapshot.urlContext.source??{},[r]:"manual"},c=se(this.rawConfig),u=this.collector.collect(c.queryParams);if(this.snapshot={queryParams:C(u),urlContext:Object.freeze({managed:C(s),...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...l})})},i.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[r]:o},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&c.enabled)){let y=this.managedConfigs.some(g=>g.param==="sid"&&g.decorateLinks!==!1);this.decorator=new E({forwardedParams:C(this.snapshot.urlContext.forwarded??{}),managedParams:C(this.decorateManaged),config:c.linkDecoration,includeSidExclude:y}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=xe()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:C(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:C(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function xe(){return{queryParams:C({}),urlContext:Object.freeze({})}}var Se=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new R,this.fallbackLogger=new _(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(o){e.error(`[Pixel] Failed to destroy module "${r.name}"`,o)}}this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:r,persistence:o}=this.config.storage,i=this.createStorageService(t,r,o?.visitor),a=this.createStorageService(t,r,o?.session),s=this.createStorageService(t,r,o?.attribution),l=this.createStorageService(t,r,o?.attribution??"localStorage"),c=this.createStorageService(t,r,"memory"),u=new Z,y=new O(l,this.config.attribution??D),g=this.createStorageService(t,r,o?.attribution??"localStorage"),p=new w(this.config.modules.core.urlContext,g),m=new A(u,y,p),f=new ie(i,this.config),S=new ne(a,this.config),x=new te(s,this.config,u),Y=new ee(e),J=new V(this.config.commerce);return{storage:c,visitor:f,session:S,fingerprint:x,dispatcher:Y,browserMetadata:u,eventBuilder:m,attribution:y,commerce:J,urlContext:p}}createStorageService(e,t,r){return new N(le(r),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};export{R as ModuleRegistry,Se as PixelRuntime};
2
+ var _=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}};function D(o){return o?Object.values(o).some(e=>typeof e=="string"&&e.trim().length>0):!1}function ge(o){return{...o}}var T=class{constructor(){this.snapshot={}}update(e){let t={...this.snapshot};for(let[r,n]of Object.entries(e)){if(typeof n!="string")continue;let i=n.trim();i&&(t[r]=i)}!t.name&&t.firstName&&(t.name=[t.firstName,t.lastName].filter(Boolean).join(" ")),this.snapshot=t}getSnapshot(){return D(this.snapshot)?ge(this.snapshot):null}clear(){this.snapshot={}}};var Xe=/\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 ye(o){return typeof Element<"u"&&o instanceof Element}function he(o){return typeof HTMLFormElement<"u"&&o instanceof HTMLFormElement}function Ce(o){return typeof HTMLInputElement<"u"&&o instanceof HTMLInputElement}function L(o){if(o==null)return;let e=String(o).trim();return e.length>0?e:void 0}function Me(o){if(Ce(o)&&o.type==="password")return!0;let e=[o.getAttribute("name"),o.getAttribute("id"),o.getAttribute("autocomplete"),o.getAttribute("placeholder"),o.getAttribute("aria-label")].filter(Boolean).join(" ");return Xe.test(e)}function Ue(o,e){for(let t of e){if(!t)continue;let r=(t.startsWith("data-"),t),n=L(o.getAttribute(r));if(n)return n}}function k(o){if(!Me(o)&&(Ce(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement))return L(o.value)}function We(o){return/^[#.\[:]/.test(o)||/[\s>+~]/.test(o)}function Fe(o,e){for(let t of e)if(!(!t||!We(t)))try{let r=o.matches(t)?o:o.querySelector(t);if(!r)continue;let n=k(r);if(n)return n}catch{}}function Ne(o,e){for(let r of e){if(!r)continue;let n=o.querySelector(`input[name="${ie(r)}"], textarea[name="${ie(r)}"], select[name="${ie(r)}"], input[id="${ie(r)}"]`);if(n){let i=k(n);if(i)return i}}let t=[];(Ce(o)||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&t.push(o),t.push(...Array.from(o.querySelectorAll("input, textarea, select")));for(let r of e){let n=r.toLowerCase();for(let i of t){if(Me(i))continue;let s=(i.getAttribute("name")??"").toLowerCase(),a=(i.getAttribute("id")??"").toLowerCase();if(!Ge(s,a,n))continue;let c=k(i);if(c)return c}}}function Ge(o,e,t){return o===t||e===t?!0:t.length<4?!1:o.includes(t)||e.includes(t)}function ie(o){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(o):o.replace(/["\\]/g,"\\$&")}function ve(...o){let e={};for(let t of o)if(t)for(let[r,n]of Object.entries(t))n==null||n===""||e[r]===void 0&&(e[r]=n);return e}function Oe(o,e){let t=new Set,r=[];for(let n of[...o??[],...e]){let i=n?.trim();!i||t.has(i)||(t.add(i),r.push(i))}return r}var Qe=["email","emailaddress","customerEmail","customer_email","e-mail"],Ye=["phone","telefone","tel","customerPhone","customer_phone","celular","mobile"],Ze=["name","nome","fullName","full_name","fullname","billing_name"],Je=["firstName","first_name","firstname","first-name","fname","primeiro","primeiro_nome","given-name"],et=["lastName","last_name","lastname","last-name","lname","sobrenome","family-name"],tt=["address","street","street_address","billing_address","shipping_address","endereco"],rt=["address2","address_2","apt","apartment","suite","complement","complemento"],nt=["city","cidade","billing_city","shipping_city"],ot=["state","estado","region","billing_state","shipping_state"],it=["postalCode","postal_code","postal","zip","zipcode","zip_code","cep","billing_zip"],st=["country","pais","billing_country","country_code"],at=["data-email"],ct=["data-phone","data-telefone"],lt=["data-name","data-nome"],ut=["data-first-name","data-firstname"],dt=["data-last-name","data-lastname"],mt=["data-address"],ft=["data-address2","data-apt"],pt=["data-city"],gt=["data-state"],yt=["data-zip","data-postal"],ht=["data-country"],A=class{constructor(e={}){this.fieldMappings=e.fieldMappings??{}}extractFromElement(e){if(!ye(e))return{};let t=this.extractFromScope(e),r=e.closest("form"),n=he(r)?this.extractFromScope(r):{},i=this.findCustomerContainer(e),s=i&&i!==e&&i!==r?this.extractFromScope(i):{};return ve(t,n,s)}extractFromForm(e){return he(e)?this.extractFromScope(e):{}}extractFromContainer(e){return ye(e)?this.extractFromScope(e):{}}extractFromScope(e){let t=this.pick(e,{mappingKey:"firstName",defaults:Je,autocomplete:"given-name",attrs:ut}),r=this.pick(e,{mappingKey:"lastName",defaults:et,autocomplete:"family-name",attrs:dt}),n=this.pick(e,{mappingKey:"name",defaults:Ze,autocomplete:"name",attrs:lt}),i=t&&r?`${t} ${r}`:t??r,s=t&&r?i:n??i;return ve({email:this.pick(e,{mappingKey:"email",defaults:Qe,type:"email",autocomplete:"email",attrs:at}),phone:this.pick(e,{mappingKey:"phone",defaults:Ye,type:"tel",autocomplete:"tel",attrs:ct}),name:L(s),firstName:t,lastName:r,address:this.pick(e,{mappingKey:"address",defaults:tt,autocomplete:["street-address","address-line1"],attrs:mt}),address2:this.pick(e,{mappingKey:"address2",defaults:rt,autocomplete:"address-line2",attrs:ft}),city:this.pick(e,{mappingKey:"city",defaults:nt,autocomplete:"address-level2",attrs:pt}),state:this.pick(e,{mappingKey:"state",defaults:ot,autocomplete:"address-level1",attrs:gt}),postalCode:this.pick(e,{mappingKey:"postalCode",defaults:it,autocomplete:"postal-code",attrs:yt}),country:this.pick(e,{mappingKey:"country",defaults:st,autocomplete:["country-name","country"],attrs:ht})})}pick(e,t){let r=t.type?this.readTypedInput(e,t.type):void 0,n=t.autocomplete?Array.isArray(t.autocomplete)?t.autocomplete:[t.autocomplete]:[],i;for(let a of n)if(i=this.readAutocomplete(e,a),i)break;let s=this.fieldsFor(t.mappingKey,t.defaults);return r??i??(t.attrs?Ue(e,t.attrs):void 0)??Fe(e,s)??Ne(e,s)}fieldsFor(e,t){return Oe(this.fieldMappings[e],t)}readTypedInput(e,t){let r=`input[type="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?k(n):void 0}readAutocomplete(e,t){let r=`input[autocomplete="${t}"], select[autocomplete="${t}"]`,n=e.matches(r)?e:e.querySelector(r);return n?k(n):void 0}findCustomerContainer(e){return e.closest("[data-email], [data-phone], [data-name], [data-track], .lead-form, .checkout-form, #checkout-form, #checkout")}};var Ct=200,M=class{constructor(e,t){this.debounceTimer=null;this.started=!1;this.onFormEvent=()=>{this.scheduleScan()};this.identity=e,this.extractor=t??new A}start(){this.started||typeof document>"u"||(this.started=!0,this.scan(),document.addEventListener("input",this.onFormEvent,!0),document.addEventListener("change",this.onFormEvent,!0))}destroy(){this.started&&(this.started=!1,typeof document<"u"&&(document.removeEventListener("input",this.onFormEvent,!0),document.removeEventListener("change",this.onFormEvent,!0)),this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null))}scan(){if(typeof document>"u")return;let e=document.forms;for(let t=0;t<e.length;t+=1)this.identity.update(this.extractor.extractFromForm(e[t]??null));document.body&&this.identity.update(this.extractor.extractFromContainer(document.body))}scheduleScan(){this.debounceTimer!==null&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.scan()},Ct)}};var U=class{constructor(e,t,r,n){this.metadataService=e,this.attribution=t??null,this.urlContext=r??null,this.customerIdentity=n??null}build(e){let t=this.metadataService.getMetadata(),r=this.attribution?.getSnapshot(),n=r!==void 0&&Object.keys(r).some(g=>{let f=r[g];return f!=null&&f!==""}),i=this.urlContext?.isEnabled()?this.urlContext.getSnapshot():null,s=i!==null&&Object.keys(i.queryParams).length>0,a=i!==null&&(i.urlContext.managed&&Object.keys(i.urlContext.managed).length>0||i.urlContext.forwarded&&Object.keys(i.urlContext.forwarded).length>0||i.urlContext.source&&Object.keys(i.urlContext.source).length>0),c=this.customerIdentity?.getSnapshot()??null,d=e.customer??c;return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...n?{identifiers:r}:{},...s?{queryParams:{...i.queryParams}}:{},...a?{urlContext:{...i.urlContext.managed?{managed:{...i.urlContext.managed}}:{},...i.urlContext.forwarded?{forwarded:{...i.urlContext.forwarded}}:{},...i.urlContext.source?{source:{...i.urlContext.source}}:{}}}:{},...D(d)?{customer:{...d}}:{}}}};var F=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 N={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},Se="attribution";var vt=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],O=class{parse(e=[]){if(typeof window>"u"||!window.location?.search)return{};try{let t=new URLSearchParams(window.location.search),r={},n={};for(let i of vt){let s=t.get(i);s&&(i==="li_fat_id"?r.liFatId=s:r[i]=s)}for(let i of e){let s=t.get(i);s&&(n[i]=s)}return Object.keys(n).length>0&&(r.customClickIds=n),r}catch{return{}}}synthesizeFbc(e,t){if(t)return t;if(e)return`fb.1.${Date.now()}.${e}`}};var B=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[n,i]of Object.entries(r)){let s=e[n];s&&(t[i]=s)}return t}parseCookies(){if(typeof document>"u")return{};try{return document.cookie.split(";").reduce((e,t)=>{let[r,...n]=t.trim().split("=");return r&&(e[r]=decodeURIComponent(n.join("=")||"")),e},{})}catch{return{}}}};var q=class{constructor(e={}){this.clickIdParser=new O;this.cookieCollector=new B;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},n={...t.customClickIds??{},...e.customClickIds??{}};if(Object.keys(n).length>0&&(r.customClickIds=n),typeof r.fbclid=="string"&&r.fbclid){let i=this.clickIdParser.synthesizeFbc(r.fbclid,typeof r.fbc=="string"?r.fbc:void 0);i&&(r.fbc=i)}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[i,s]of Object.entries(t))if(!(s==null||s==="")){if(i==="customClickIds"&&typeof s=="object"){r.customClickIds={...e.customClickIds??{},...s};continue}r[i]=s}let n=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=n),r.lastCollectedAt=n,r}};var K=class{constructor(e,t){this.storage=e,this.persist=t.persist,this.ttlMs=t.ttlDays*24*60*60*1e3,this.storageKey=t.storageKey??Se}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 z=class{constructor(e,t=N){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new K(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new q({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 se=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 ae=class{constructor(e){this.listeners=new Set;this.lastEvent=null;this.logger=e}dispatch(e){this.lastEvent=e;let t=[...this.listeners];for(let r=0;r<t.length;r+=1){let n=t[r];if(n)try{n(e)}catch(i){this.logger?.warn(St(i,e.type,r))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.lastEvent=null}getListenerCount(){return this.listeners.size}getLastEvent(){return this.lastEvent}};function St(o,e,t){let r=o instanceof Error?o.name:typeof o=="object"&&o!==null&&"name"in o?String(o.name):"Error",n=o instanceof Error?o.message:typeof o=="string"?o:"unknown";return n=n.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"[redacted]").replace(/\+?\d[\d\s().-]{7,}\d/g,"[redacted]"),n.length>200&&(n=`${n.slice(0,200)}\u2026`),{code:"DISPATCHER_LISTENER_FAILED",eventType:e,listenerIndex:t,errorName:r,message:n,timestamp:Date.now()}}var xt="fingerprint";function bt(o){let e=0;for(let n=0;n<o.length;n++)e=(e<<5)-e+o.charCodeAt(n),e|=0;let t=Math.abs(e).toString(16).padStart(8,"0"),r=0;for(let n=o.length-1;n>=0;n--)r=(r<<5)-r+o.charCodeAt(n),r|=0;return`fp_${t}${Math.abs(r).toString(16).padStart(8,"0")}`}function It(o){let e=o.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return bt(t.join("|"))}var ce=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??xt,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=It(this.metadataService);return this.storage.set(this.storageKey,t),t}};var P=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 n=this.storage.key(r);n&&e(n)&&t.push(n)}for(let r of t)this.storage.removeItem(r);return}for(let t of this.memoryFallback.keys())e(t)&&this.memoryFallback.delete(t)}};var b=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 Et(o){return"removeKeysMatching"in o&&typeof o.removeKeysMatching=="function"}var V=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(Et(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 xe(o){let e=o??"memory";if(typeof window>"u")return new b;switch(e){case"memory":return new b;case"localStorage":return new P(window.localStorage);case"sessionStorage":return new P(window.sessionStorage);case"cookie_localStorage":return new P(window.localStorage);case"cookie":return new b;case"indexedDB":return new b;default:return new b}}var $=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 n=typeof r.id=="string"?r.id.trim():"";if(!n||this.productsById.has(n))continue;let i=this.normalizeProduct(r,n,t);this.productsById.set(n,i),this.orderedIds.push(n);let s=typeof i.sku=="string"?i.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,i)}}normalizeProduct(e,t,r){let n=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0,i=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,...n!==void 0?{sku:n}:{},...i!==void 0?{currency:i}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var j=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 i=this.itemsByProductId.get(t),s=e.metadata?{...e.metadata}:i?.metadata?{...i.metadata}:void 0,a={...i,...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 n=this.itemsByProductId.get(e);this.itemsByProductId.set(e,{...n,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 H=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 n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:this.sumValue(r),i=this.resolveCurrency(e,r);return{items:r,...n!==void 0?{value:n}:{},...i!==void 0?{currency:i}:{}}}sumValue(e){let t=0,r=!1;for(let n of e){if(typeof n.price!="number"||!Number.isFinite(n.price))continue;let i=typeof n.quantity=="number"&&Number.isFinite(n.quantity)?n.quantity:1;t+=n.price*i,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 Pt=["email","phone","name","firstName","lastName","address","address2","city","state","postalCode","country"],le={pageView:{enabled:!0,source:"cart"},viewContent:{enabled:!0,source:"event_or_cart"},lead:{enabled:!1,source:"event_or_cart"},addToCart:{enabled:!0,source:"event_or_cart"},removeFromCart:{enabled:!0,source:"event_or_cart"},initiateCheckout:{enabled:!0,source:"cart"},addPaymentInfo:{enabled:!0,source:"cart"},purchase:{enabled:!0,source:"cart"}},be={enabled:!0,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},customer:{fields:{}},enrichment:{...le}};function Be(o){return o?(Array.isArray(o)?o:[o]).map(t=>String(t).trim()).filter(Boolean):[]}function qe(o,e){let t={};for(let r of Pt){let n=[...Be(o?.fields?.[r]),...Be(e?.[r])];n.length>0&&(t[r]=n)}return t}function X(o){switch(o){case"event":case"event_items":return"event";case"manual":return"manual";case"catalog":return"catalog";case"cart":case"selected_items":default:return"cart"}}var W=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=At(e.defaultCurrency),this.calculateValueFrom=X(e.calculateValueFrom)}resolve(e){if(e.enrichmentSource==="event")return{data:{...e.payload??{}}};switch(e.eventType){case"ADD_TO_CART":return this.resolveAddToCart(e);case"REMOVE_FROM_CART":return this.resolveRemoveFromCart(e);case"INITIATE_CHECKOUT":return this.resolveCheckoutLike(e,!1);case"PURCHASE":return this.resolveCheckoutLike(e,!0);case"VIEW_CONTENT":return this.resolveViewContent(e);case"ADD_PAYMENT_INFO":return this.resolveCheckoutLike(e,!1);default:return{data:{...e.payload??{}}}}}resolveAddToCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=e.enrichmentSource??"event_or_cart",i=n==="cart"||n==="event_or_cart",s=n==="catalog"||n==="cart"||n==="event_or_cart",a=u(t.priceId)??u(t.productId)??u(r.productId)??(s?this.lookupIdBySku(u(t.sku)??u(r.sku)):void 0),c=!a&&i?this.resolvePrimaryCartItem():null;!a&&c&&(a=c.productId);let l=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(u(t.sku)??u(r.sku)):null,d=a??l?.id,g=i&&d?this.state.getItem(d)??c:null;if(n==="catalog"&&!d&&!l)return{data:{...t}};let f=u(t.productName)??u(r.productName)??l?.name,y=v(t.price)??v(r.price)??(i?v(g?.price):void 0)??l?.price,m=v(t.quantity)??v(r.quantity)??(i?v(g?.quantity):void 0)??l?.quantity??1,p=u(t.currency)??u(r.currency)??(i?u(g?.currency):void 0)??l?.currency??this.defaultCurrency,x=kt(l,{priceId:u(t.priceId),productId:d,offerId:u(t.offerId),id:u(t.id)}),S={};x.id&&(S.id=x.id),x.priceId&&(S.priceId=x.priceId),x.productId&&(S.productId=x.productId),x.offerId&&(S.offerId=x.offerId),f&&(S.productName=f),y!==void 0&&(S.price=y),p&&(S.currency=p),m!==void 0&&(S.quantity=m);for(let[ne,oe]of Object.entries(t))oe!==void 0&&(ne in S||(S[ne]=oe));return{data:S}}resolvePrimaryCartItem(){let e=this.state.getSelectedItems();return e.length===0?null:e.length===1?e[0]??null:e.find(r=>this.catalog.getById(r.productId)?.type==="main")??e[0]??null}resolveRemoveFromCart(e){let t=e.payload??{},r=e.extractedProduct??{},n=u(t.productId)??u(r.productId)??this.lookupIdBySku(u(t.sku)??u(r.sku)),i=n?this.catalog.getById(n):null,s=n??i?.id,a=s?this.state.getItem(s):null,c=v(t.quantity)??v(r.quantity)??v(a?.quantity)??1,l={};s&&(l.productId=s),c!==void 0&&(l.quantity=c);for(let[d,g]of Object.entries(t))g!==void 0&&(d in l||(l[d]=g));return{data:l}}resolveCheckoutLike(e,t){let r={...e.payload??{}},n=v(r.value),i=u(r.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,c=this.resolveItemsSource(s,a),l=c.map(x=>this.toPixelItem(x)),d=a!=="catalog"&&this.calculateValueFrom!=="manual",g=n===void 0&&d,f=this.calculator.calculate({items:c,value:g?void 0:n,currency:i,defaultCurrency:this.defaultCurrency}),y=n!==void 0?n:d?f.value:void 0,m=i??f.currency??this.defaultCurrency,p={...r};return l.length>0?p.items=l:s===null&&delete p.items,y!==void 0?p.value=y:delete p.value,m&&(p.currency=m),{data:p,items:f.items,...y!==void 0?{value:y}:{},...m?{currency:m}:{}}}resolveViewContent(e){let t={...e.payload??{}},r=e.enrichmentSource??"event_or_cart";if(r==="cart"||r==="event_or_cart"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:r}),i=this.resolveCheckoutLike({...e,eventType:"INITIATE_CHECKOUT",enrichmentSource:r},!1),s={...t},a=u(t.contentId)??u(n.data.productId)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].id=="string"?i.data.items[0].id:void 0),c=u(t.contentName)??u(n.data.productName)??(Array.isArray(i.data.items)&&i.data.items[0]&&typeof i.data.items[0].name=="string"?i.data.items[0].name:void 0);return a&&(s.contentId=a),c&&(s.contentName=c),v(t.value)===void 0&&i.value!==void 0&&(s.value=i.value),!u(t.currency)&&i.currency&&(s.currency=i.currency),t.items===void 0&&Array.isArray(i.data.items)&&(s.items=i.data.items),{data:s,...i.value!==void 0?{value:i.value}:{},...i.currency?{currency:i.currency}:{},items:i.items}}if(r==="catalog"){let n=this.resolveAddToCart({...e,eventType:"ADD_TO_CART",enrichmentSource:"catalog"}),i={...t};return n.data.productId&&!u(t.contentId)&&(i.contentId=n.data.productId),n.data.productName&&!u(t.contentName)&&(i.contentName=n.data.productName),n.data.price!==void 0&&v(t.value)===void 0&&(i.value=n.data.price),n.data.currency&&!u(t.currency)&&(i.currency=n.data.currency),{data:i}}return{data:t}}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,t){if(e!==null)return e.map(r=>this.enrichItem(r));if(t==="catalog")return[];if(t==="cart"&&this.calculateValueFrom!=="manual"&&this.calculateValueFrom!=="event")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="cart")return this.state.getSelectedItems().map(r=>this.enrichItem({productId:r.productId,price:r.price,quantity:r.quantity,currency:r.currency}));if(this.calculateValueFrom==="catalog"){let r=this.state.getSelectedItems();return r.length>0?r.map(n=>this.enrichItem({productId:n.productId,price:n.price,quantity:n.quantity,currency:n.currency})):this.catalog.list().map(n=>this.enrichItem({productId:n.id,price:n.price,quantity:n.quantity??1,currency:n.currency,productName:n.name,sku:n.sku,category:n.category}))}return[]}enrichItem(e){let t=e.productId??this.lookupIdBySku(e.sku)??void 0,r=t?this.catalog.getById(t):this.lookupProductBySku(e.sku),n=t??r?.id;return{...e,...n?{productId:n}:{},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:u(e.productId)??u(e.id),sku:u(e.sku),productName:u(e.productName)??u(e.name),price:v(e.price),quantity:v(e.quantity),currency:u(e.currency),category:u(e.category)}}lookupIdBySku(e){if(e)return this.catalog.getBySku(e)?.id}lookupProductBySku(e){return e?this.catalog.getBySku(e):null}};function kt(o,e){let t=o?.metadata??{},r=u(t.priceId),n=u(t.productId),i=u(t.offerId),s=e.priceId??r;if(!s){let a=e.productId??o?.id;return{...e.id?{id:e.id}:{},...a?{productId:a}:{},...e.offerId?{offerId:e.offerId}:{}}}return{id:e.id??s,priceId:s,productId:n??e.productId??s,offerId:i??e.offerId??s}}function u(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}function v(o){if(!(typeof o!="number"||!Number.isFinite(o)))return o}function At(o){if(typeof o!="string")return;let e=o.trim();return e.length>0?e:void 0}var G=class{constructor(e){this.config={...be,...e,catalog:{products:e?.catalog?.products??[]},cart:{...be.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...le,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new $(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new j(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new W({catalog:this.catalog,state:this.state,calculator:new H,defaultCurrency:this.config.currency,calculateValueFrom:X(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=le[e];return{enabled:t?.enabled??r.enabled,source:t?.source??r.source}}isEnabled(){return this.enabled}isEnrichmentEnabled(e){return this.enabled&&this.getEnrichment(e).enabled===!0}getEnrichmentSource(e){return this.getEnrichment(e).source??"event_or_cart"}resolveForEvent(e,t,r={}){return this.isEnrichmentEnabled(e)?this.resolver.resolve({eventType:t,payload:r,enrichmentSource:this.getEnrichmentSource(e)}).data:null}resolvePageViewEnrichment(){if(!this.isEnrichmentEnabled("pageView")||(this.getEnrichment("pageView").source??"cart")==="event")return null;let t=this.resolver.resolve({eventType:"INITIATE_CHECKOUT",payload:{}}),r=t.data.items??[],n=r[0],i=n&&typeof n.id=="string"?n.id:void 0,s=n&&typeof n.name=="string"?n.name:void 0;return t.value===void 0&&!t.currency&&r.length===0?null:{...t.value!==void 0?{value:t.value}:{},...t.currency?{currency:t.currency}:{},...r.length>0?{items:r}:{},...i?{contentId:i}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return X(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function wt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function ue(){return`ses_${wt()}`}var Rt="session",de=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Rt}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 n=ue();return this.writeSessionData({sessionId:n,lastActivityAt:r,createdAt:r}),{sessionId:n,expired:!1,created:!0}}if(r-t.lastActivityAt>e){let n=t.sessionId,i=ue();return this.writeSessionData({sessionId:i,lastActivityAt:r,createdAt:r}),{sessionId:i,expired:!0,previousSessionId:n,created:!1}}return{sessionId:t.sessionId,expired:!1,created:!1}}ensureSessionId(){return this.ensureSession(Number.MAX_SAFE_INTEGER).sessionId}touchActivity(){let e=this.getSessionData();e&&this.writeSessionData({...e,lastActivityAt:Date.now()})}renew(){let e=Date.now(),t=ue();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 _t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Ke(){return`vst_${_t()}`}var Dt="visitor",me=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??Dt}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Ke();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var Ie=["token","access_token","refresh_token","id_token","password","pass","pwd","email","phone","cpf","cnpj","document","card","cc","credit_card","cvv","cvc","auth","code","sessionId","internalSessionId","pixelSessionId"],Ee=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],Pe=["[data-no-url-context]","[download]"],ze="[data-no-sid]";function I(o){return o.trim().toLowerCase()}function Q(o){try{return decodeURIComponent(o)}catch{return o}}function Y(o,e){let t=new Set;if(e!==!1)for(let r of Ie)t.add(I(r));for(let r of o??[])typeof r=="string"&&r.trim()&&t.add(I(r));return t}function ke(o,e){let t=[];e!==!1&&t.push(...Ee);for(let r of o??[])typeof r=="string"&&r.trim()&&t.push(r.trim().toLowerCase());return Array.from(new Set(t.map(r=>r.toLowerCase())))}function Ae(o,e,t){let r=[];e!==!1&&r.push(...Pe),t&&r.push(ze);for(let n of o??[])typeof n=="string"&&n.trim()&&r.push(n.trim());return Array.from(new Set(r))}function fe(o,e){return e.has(I(o))}function Ve(o,e){let r=o.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),n=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===n||r.endsWith(`.${n}`)}function we(o,e,t){if(!o)return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local");for(let r of t)if(Ve(o,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local"?!1:Ve(o,r))}function Re(o="sid"){let e=(o||"sid").replace(/[^a-zA-Z0-9_-]/g,"")||"sid",t=Date.now().toString(36),r=Math.random().toString(36).slice(2,10);return`${e}_${t}_${r}`}function h(){return typeof window<"u"&&typeof document<"u"}function _e(o){if(h())try{History.prototype.replaceState.call(history,history.state,document.title,o)}catch{}}function E(o){let e={};if(!o||o==="?")return e;let t=o.startsWith("?")?o.slice(1):o;if(!t)return e;for(let r of t.split("&")){if(!r)continue;let n=r.indexOf("="),i=Q((n>=0?r.slice(0,n):r).replace(/\+/g," ")).trim();if(!i)continue;let s=n>=0?Q(r.slice(n+1).replace(/\+/g," ")):"";e[i]=s}return e}function Z(o){let e=[];for(let[t,r]of Object.entries(o))t&&e.push(`${encodeURIComponent(t)}=${encodeURIComponent(r??"")}`);return e.length>0?`?${e.join("&")}`:""}function C(o){return Object.freeze({...o})}function De(o,e){let t=o.trim(),r=e.search||"",n=e.hash||"";return t.startsWith("//")?`//${e.host}${e.pathname}${r}${n}`:/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(t)?e.toString():t.startsWith("/")?`${e.pathname}${r}${n}`:t.startsWith("#")?`${r}${n}`:`${t.split(/[?#]/)[0]??t}${r}${n}`}var J=class{collect(e){if(!e||e.enabled===!1)return{};if(!h())return{};let t=E(window.location.search),r=Y(e.denylist,e.mergeDefaultDenylist),n=e.mode??"all_except",i=new Set((e.allowlist??[]).map(I).filter(Boolean)),s={};for(let[a,c]of Object.entries(t))fe(a,r)||n==="allowlist"&&!i.has(I(a))||c!==""&&(s[a]=c);return s}};var ee=class{constructor(e){this.store=e}resolve(e){let t={},r={},n={},i={},s=h()?E(window.location.search):{};for(let a of e){let c=a.param?.trim();if(!c)continue;let l=a.mode??"read_write",d=l==="read_only"||l==="read_write",g=l==="write_only"||l==="read_write",f=null,y=null;if(d){let m=s[c];m&&m.length>0&&(f=m,y="url")}if(!f&&d&&a.persistence?.enabled!==!1){let m=a.persistence?.cookie?.name?.trim()||c;if(a.persistence?.cookie?.enabled!==!1){let p=this.store.getCookie(m);p&&(f=p,y="cookie")}}if(!f&&d&&a.persistence?.enabled!==!1){let m=a.persistence?.storageKey?.trim()||c,p=this.store.getStorage(m);p&&(f=p,y="storage")}!f&&g&&a.generator?.type==="public_id"&&(f=Re(a.generator.prefix??c),y="generated"),!(!f||!y)&&(t[c]=f,r[c]=y,a.decorateLinks!==!1&&(n[c]=f),a.persistence?.enabled!==!1&&this.persist(a,f),g&&(a.writeStrategy??"replaceState")==="replaceState"&&h()&&s[c]!==f&&(i[c]=f))}return Object.keys(i).length>0&&h()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:n}}applyExternalValue(e,t){let r=t.trim();r&&(e.persistence?.enabled!==!1&&this.persist(e,r),(e.writeStrategy??"replaceState")==="replaceState"&&h()&&this.writeToUrl({[e.param]:r}))}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",n=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,s=i?.name?.trim()||e.param;(r==="storage"||r==="localStorage_cookie")&&this.store.setStorage(n,t),(r==="cookie"||r==="localStorage_cookie")&&i?.enabled!==!1&&this.store.setCookie({name:s,value:t,path:i?.path??"/",domain:i?.domain??"auto",sameSite:i?.sameSite??"Lax",secure:i?.secure??!0,maxAgeMs:i?.maxAgeMs})}writeToUrl(e){let r={...E(window.location.search),...e},n=Z(r),i=window.location.hash??"",s=window.location.pathname+n+i;_e(s)}};var te=class{resolve(e){let{queryParams:t,managedValues:r,config:n}=e;if(!n||n.enabled===!1)return{};let i=Y(n.denylist,n.mergeDefaultDenylist),s=n.mode??"all_except",a=new Set((n.allowlist??[]).map(I).filter(Boolean)),c={};for(let[l,d]of Object.entries(t))d&&(fe(l,i)||l in r||s==="allowlist"&&!a.has(I(l))||(c[l]=d));return c}};var Tt=["mailto:","tel:","javascript:","data:","blob:"],w=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;if(Lt(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=ke(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=Ae(e.config.excludeSelectors,e.config.mergeDefaultExcludeSelectors,e.includeSidExclude===!0);return}let n=e,i=t;this.forwardedParams=Object.freeze({}),this.managedParams=Object.freeze({...n}),this.config=i,this.excludedDomains=ke(i.excludedDomains,i.mergeDefaultExcludedDomains),this.excludeSelectors=Ae(i.excludeSelectors,i.mergeDefaultExcludeSelectors,r===!0)}updateManagedParams(e){if(this.managedParams=Object.freeze({...e}),!this.started||!h()||this.config.enabled===!1)return;let t=this.config.strategy??"on_click";(t==="on_init"||t==="both")&&this.decorateMatchingLinks()}start(){if(this.started||!h()||this.config.enabled===!1||Object.keys(this.forwardedParams).length===0&&Object.keys(this.managedParams).length===0)return;this.started=!0;let e=this.config.strategy??"on_click";(e==="on_init"||e==="both")&&this.decorateMatchingLinks(),(e==="on_click"||e==="both")&&(this.clickHandler=t=>{let r=Mt(t.target);r&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))},document.addEventListener("click",this.clickHandler,!0))}destroy(){this.started&&(this.clickHandler&&typeof document<"u"&&document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null,this.started=!1)}decorateHref(e,t){if(!e||e.trim()==="")return null;let r=e.trim(),n=r.toLowerCase();for(let m of Tt)if(n.startsWith(m))return m==="mailto:"&&this.config.decorateMailto===!0||m==="tel:"&&this.config.decorateTel===!0,null;if(r.startsWith("#")&&this.config.decorateHashLinks!==!0)return null;let i;try{let m=h()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!we(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=E(i.search),a=this.config.preserveExisting!==!1,c=this.config.overwriteExisting===!0,l={...s},d=!1;for(let[m,p]of Object.entries(this.forwardedParams))m in l&&a&&!c||(l[m]!==p&&(d=!0),l[m]=p);for(let[m,p]of Object.entries(this.managedParams))l[m]!==p&&(d=!0),l[m]=p;let g=E(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),f=Ut(r)>Object.keys(g).length;if(!d&&!f)return r;let y=Z(l);return i.search=y.startsWith("?")?y.slice(1):y,De(r,i)}decorateMatchingLinks(){let e=this.config.selector??"a[href]",t;try{t=document.querySelectorAll(e)}catch{return}for(let r of t)r instanceof HTMLAnchorElement&&(this.isExcludedAnchor(r)||this.decorateAnchor(r))}isExcludedAnchor(e){if(e.hasAttribute("download"))return!0;for(let t of this.excludeSelectors)try{if(e.matches(t))return!0}catch{}return!1}decorateAnchor(e){let t=e.getAttribute("href");if(!t)return;let r=this.decorateHref(t);r!=null&&r!==t&&e.setAttribute("href",r)}};function Lt(o){return typeof o=="object"&&o!==null&&"config"in o&&typeof o.config=="object"&&o.config!==null}function Mt(o){return o instanceof Element?o.closest("a[href]"):null}function Ut(o){let e=o.indexOf("?");if(e<0)return 0;let t=o.indexOf("#",e),r=t>=0?o.slice(e+1,t):o.slice(e+1);return r?r.split("&").filter(Boolean).length:0}var re=class{constructor(e){this.storage=e??null}getStorage(e){if(!this.storage)return null;try{let t=this.storage.get(e);return typeof t=="string"&&t.length>0?t:null}catch{return null}}setStorage(e,t){if(this.storage)try{this.storage.set(e,t)}catch{}}getCookie(e){if(!h())return null;try{let t=document.cookie?document.cookie.split(";"):[];for(let r of t){let n=r.indexOf("=");if((n>=0?r.slice(0,n):r).trim()!==e)continue;let s=n>=0?r.slice(n+1).trim():"";return Q(s)}}catch{return null}return null}setCookie(e){if(!h())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=Ft(e.domain);r&&t.push(`domain=${r}`),typeof e.maxAgeMs=="number"&&Number.isFinite(e.maxAgeMs)&&t.push(`max-age=${Math.max(0,Math.floor(e.maxAgeMs/1e3))}`);let n=e.sameSite??"Lax";t.push(`SameSite=${n}`),(e.secure===!0||typeof location<"u"&&location.protocol==="https:")&&t.push("Secure");try{document.cookie=t.join("; ")}catch{}}};function Ft(o){if(!o||o==="auto"){if(!h())return null;let e=location.hostname;return e==="localhost"||e==="127.0.0.1"||/^\d+\.\d+\.\d+\.\d+$/.test(e)||!e.includes(".")?null:e}return o}var je={key:"public_session",param:"sid",mode:"read_write",writeStrategy:"replaceState",generator:{type:"public_id",prefix:"sid"},persistence:{enabled:!0,strategy:"localStorage_cookie",storageKey:"sid",cookie:{enabled:!0,name:"sid",domain:"auto",path:"/",sameSite:"Lax",secure:!0,maxAgeMs:2592e6}},decorateLinks:!0},Ot={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Bt={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},qt={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function pe(o){if(!o||o.enabled!==!0)return{enabled:!1,queryParams:{enabled:!1},managedParams:[],forwardParams:{enabled:!1},linkDecoration:{enabled:!1}};let e=o.managedParams!==void 0?o.managedParams.map($e):[$e(je)];return{enabled:!0,queryParams:{...Ot,...o.queryParams,...o.queryParams?.allowlist?{allowlist:[...o.queryParams.allowlist]}:{},...o.queryParams?.denylist?{denylist:[...o.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Bt,...o.forwardParams,...o.forwardParams?.allowlist?{allowlist:[...o.forwardParams.allowlist]}:{},...o.forwardParams?.denylist?{denylist:[...o.forwardParams.denylist]}:{}},linkDecoration:{...qt,...o.linkDecoration,...o.linkDecoration?.allowedDomains&&o.linkDecoration.allowedDomains!=="*"?{allowedDomains:[...o.linkDecoration.allowedDomains]}:{},...o.linkDecoration?.excludedDomains?{excludedDomains:[...o.linkDecoration.excludedDomains]}:{},...o.linkDecoration?.excludeSelectors?{excludeSelectors:[...o.linkDecoration.excludeSelectors]}:{}}}}function $e(o){return{...o,...o.generator?{generator:{...o.generator}}:{},...o.persistence?{persistence:{...o.persistence,...o.persistence.cookie?{cookie:{...o.persistence.cookie}}:{}}}:{}}}var R=class{constructor(e,t){this.collector=new J;this.forwardResolver=new te;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Te();this.managedConfigs=[];this.decorateManaged={};this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=pe(this.rawConfig);if(this.enabled=e.enabled,this.managedConfigs=e.managedParams,!e.enabled){this.snapshot=Te();return}this.store=new re(this.storage),this.managedResolver=new ee(this.store);let t=this.collector.collect(e.queryParams),r=this.managedResolver.resolve(e.managedParams),n=Object.keys(r.values).length>0?this.collector.collect(e.queryParams):t,i=this.forwardResolver.resolve({queryParams:n,managedValues:r.values,config:e.forwardParams}),s={...r.sources};for(let d of Object.keys(i))s[d]||(s[d]="url");let a={...Object.keys(r.values).length>0?{managed:C(r.values)}:{},...Object.keys(i).length>0?{forwarded:C(i)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:C(n),urlContext:Object.freeze(a)};let c=C(i);this.decorateManaged={...r.decorateParams};let l=e.managedParams.some(d=>d.param==="sid"&&d.decorateLinks!==!1);this.decorator=new w({forwardedParams:c,managedParams:C(this.decorateManaged),config:e.linkDecoration,includeSidExclude:l}),this.decorator.start()}setManagedParam(e,t){if(!this.initialized||!this.enabled||!this.managedResolver)return!1;let r=e.trim(),n=t.trim();if(!r||!n)return!1;let i=this.managedConfigs.find(g=>g.param===r);if(!i)return!1;if(this.snapshot.urlContext.managed?.[r]===n)return!0;this.managedResolver.applyExternalValue(i,n);let a={...this.snapshot.urlContext.managed??{},[r]:n},c={...this.snapshot.urlContext.source??{},[r]:"manual"},l=pe(this.rawConfig),d=this.collector.collect(l.queryParams);if(this.snapshot={queryParams:C(d),urlContext:Object.freeze({managed:C(a),...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},source:Object.freeze({...c})})},i.decorateLinks!==!1&&(this.decorateManaged={...this.decorateManaged,[r]:n},this.decorator?.updateManagedParams(this.decorateManaged),!this.decorator&&l.enabled)){let g=this.managedConfigs.some(f=>f.param==="sid"&&f.decorateLinks!==!1);this.decorator=new w({forwardedParams:C(this.snapshot.urlContext.forwarded??{}),managedParams:C(this.decorateManaged),config:l.linkDecoration,includeSidExclude:g}),this.decorator.start()}return!0}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.managedConfigs=[],this.decorateManaged={},this.initialized=!1,this.enabled=!1,this.snapshot=Te()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:C(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:C(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:C(this.snapshot.urlContext.forwarded)}:{},...this.snapshot.urlContext.source?{source:Object.freeze({...this.snapshot.urlContext.source})}:{}}}}getQueryParams(){return{...this.snapshot.queryParams}}getUrlContext(){return this.getSnapshot().urlContext}};function Te(){return{queryParams:C({}),urlContext:Object.freeze({})}}var Le=class{constructor(e){this.initialized=!1;this.customerObserver=null;this.initializedModules=[];this.context=null;this.config=e,this.registry=new _,this.fallbackLogger=new F(e.app.debug===!0)}register(e){this.registry.register(e)}async init(){if(this.initialized){this.getLogger().debug("[PixelRuntime] Runtime already initialized");return}this.fallbackLogger.debug("[PixelRuntime] Initializing runtime"),this.context=this.createContext(),this.context.services.attribution.init(),this.startCustomerObserver();for(let e of this.registry.getAll()){if(!this.isModuleEnabled(e)){this.fallbackLogger.debug(`[PixelRuntime] Skipping disabled module: ${e.name}`);continue}this.fallbackLogger.debug(`[PixelRuntime] Initializing module: ${e.name}`);try{await e.init(this.context),this.initializedModules.push(e)}catch(t){this.fallbackLogger.error(`[Pixel] Failed to initialize module "${e.name}"`,t)}}this.initialized=!0}async destroy(){if(!this.initialized)return;let e=this.getLogger();for(let t=this.initializedModules.length-1;t>=0;t--){let r=this.initializedModules[t];e.debug(`[PixelRuntime] Destroying module: ${r.name}`);try{await r.destroy?.()}catch(n){e.error(`[Pixel] Failed to destroy module "${r.name}"`,n)}}this.customerObserver?.destroy(),this.customerObserver=null,this.context?.services.customerIdentity?.clear(),this.context?.services.attribution.destroy(),this.context?.services.dispatcher.clear(),this.initialized=!1,this.initializedModules.length=0,this.context=null,this.fallbackLogger.debug("[PixelRuntime] Runtime destroyed")}isInitialized(){return this.initialized}getDebugServices(){return this.context?.services??null}getInitializedModuleNames(){return this.initializedModules.map(e=>e.name)}getRegisteredModuleNames(){return this.registry.getAll().map(e=>e.name)}createServices(e){let{namespace:t,prefix:r,persistence:n}=this.config.storage,i=this.createStorageService(t,r,n?.visitor),s=this.createStorageService(t,r,n?.session),a=this.createStorageService(t,r,n?.attribution),c=this.createStorageService(t,r,n?.attribution??"localStorage"),l=this.createStorageService(t,r,"memory"),d=new se,g=new z(c,this.config.attribution??N),f=this.createStorageService(t,r,n?.attribution??"localStorage"),y=new R(this.config.modules.core.urlContext,f),m=new T,p=new U(d,g,y,m),x=new me(i,this.config),S=new de(s,this.config),ne=new ce(a,this.config,d),oe=new ae(e),He=new G(this.config.commerce);return{storage:l,visitor:x,session:S,fingerprint:ne,dispatcher:oe,browserMetadata:d,eventBuilder:p,attribution:g,commerce:He,urlContext:y,customerIdentity:m}}startCustomerObserver(){let e=this.context?.services.customerIdentity;e&&(this.customerObserver=new M(e,new A({fieldMappings:qe(this.config.commerce.customer,this.config.commerce.mappings?.fields)})),this.customerObserver.start())}createStorageService(e,t,r){return new V(xe(r),e,t)}createContext(){return{config:this.config,logger:this.fallbackLogger,services:this.createServices(this.fallbackLogger)}}getLogger(){return this.context?.logger??this.fallbackLogger}isModuleEnabled(e){return e.name==="diagnostics"?!0:{privacy:this.config.modules.privacy.enabled,core:this.config.modules.core.enabled,behavior:this.config.modules.behavior.enabled,conversion:this.config.modules.conversion.enabled,transport:this.config.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};export{_ as ModuleRegistry,Le as PixelRuntime};
3
3
  //# sourceMappingURL=index.esm.js.map