@beworke/pixel 0.1.0-rc.5 → 0.1.0-rc.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +38 -69
- package/RELEASE_CANDIDATE.md +19 -13
- package/dist/{StorageFactory-CPghDPBj.d.mts → StorageFactory-Cq29vF32.d.mts} +2 -2
- package/dist/{StorageFactory-tjfzk57c.d.ts → StorageFactory-DeMaZ8wk.d.ts} +2 -2
- package/dist/config/index.cjs.js +1 -1
- package/dist/config/index.cjs.js.map +1 -1
- package/dist/config/index.d.mts +4 -4
- package/dist/config/index.d.ts +4 -4
- package/dist/config/index.esm.js +1 -1
- package/dist/config/index.esm.js.map +1 -1
- package/dist/events/index.cjs.js.map +1 -1
- package/dist/events/index.d.mts +2 -2
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.esm.js.map +1 -1
- package/dist/examples/html-script/README.md +20 -76
- package/dist/examples/html-script/RELEASE_CANDIDATE.md +14 -13
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-autocomplete.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-disabled.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-card-fields.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-data-track.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-dedupe.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-manual.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-rules-card.html +1 -1
- package/dist/examples/html-script/add-payment-info/example-add-payment-info-security.html +1 -1
- package/dist/examples/html-script/add-to-cart/README.md +6 -3
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-attribute.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-auto.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-click.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-dedupe.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-link.html +597 -0
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-manual.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-order-bump.html +3 -2
- package/dist/examples/html-script/add-to-cart/example-add-to-cart-text.html +3 -2
- package/dist/examples/html-script/behavior/example-behavior-engagement.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-heartbeat.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-runtime-intelligence.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior-viewport.html +1 -1
- package/dist/examples/html-script/behavior/example-behavior.html +1 -1
- package/dist/examples/html-script/example-basic.html +1 -1
- package/dist/examples/html-script/example-checkout-commerce.html +1 -1
- package/dist/examples/html-script/example-conversion.html +1 -1
- package/dist/examples/html-script/example-integration.html +1 -1
- package/dist/examples/html-script/example-landing-commerce.html +42 -1
- package/dist/examples/html-script/example-runtime-diagnostics.html +1 -1
- package/dist/examples/html-script/example-transport.html +6 -1
- package/dist/examples/html-script/full-funnel/README.md +1 -1
- package/dist/examples/html-script/full-funnel/checkout.html +1 -1
- package/dist/examples/html-script/full-funnel/downsell.html +1 -1
- package/dist/examples/html-script/full-funnel/landing.html +54 -2
- package/dist/examples/html-script/full-funnel/thank-you.html +1 -1
- package/dist/examples/html-script/full-funnel/upsell.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-attribute.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-auto.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-click.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-manual.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-snapshot.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-submit.html +1 -1
- package/dist/examples/html-script/initiate-checkout/example-initiate-checkout-text.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-attribute.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-auto.html +1 -1
- package/dist/examples/html-script/lead/example-lead-trigger-click.html +1 -1
- package/dist/examples/html-script/release-candidate.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-attribute.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-css.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-dedupe.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-manual.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-multi.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-state.html +1 -1
- package/dist/examples/html-script/remove-from-cart/example-remove-from-cart-text.html +1 -1
- package/dist/examples/html-script/search/example-search-attribute.html +1 -1
- package/dist/examples/html-script/search/example-search-button-sync.html +1 -1
- package/dist/examples/html-script/search/example-search-dedupe.html +1 -1
- package/dist/examples/html-script/search/example-search-input.html +1 -1
- package/dist/examples/html-script/search/example-search-manual.html +1 -1
- package/dist/examples/html-script/search/example-search-submit.html +1 -1
- package/dist/examples/html-script/search/example-search-text.html +1 -1
- package/dist/examples/html-script/url-context/example-url-context-allowed-domains.html +38 -9
- package/dist/examples/html-script/url-context/example-url-context-landing.html +53 -13
- package/dist/examples/html-script/url-context/example-url-context-upsell.html +48 -10
- package/dist/examples/html-script/url-context/example-url-context.html +51 -17
- package/dist/examples/html-script/view-content/example-view-content-attribute.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-css.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-dedupe.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-empty.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-manual.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-product-card.html +1 -1
- package/dist/examples/html-script/view-content/example-view-content-text.html +1 -1
- package/dist/examples/release-candidate/README.md +2 -1
- package/dist/examples/v2/README.md +15 -15
- package/dist/{index-CQAyT5Od.d.ts → index-B8u_3PGG.d.ts} +21 -2
- package/dist/{index-JlKPz4pp.d.mts → index-BxT2d-TK.d.mts} +21 -2
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.mts +19 -782
- package/dist/index.d.ts +19 -782
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/{pixel-BxZZx8l5.d.ts → pixel-2uL4LSyC.d.ts} +126 -5
- package/dist/{pixel-CKc4OQUx.d.mts → pixel-DMwpppf_.d.mts} +126 -5
- package/dist/{pixel-default-config-aAOujzwp.d.ts → pixel-default-config-BDPUVHse.d.ts} +1 -1
- package/dist/{pixel-default-config-CJl-eypl.d.mts → pixel-default-config-C5uLt52W.d.mts} +1 -1
- package/dist/runtime/index.cjs.js +1 -1
- package/dist/runtime/index.cjs.js.map +1 -1
- package/dist/runtime/index.d.mts +6 -6
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.esm.js +1 -1
- package/dist/runtime/index.esm.js.map +1 -1
- package/dist/services/index.cjs.js +1 -1
- package/dist/services/index.cjs.js.map +1 -1
- package/dist/services/index.d.mts +7 -7
- package/dist/services/index.d.ts +7 -7
- package/dist/services/index.esm.js +1 -1
- package/dist/services/index.esm.js.map +1 -1
- package/dist/{types-BP8dz1gP.d.mts → types-6HF3UlsL.d.mts} +2 -2
- package/dist/{types-C75pQP31.d.ts → types-BqUEoZo0.d.ts} +2 -2
- package/dist/{types-DMhzHSVC.d.mts → types-CgrabttM.d.mts} +2 -2
- package/dist/{types-D_SsCur9.d.ts → types-fFcQ1apy.d.ts} +2 -2
- package/dist/{url-context-BjAsQoVl.d.mts → url-context-Ck2LK18V.d.mts} +4 -2
- package/dist/{url-context-BjAsQoVl.d.ts → url-context-Ck2LK18V.d.ts} +4 -2
- package/dist/v2/global.global.js +1 -1
- package/dist/v2/global.global.js.map +1 -1
- package/dist/v2/index.cjs.js +1 -1
- package/dist/v2/index.cjs.js.map +1 -1
- package/dist/v2/index.d.mts +793 -9
- package/dist/v2/index.d.ts +793 -9
- package/dist/v2/index.esm.js +1 -1
- package/dist/v2/index.esm.js.map +1 -1
- package/docs/public/README.md +77 -0
- package/docs/public/api/exports.md +47 -0
- package/docs/public/api/pixel.md +65 -0
- package/docs/public/configuration/commerce.md +44 -0
- package/docs/public/configuration/modules.md +66 -0
- package/docs/public/configuration/overview.md +66 -0
- package/docs/public/events/catalog.md +65 -0
- package/docs/public/getting-started/installation.md +78 -0
- package/docs/public/getting-started/quick-start.md +77 -0
- package/docs/public/getting-started/react-nextjs.md +55 -0
- package/docs/public/getting-started/script-tag.md +57 -0
- package/docs/public/guides/funnel-checkout.md +52 -0
- package/docs/public/guides/funnel-downsell.md +53 -0
- package/docs/public/guides/funnel-full.md +64 -0
- package/docs/public/guides/funnel-landing.md +68 -0
- package/docs/public/guides/funnel-thank-you.md +48 -0
- package/docs/public/guides/funnel-upsell.md +72 -0
- package/docs/public/limitations.md +32 -0
- package/docs/public/privacy/limitations.md +33 -0
- package/docs/public/release-candidate/validation.md +42 -0
- package/docs/public/troubleshooting.md +55 -0
- package/package.json +10 -13
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as UrlContextConfig } from './url-context-
|
|
1
|
+
import { U as UrlContextConfig } from './url-context-Ck2LK18V.js';
|
|
2
2
|
|
|
3
3
|
type MetaBrowserDestinationConfig = {
|
|
4
4
|
enabled: boolean;
|
|
@@ -186,12 +186,16 @@ type SelectorFormConfig = string[] | {
|
|
|
186
186
|
};
|
|
187
187
|
|
|
188
188
|
/**
|
|
189
|
-
* Contrato de fontes independentes para auto detectors (Etapa 14).
|
|
189
|
+
* Contrato de fontes independentes para auto detectors (Etapa 14+).
|
|
190
190
|
* Um evento automático pode ter várias sources; cada uma vira um detector.
|
|
191
|
+
*
|
|
192
|
+
* A source `url` observa a URL da página (`window.location`) / rotas.
|
|
193
|
+
* A source `link` observa o destino de um `<a href>` clicado.
|
|
191
194
|
*/
|
|
192
195
|
|
|
193
|
-
type AutoSourceType = 'selector' | 'form' | 'payment' | 'lifecycle' | 'url';
|
|
196
|
+
type AutoSourceType = 'selector' | 'form' | 'payment' | 'lifecycle' | 'url' | 'link';
|
|
194
197
|
type AutoSourceBase = {
|
|
198
|
+
/** Nome estável da source (obrigatório). */
|
|
195
199
|
name: string;
|
|
196
200
|
type: AutoSourceType;
|
|
197
201
|
enabled?: boolean;
|
|
@@ -223,11 +227,128 @@ type LifecycleAutoSource = AutoSourceBase & {
|
|
|
223
227
|
type: 'lifecycle';
|
|
224
228
|
trigger: 'init' | 'ready';
|
|
225
229
|
};
|
|
230
|
+
/**
|
|
231
|
+
* Observa a URL da página atual (location / history).
|
|
232
|
+
* Não confundir com `LinkAutoSource` (destino de um clique em âncora).
|
|
233
|
+
*/
|
|
226
234
|
type UrlAutoSource = AutoSourceBase & {
|
|
227
235
|
type: 'url';
|
|
228
236
|
patterns: string[];
|
|
229
237
|
};
|
|
230
|
-
|
|
238
|
+
/** Protocols HTTP suportados pelo matcher de links. */
|
|
239
|
+
type LinkMatchProtocol = 'http:' | 'https:';
|
|
240
|
+
/**
|
|
241
|
+
* Condição de query string para match de destino.
|
|
242
|
+
* Sem regex arbitrária / callbacks.
|
|
243
|
+
*/
|
|
244
|
+
type LinkQueryCondition = {
|
|
245
|
+
key: string;
|
|
246
|
+
operator: 'exists' | 'absent';
|
|
247
|
+
} | {
|
|
248
|
+
key: string;
|
|
249
|
+
operator: 'equals' | 'starts_with';
|
|
250
|
+
value: string;
|
|
251
|
+
caseSensitive?: boolean;
|
|
252
|
+
} | {
|
|
253
|
+
key: string;
|
|
254
|
+
operator: 'one_of';
|
|
255
|
+
value: string[];
|
|
256
|
+
caseSensitive?: boolean;
|
|
257
|
+
};
|
|
258
|
+
type LinkQueryMatch = {
|
|
259
|
+
/** Default: `all`. */
|
|
260
|
+
mode?: 'all' | 'any';
|
|
261
|
+
conditions: LinkQueryCondition[];
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Regras para reconhecer o destino do link (AND entre grupos configurados).
|
|
265
|
+
* Arrays dentro de um grupo usam OR.
|
|
266
|
+
*/
|
|
267
|
+
type LinkTargetMatch = {
|
|
268
|
+
protocols?: LinkMatchProtocol[];
|
|
269
|
+
/** Origins absolutas normalizadas (sem `/` final), ex.: `https://checkout.example.com`. */
|
|
270
|
+
origins?: string[];
|
|
271
|
+
/** Hostnames em lowercase, ex.: `checkout.example.com`. */
|
|
272
|
+
hostnames?: string[];
|
|
273
|
+
path?: {
|
|
274
|
+
exact?: string[];
|
|
275
|
+
prefixes?: string[];
|
|
276
|
+
/**
|
|
277
|
+
* Prefixo de **segmento** do path (não do pathname inteiro).
|
|
278
|
+
* Ex.: `pri` casa `/pri6670988`, `/pri_123` e `/examples/security/pri6670988.html`,
|
|
279
|
+
* mas não `/privacy` (próximo char precisa ser dígito ou `_`+dígito).
|
|
280
|
+
*/
|
|
281
|
+
segmentPrefixes?: string[];
|
|
282
|
+
/**
|
|
283
|
+
* Template simples: `/pay/:offerId`.
|
|
284
|
+
* `:param` captura um segmento; literais devem casar exatamente.
|
|
285
|
+
*/
|
|
286
|
+
template?: string;
|
|
287
|
+
};
|
|
288
|
+
query?: LinkQueryMatch;
|
|
289
|
+
};
|
|
290
|
+
/**
|
|
291
|
+
* Origem de um valor resolvido a partir do link / elemento.
|
|
292
|
+
*/
|
|
293
|
+
type LinkValueResolver = {
|
|
294
|
+
source: 'query';
|
|
295
|
+
key: string;
|
|
296
|
+
} | {
|
|
297
|
+
source: 'pathParam';
|
|
298
|
+
key: string;
|
|
299
|
+
} | {
|
|
300
|
+
source: 'pathSegment';
|
|
301
|
+
/**
|
|
302
|
+
* Índice do segmento (0 = primeiro).
|
|
303
|
+
* Índice negativo conta do fim (`-1` = último segmento).
|
|
304
|
+
*/
|
|
305
|
+
index: number;
|
|
306
|
+
} | {
|
|
307
|
+
source: 'attribute';
|
|
308
|
+
name: string;
|
|
309
|
+
} | {
|
|
310
|
+
source: 'dataset';
|
|
311
|
+
/** Chave camelCase do `dataset` (`data-product-id` → `productId`). */
|
|
312
|
+
key: string;
|
|
313
|
+
} | {
|
|
314
|
+
source: 'static';
|
|
315
|
+
value: string | number | boolean | null;
|
|
316
|
+
} | {
|
|
317
|
+
source: 'href' | 'origin' | 'hostname' | 'pathname' | 'text';
|
|
318
|
+
};
|
|
319
|
+
type LinkValueTransform = 'trim' | 'lowercase' | 'uppercase' | 'number';
|
|
320
|
+
type LinkValueBinding = {
|
|
321
|
+
from: LinkValueResolver | LinkValueResolver[];
|
|
322
|
+
required?: boolean;
|
|
323
|
+
transform?: LinkValueTransform;
|
|
324
|
+
};
|
|
325
|
+
/**
|
|
326
|
+
* Source automática baseada no destino de um link clicado.
|
|
327
|
+
*
|
|
328
|
+
* `match` decide se o destino corresponde.
|
|
329
|
+
* `bindings` resolve valores genéricos (incluindo chaves semânticas
|
|
330
|
+
* como `productId` reconhecidas pelo mapper do evento).
|
|
331
|
+
*/
|
|
332
|
+
type LinkAutoSource = AutoSourceBase & {
|
|
333
|
+
type: 'link';
|
|
334
|
+
/** Somente click nesta etapa. Default: `click`. */
|
|
335
|
+
trigger?: 'click';
|
|
336
|
+
/**
|
|
337
|
+
* Restrição opcional sobre o elemento.
|
|
338
|
+
* Sem selector, usa o `<a href>` ancestral mais próximo do clique.
|
|
339
|
+
*/
|
|
340
|
+
selector?: SelectorConfig;
|
|
341
|
+
selectorType?: SelectorType;
|
|
342
|
+
/** Regras de reconhecimento do destino. */
|
|
343
|
+
match: LinkTargetMatch;
|
|
344
|
+
/**
|
|
345
|
+
* Valores extraídos do link / elemento / configuração.
|
|
346
|
+
* Chaves são genéricas; o mapper do evento reconhece semântica
|
|
347
|
+
* opcional (`productId`, `query`, etc.).
|
|
348
|
+
*/
|
|
349
|
+
bindings?: Record<string, LinkValueBinding>;
|
|
350
|
+
};
|
|
351
|
+
type AutoTrackSource = SelectorAutoSource | FormAutoSource | PaymentAutoSource | LifecycleAutoSource | UrlAutoSource | LinkAutoSource;
|
|
231
352
|
|
|
232
353
|
/**
|
|
233
354
|
* Contratos globais de commerce (root `PixelConfig.commerce`).
|
|
@@ -728,4 +849,4 @@ type PixelConfig = {
|
|
|
728
849
|
modules: ModulesConfig;
|
|
729
850
|
};
|
|
730
851
|
|
|
731
|
-
export {
|
|
852
|
+
export { type CommerceEnrichmentSource as $, type AttributionStoragePersistence as A, type BehaviorModuleConfig as B, type ConversionModuleConfig as C, type PaymentMethod as D, type EngagementThresholds as E, type FingerprintMode as F, type SelectorAutoSource as G, type SelectorConfig as H, type IntegrationsModuleConfig as I, type SelectorDescriptor as J, type SelectorInput as K, type LifecycleAutoSource as L, type SelectorType as M, type SelectorFormConfig as N, type SelectorFormMode as O, type PixelConfig as P, type QueueStoragePersistence as Q, type SelectorFormTrigger as R, type SessionStoragePersistence as S, type TransportModuleConfig as T, type CommerceCalculateValueFrom as U, type VisitorStoragePersistence as V, type CommerceCartConfig as W, type CommerceCartItem as X, type CommerceCartMode as Y, type CommerceConfig as Z, type CommerceEnrichmentConfig as _, type AttributionConfig as a, type CommerceEventEnrichmentConfig as a0, type CommerceMappingsConfig as a1, type CommerceProduct as a2, type ProductCatalogConfig as a3, type ProductType as a4, type UrlAutoSource as a5, DEFAULT_SELECTOR_TYPE as a6, DEFAULT_COMMERCE_CONFIG as a7, DEFAULT_COMMERCE_ENRICHMENT as a8, getPrimarySelectorValue as a9, type MetaIntegrationConfig as aA, type ModulesConfig as aB, type TikTokBrowserDestinationConfig as aC, type OrderingConfig as aD, type PageViewConfig as aE, type PiiConfig as aF, type PrivacyConsentConfig as aG, type PurchaseAutoDetectorConfig as aH, type RemoveFromCartAutoDetectorConfig as aI, type ScrollBehaviorConfig as aJ, type SearchAutoDetectorConfig as aK, type SessionConfig as aL, type TransportBatchConfig as aM, type TransportFlushConfig as aN, type TransportOfflineConfig as aO, type TransportRetryConfig as aP, type TransportTimeoutConfig as aQ, type ViewContentAutoDetectorConfig as aR, type ViewportBehaviorConfig as aS, type ViewportTargetConfig as aT, type VisibilityBehaviorConfig as aU, type VisitorConfig as aV, normalizeCalculateValueFrom as aa, resolveSelectorTypeFallback as ab, type AddPaymentInfoAutoDetectorConfig as ac, type AddToCartAutoDetectorConfig as ad, type AnonymizationConfig as ae, type AutoConversionConfig as af, type AutoDetectorConfig as ag, type ClickBehaviorConfig as ah, type ConsentConfig as ai, type ConversionAutoDetectorsConfig as aj, type ConversionRulesConfig as ak, type CoordinationConfig as al, type DedupeConfig as am, type EngagementBehaviorConfig as an, type ExitIntentBehaviorConfig as ao, type FingerprintConfig as ap, type GoogleBrowserDestinationConfig as aq, type GoogleIntegrationConfig as ar, type HeartbeatModuleConfig as as, type IdleBehaviorConfig as at, type InitiateCheckoutAutoDetectorConfig as au, type IntegrationTestDestinationConfig as av, type LeadAutoDetectorConfig as aw, type ManualConversionConfig as ax, type ManualEventConfig as ay, type MetaBrowserDestinationConfig as az, type CoreModuleConfig as b, type PrivacyModuleConfig as c, type AppConfig as d, type PixelEnvironment as e, type PixelSource as f, type PixelTarget as g, type IdentityConfig as h, type TransportConfig as i, type StorageConfig as j, type StorageKeysConfig as k, type AutoSourceBase as l, type AutoSourceType as m, type AutoTrackSource as n, type EngagementWeights as o, type EngagementPenalties as p, type FormAutoSource as q, type LinkAutoSource as r, type LinkMatchProtocol as s, type LinkQueryCondition as t, type LinkQueryMatch as u, type LinkTargetMatch as v, type LinkValueBinding as w, type LinkValueResolver as x, type LinkValueTransform as y, type PaymentAutoSource as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as UrlContextConfig } from './url-context-
|
|
1
|
+
import { U as UrlContextConfig } from './url-context-Ck2LK18V.mjs';
|
|
2
2
|
|
|
3
3
|
type MetaBrowserDestinationConfig = {
|
|
4
4
|
enabled: boolean;
|
|
@@ -186,12 +186,16 @@ type SelectorFormConfig = string[] | {
|
|
|
186
186
|
};
|
|
187
187
|
|
|
188
188
|
/**
|
|
189
|
-
* Contrato de fontes independentes para auto detectors (Etapa 14).
|
|
189
|
+
* Contrato de fontes independentes para auto detectors (Etapa 14+).
|
|
190
190
|
* Um evento automático pode ter várias sources; cada uma vira um detector.
|
|
191
|
+
*
|
|
192
|
+
* A source `url` observa a URL da página (`window.location`) / rotas.
|
|
193
|
+
* A source `link` observa o destino de um `<a href>` clicado.
|
|
191
194
|
*/
|
|
192
195
|
|
|
193
|
-
type AutoSourceType = 'selector' | 'form' | 'payment' | 'lifecycle' | 'url';
|
|
196
|
+
type AutoSourceType = 'selector' | 'form' | 'payment' | 'lifecycle' | 'url' | 'link';
|
|
194
197
|
type AutoSourceBase = {
|
|
198
|
+
/** Nome estável da source (obrigatório). */
|
|
195
199
|
name: string;
|
|
196
200
|
type: AutoSourceType;
|
|
197
201
|
enabled?: boolean;
|
|
@@ -223,11 +227,128 @@ type LifecycleAutoSource = AutoSourceBase & {
|
|
|
223
227
|
type: 'lifecycle';
|
|
224
228
|
trigger: 'init' | 'ready';
|
|
225
229
|
};
|
|
230
|
+
/**
|
|
231
|
+
* Observa a URL da página atual (location / history).
|
|
232
|
+
* Não confundir com `LinkAutoSource` (destino de um clique em âncora).
|
|
233
|
+
*/
|
|
226
234
|
type UrlAutoSource = AutoSourceBase & {
|
|
227
235
|
type: 'url';
|
|
228
236
|
patterns: string[];
|
|
229
237
|
};
|
|
230
|
-
|
|
238
|
+
/** Protocols HTTP suportados pelo matcher de links. */
|
|
239
|
+
type LinkMatchProtocol = 'http:' | 'https:';
|
|
240
|
+
/**
|
|
241
|
+
* Condição de query string para match de destino.
|
|
242
|
+
* Sem regex arbitrária / callbacks.
|
|
243
|
+
*/
|
|
244
|
+
type LinkQueryCondition = {
|
|
245
|
+
key: string;
|
|
246
|
+
operator: 'exists' | 'absent';
|
|
247
|
+
} | {
|
|
248
|
+
key: string;
|
|
249
|
+
operator: 'equals' | 'starts_with';
|
|
250
|
+
value: string;
|
|
251
|
+
caseSensitive?: boolean;
|
|
252
|
+
} | {
|
|
253
|
+
key: string;
|
|
254
|
+
operator: 'one_of';
|
|
255
|
+
value: string[];
|
|
256
|
+
caseSensitive?: boolean;
|
|
257
|
+
};
|
|
258
|
+
type LinkQueryMatch = {
|
|
259
|
+
/** Default: `all`. */
|
|
260
|
+
mode?: 'all' | 'any';
|
|
261
|
+
conditions: LinkQueryCondition[];
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Regras para reconhecer o destino do link (AND entre grupos configurados).
|
|
265
|
+
* Arrays dentro de um grupo usam OR.
|
|
266
|
+
*/
|
|
267
|
+
type LinkTargetMatch = {
|
|
268
|
+
protocols?: LinkMatchProtocol[];
|
|
269
|
+
/** Origins absolutas normalizadas (sem `/` final), ex.: `https://checkout.example.com`. */
|
|
270
|
+
origins?: string[];
|
|
271
|
+
/** Hostnames em lowercase, ex.: `checkout.example.com`. */
|
|
272
|
+
hostnames?: string[];
|
|
273
|
+
path?: {
|
|
274
|
+
exact?: string[];
|
|
275
|
+
prefixes?: string[];
|
|
276
|
+
/**
|
|
277
|
+
* Prefixo de **segmento** do path (não do pathname inteiro).
|
|
278
|
+
* Ex.: `pri` casa `/pri6670988`, `/pri_123` e `/examples/security/pri6670988.html`,
|
|
279
|
+
* mas não `/privacy` (próximo char precisa ser dígito ou `_`+dígito).
|
|
280
|
+
*/
|
|
281
|
+
segmentPrefixes?: string[];
|
|
282
|
+
/**
|
|
283
|
+
* Template simples: `/pay/:offerId`.
|
|
284
|
+
* `:param` captura um segmento; literais devem casar exatamente.
|
|
285
|
+
*/
|
|
286
|
+
template?: string;
|
|
287
|
+
};
|
|
288
|
+
query?: LinkQueryMatch;
|
|
289
|
+
};
|
|
290
|
+
/**
|
|
291
|
+
* Origem de um valor resolvido a partir do link / elemento.
|
|
292
|
+
*/
|
|
293
|
+
type LinkValueResolver = {
|
|
294
|
+
source: 'query';
|
|
295
|
+
key: string;
|
|
296
|
+
} | {
|
|
297
|
+
source: 'pathParam';
|
|
298
|
+
key: string;
|
|
299
|
+
} | {
|
|
300
|
+
source: 'pathSegment';
|
|
301
|
+
/**
|
|
302
|
+
* Índice do segmento (0 = primeiro).
|
|
303
|
+
* Índice negativo conta do fim (`-1` = último segmento).
|
|
304
|
+
*/
|
|
305
|
+
index: number;
|
|
306
|
+
} | {
|
|
307
|
+
source: 'attribute';
|
|
308
|
+
name: string;
|
|
309
|
+
} | {
|
|
310
|
+
source: 'dataset';
|
|
311
|
+
/** Chave camelCase do `dataset` (`data-product-id` → `productId`). */
|
|
312
|
+
key: string;
|
|
313
|
+
} | {
|
|
314
|
+
source: 'static';
|
|
315
|
+
value: string | number | boolean | null;
|
|
316
|
+
} | {
|
|
317
|
+
source: 'href' | 'origin' | 'hostname' | 'pathname' | 'text';
|
|
318
|
+
};
|
|
319
|
+
type LinkValueTransform = 'trim' | 'lowercase' | 'uppercase' | 'number';
|
|
320
|
+
type LinkValueBinding = {
|
|
321
|
+
from: LinkValueResolver | LinkValueResolver[];
|
|
322
|
+
required?: boolean;
|
|
323
|
+
transform?: LinkValueTransform;
|
|
324
|
+
};
|
|
325
|
+
/**
|
|
326
|
+
* Source automática baseada no destino de um link clicado.
|
|
327
|
+
*
|
|
328
|
+
* `match` decide se o destino corresponde.
|
|
329
|
+
* `bindings` resolve valores genéricos (incluindo chaves semânticas
|
|
330
|
+
* como `productId` reconhecidas pelo mapper do evento).
|
|
331
|
+
*/
|
|
332
|
+
type LinkAutoSource = AutoSourceBase & {
|
|
333
|
+
type: 'link';
|
|
334
|
+
/** Somente click nesta etapa. Default: `click`. */
|
|
335
|
+
trigger?: 'click';
|
|
336
|
+
/**
|
|
337
|
+
* Restrição opcional sobre o elemento.
|
|
338
|
+
* Sem selector, usa o `<a href>` ancestral mais próximo do clique.
|
|
339
|
+
*/
|
|
340
|
+
selector?: SelectorConfig;
|
|
341
|
+
selectorType?: SelectorType;
|
|
342
|
+
/** Regras de reconhecimento do destino. */
|
|
343
|
+
match: LinkTargetMatch;
|
|
344
|
+
/**
|
|
345
|
+
* Valores extraídos do link / elemento / configuração.
|
|
346
|
+
* Chaves são genéricas; o mapper do evento reconhece semântica
|
|
347
|
+
* opcional (`productId`, `query`, etc.).
|
|
348
|
+
*/
|
|
349
|
+
bindings?: Record<string, LinkValueBinding>;
|
|
350
|
+
};
|
|
351
|
+
type AutoTrackSource = SelectorAutoSource | FormAutoSource | PaymentAutoSource | LifecycleAutoSource | UrlAutoSource | LinkAutoSource;
|
|
231
352
|
|
|
232
353
|
/**
|
|
233
354
|
* Contratos globais de commerce (root `PixelConfig.commerce`).
|
|
@@ -728,4 +849,4 @@ type PixelConfig = {
|
|
|
728
849
|
modules: ModulesConfig;
|
|
729
850
|
};
|
|
730
851
|
|
|
731
|
-
export {
|
|
852
|
+
export { type CommerceEnrichmentSource as $, type AttributionStoragePersistence as A, type BehaviorModuleConfig as B, type ConversionModuleConfig as C, type PaymentMethod as D, type EngagementThresholds as E, type FingerprintMode as F, type SelectorAutoSource as G, type SelectorConfig as H, type IntegrationsModuleConfig as I, type SelectorDescriptor as J, type SelectorInput as K, type LifecycleAutoSource as L, type SelectorType as M, type SelectorFormConfig as N, type SelectorFormMode as O, type PixelConfig as P, type QueueStoragePersistence as Q, type SelectorFormTrigger as R, type SessionStoragePersistence as S, type TransportModuleConfig as T, type CommerceCalculateValueFrom as U, type VisitorStoragePersistence as V, type CommerceCartConfig as W, type CommerceCartItem as X, type CommerceCartMode as Y, type CommerceConfig as Z, type CommerceEnrichmentConfig as _, type AttributionConfig as a, type CommerceEventEnrichmentConfig as a0, type CommerceMappingsConfig as a1, type CommerceProduct as a2, type ProductCatalogConfig as a3, type ProductType as a4, type UrlAutoSource as a5, DEFAULT_SELECTOR_TYPE as a6, DEFAULT_COMMERCE_CONFIG as a7, DEFAULT_COMMERCE_ENRICHMENT as a8, getPrimarySelectorValue as a9, type MetaIntegrationConfig as aA, type ModulesConfig as aB, type TikTokBrowserDestinationConfig as aC, type OrderingConfig as aD, type PageViewConfig as aE, type PiiConfig as aF, type PrivacyConsentConfig as aG, type PurchaseAutoDetectorConfig as aH, type RemoveFromCartAutoDetectorConfig as aI, type ScrollBehaviorConfig as aJ, type SearchAutoDetectorConfig as aK, type SessionConfig as aL, type TransportBatchConfig as aM, type TransportFlushConfig as aN, type TransportOfflineConfig as aO, type TransportRetryConfig as aP, type TransportTimeoutConfig as aQ, type ViewContentAutoDetectorConfig as aR, type ViewportBehaviorConfig as aS, type ViewportTargetConfig as aT, type VisibilityBehaviorConfig as aU, type VisitorConfig as aV, normalizeCalculateValueFrom as aa, resolveSelectorTypeFallback as ab, type AddPaymentInfoAutoDetectorConfig as ac, type AddToCartAutoDetectorConfig as ad, type AnonymizationConfig as ae, type AutoConversionConfig as af, type AutoDetectorConfig as ag, type ClickBehaviorConfig as ah, type ConsentConfig as ai, type ConversionAutoDetectorsConfig as aj, type ConversionRulesConfig as ak, type CoordinationConfig as al, type DedupeConfig as am, type EngagementBehaviorConfig as an, type ExitIntentBehaviorConfig as ao, type FingerprintConfig as ap, type GoogleBrowserDestinationConfig as aq, type GoogleIntegrationConfig as ar, type HeartbeatModuleConfig as as, type IdleBehaviorConfig as at, type InitiateCheckoutAutoDetectorConfig as au, type IntegrationTestDestinationConfig as av, type LeadAutoDetectorConfig as aw, type ManualConversionConfig as ax, type ManualEventConfig as ay, type MetaBrowserDestinationConfig as az, type CoreModuleConfig as b, type PrivacyModuleConfig as c, type AppConfig as d, type PixelEnvironment as e, type PixelSource as f, type PixelTarget as g, type IdentityConfig as h, type TransportConfig as i, type StorageConfig as j, type StorageKeysConfig as k, type AutoSourceBase as l, type AutoSourceType as m, type AutoTrackSource as n, type EngagementWeights as o, type EngagementPenalties as p, type FormAutoSource as q, type LinkAutoSource as r, type LinkMatchProtocol as s, type LinkQueryCondition as t, type LinkQueryMatch as u, type LinkTargetMatch as v, type LinkValueBinding as w, type LinkValueResolver as x, type LinkValueTransform as y, type PaymentAutoSource as z };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Pixel v2 — SDK de analytics e conversão */
|
|
2
|
-
"use strict";var ae=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var De=(n,e)=>{for(var t in e)ae(n,t,{get:e[t],enumerable:!0})},Te=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!_e.call(n,o)&&o!==t&&ae(n,o,{get:()=>e[o],enumerable:!(r=Ae(e,o))||r.enumerable});return n};var Ue=n=>Te(ae({},"__esModule",{value:!0}),n);var Je={};De(Je,{ModuleRegistry:()=>k,PixelRuntime:()=>se});module.exports=Ue(Je);var k=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 E=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,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);return{...e,timestamp:Date.now(),path:t.path,url:t.url,hostname:t.hostname,language:t.language,timezone:t.timezone,...o?{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}}:{}}}:{}}}};var w=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 A={enabled:!0,ttlDays:90,persist:!0,captureUrlParams:!0,captureCookies:!0,customClickIdParams:[]},ce="attribution";var Le=["fbclid","gclid","gbraid","wbraid","ttclid","msclkid","epik","li_fat_id"],R=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 Le){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&&(o[i]=s)}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 _=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 s=e[o];s&&(t[i]=s)}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 D=class{constructor(e={}){this.clickIdParser=new R;this.cookieCollector=new _;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,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 o=Date.now();return e.firstCollectedAt||(r.firstCollectedAt=o),r.lastCollectedAt=o,r}};var T=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 U=class{constructor(e,t=A){this.snapshot={};this.active=!1;this.enabled=t.enabled!==!1,this.store=new T(e,{persist:t.persist!==!1,ttlDays:t.ttlDays??90}),this.collector=new D({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 J=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(Me(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 Me(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 Oe="fingerprint";function Ne(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 Fe(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Ne(t.join("|"))}var ee=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Oe,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Fe(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 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 S=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 Be(n){return"removeKeysMatching"in n&&typeof n.removeKeysMatching=="function"}var L=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(Be(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 S;switch(e){case"memory":return new S;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 S;case"indexedDB":return new S;default:return new S}}var M=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 s=typeof i.sku=="string"?i.sku.trim():"";s&&!this.productsBySku.has(s)&&this.productsBySku.set(s,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,s=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}:{},...s!==void 0?{quantity:s}:{},...e.metadata?{metadata:{...e.metadata}}:{}}}cloneProduct(e){return{...e,...e.metadata?{metadata:{...e.metadata}}:{}}}};var O=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 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 N=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 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 te={pageView:{enabled:!1,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"}},ue={enabled:!1,currency:"BRL",catalog:{products:[]},cart:{mode:"custom",initialItems:[],allowDynamicItems:!0,calculateValueFrom:"cart"},mappings:{attributes:{},fields:{}},enrichment:{...te}};function F(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 B=class{constructor(e){this.catalog=e.catalog,this.state=e.state,this.calculator=e.calculator,this.defaultCurrency=qe(e.defaultCurrency),this.calculateValueFrom=F(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",s=o==="catalog"||o==="cart"||o==="event_or_cart",a=d(t.productId)??d(r.productId)??(s?this.lookupIdBySku(d(t.sku)??d(r.sku)):void 0),l=!a&&i?this.resolvePrimaryCartItem():null;!a&&l&&(a=l.productId);let c=s&&a?this.catalog.getById(a):s?this.lookupProductBySku(d(t.sku)??d(r.sku)):null,u=a??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=h(t.price)??h(r.price)??(i?h(y?.price):void 0)??c?.price,m=h(t.quantity)??h(r.quantity)??(i?h(y?.quantity):void 0)??c?.quantity??1,f=d(t.currency)??d(r.currency)??(i?d(y?.currency):void 0)??c?.currency??this.defaultCurrency,C={};u&&(C.productId=u),g&&(C.productName=g),p!==void 0&&(C.price=p),f&&(C.currency=f),m!==void 0&&(C.quantity=m);for(let[Q,Y]of Object.entries(t))Y!==void 0&&(Q in C||(C[Q]=Y));return{data:C}}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,s=o??i?.id,a=s?this.state.getItem(s):null,l=h(t.quantity)??h(r.quantity)??h(a?.quantity)??1,c={};s&&(c.productId=s),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=h(r.value),i=d(r.currency),s=this.readPayloadItems(e),a=e.enrichmentSource,l=this.resolveItemsSource(s,a),c=l.map(C=>this.toPixelItem(C)),u=a!=="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:s===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),s={...t},a=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 a&&(s.contentId=a),l&&(s.contentName=l),h(t.value)===void 0&&i.value!==void 0&&(s.value=i.value),!d(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 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&&h(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:h(e.price),quantity:h(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 d(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function h(n){if(!(typeof n!="number"||!Number.isFinite(n)))return n}function qe(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var q=class{constructor(e){this.config={...ue,...e,catalog:{products:e?.catalog?.products??[]},cart:{...ue.cart,...e?.cart,initialItems:e?.cart?.initialItems?e.cart.initialItems.map(t=>({...t})):[]},mappings:{attributes:{...e?.mappings?.attributes??{}},fields:{...e?.mappings?.fields??{}}},enrichment:{...te,...e?.enrichment}},this.enabled=this.config.enabled===!0,this.catalog=new M(this.config.catalog?.products,{defaultCurrency:this.config.currency}),this.state=new O(this.config.cart?.initialItems,{allowDynamicItems:this.config.cart?.allowDynamicItems!==!1}),this.resolver=new B({catalog:this.catalog,state:this.state,calculator:new N,defaultCurrency:this.config.currency,calculateValueFrom:F(this.config.cart?.calculateValueFrom)})}getEnrichment(e){let t=this.config.enrichment?.[e],r=te[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,s=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}:{},...s?{contentName:s}:{}}}getResolver(){return this.resolver}getCalculateValueFrom(){return F(this.config.cart?.calculateValueFrom)}getMappings(){return this.config.mappings}};function Ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function re(){return`ses_${Ke()}`}var ze="session",oe=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??ze}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=re();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=re();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=re();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 Ve(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function Se(){return`vst_${Ve()}`}var $e="visitor",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??$e}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=Se();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var de=["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]"],xe="[data-no-sid]";function x(n){return n.trim().toLowerCase()}function K(n){try{return decodeURIComponent(n)}catch{return n}}function z(n,e){let t=new Set;if(e!==!1)for(let r of de)t.add(x(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(x(r));return t}function Ie(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(xe);for(let o of n??[])typeof o=="string"&&o.trim()&&r.push(o.trim());return Array.from(new Set(r))}function ie(n,e){return e.has(x(n))}function be(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function pe(n,e,t){if(!n)return!1;for(let r of t)if(be(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>be(n,r))}function fe(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 v(){return typeof window<"u"&&typeof document<"u"}function ye(n){if(v())try{History.prototype.replaceState.call(history,history.state,document.title,n)}catch{}}function b(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=K((o>=0?r.slice(0,o):r).replace(/\+/g," ")).trim();if(!i)continue;let s=o>=0?K(r.slice(o+1).replace(/\+/g," ")):"";e[i]=s}return e}function V(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 I(n){return Object.freeze({...n})}function he(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 $=class{collect(e){if(!e||e.enabled===!1)return{};if(!v())return{};let t=b(window.location.search),r=z(e.denylist,e.mergeDefaultDenylist),o=e.mode??"all_except",i=new Set((e.allowlist??[]).map(x).filter(Boolean)),s={};for(let[a,l]of Object.entries(t))ie(a,r)||o==="allowlist"&&!i.has(x(a))||l!==""&&(s[a]=l);return s}};var j=class{constructor(e){this.store=e}resolve(e){let t={},r={},o={},i={},s=v()?b(window.location.search):{};for(let a of e){let l=a.param?.trim();if(!l)continue;let c=a.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=s[l];m&&m.length>0&&(g=m,p="url")}if(!g&&u&&a.persistence?.enabled!==!1){let m=a.persistence?.cookie?.name?.trim()||l;if(a.persistence?.cookie?.enabled!==!1){let f=this.store.getCookie(m);f&&(g=f,p="cookie")}}if(!g&&u&&a.persistence?.enabled!==!1){let m=a.persistence?.storageKey?.trim()||l,f=this.store.getStorage(m);f&&(g=f,p="storage")}!g&&y&&a.generator?.type==="public_id"&&(g=fe(a.generator.prefix??l),p="generated"),!(!g||!p)&&(t[l]=g,r[l]=p,a.decorateLinks!==!1&&(o[l]=g),a.persistence?.enabled!==!1&&this.persist(a,g),y&&(a.writeStrategy??"replaceState")==="replaceState"&&v()&&s[l]!==g&&(i[l]=g))}return Object.keys(i).length>0&&v()&&this.writeToUrl(i),{values:t,sources:r,decorateParams:o}}persist(e,t){let r=e.persistence?.strategy??"localStorage_cookie",o=e.persistence?.storageKey?.trim()||e.param,i=e.persistence?.cookie,s=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: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={...b(window.location.search),...e},o=V(r),i=window.location.hash??"",s=window.location.pathname+o+i;ye(s)}};var H=class{resolve(e){let{queryParams:t,managedValues:r,config:o}=e;if(!o||o.enabled===!1)return{};let i=z(o.denylist,o.mergeDefaultDenylist),s=o.mode??"all_except",a=new Set((o.allowlist??[]).map(x).filter(Boolean)),l={};for(let[c,u]of Object.entries(t))u&&(ie(c,i)||c in r||s==="allowlist"&&!a.has(x(c))||(l[c]=u));return l}};var je=["mailto:","tel:","javascript:","data:","blob:"],X=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;this.params=Object.freeze({...e}),this.config=t,this.excludedDomains=Ie(t.excludedDomains,t.mergeDefaultExcludedDomains),this.excludeSelectors=Pe(t.excludeSelectors,t.mergeDefaultExcludeSelectors,r)}start(){if(this.started||!v()||this.config.enabled===!1||Object.keys(this.params).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=He(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 je)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=v()?window.location.href:`https://${t??"example.com"}/`;i=new URL(r,m)}catch{return null}if(!pe(i.hostname,this.config.allowedDomains,this.excludedDomains))return null;let s=b(i.search),a=this.config.preserveExisting!==!1,l=this.config.overwriteExisting===!0,c={...s},u=!1;for(let[m,f]of Object.entries(this.params))m in c&&a&&!l||(c[m]!==f&&(u=!0),c[m]=f);let y=b(r.includes("?")?r.slice(r.indexOf("?")).split("#")[0]??"":""),g=Xe(r)>Object.keys(y).length;if(!u&&!g)return r;let p=V(c);return i.search=p.startsWith("?")?p.slice(1):p,he(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 He(n){return n instanceof Element?n.closest("a[href]"):null}function Xe(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 W=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(!v())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 s=o>=0?r.slice(o+1).trim():"";return K(s)}}catch{return null}return null}setCookie(e){if(!v())return;let t=[`${encodeURIComponent(e.name)}=${encodeURIComponent(e.value)}`];t.push(`path=${e.path??"/"}`);let r=We(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 We(n){if(!n||n==="auto"){if(!v())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},Qe={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ye={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},Ze={enabled:!0,strategy:"on_click",selector:"a[href]",allowedDomains:"*",mergeDefaultExcludedDomains:!0,mergeDefaultExcludeSelectors:!0,preserveExisting:!0,overwriteExisting:!1,decorateHashLinks:!1,decorateMailto:!1,decorateTel:!1};function ve(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:{...Qe,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Ye,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...Ze,...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 G=class{constructor(e,t){this.collector=new $;this.forwardResolver=new H;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Ce();this.initialized=!1;this.enabled=!1;this.rawConfig=e,this.storage=t??null}init(){if(this.initialized)return;this.initialized=!0;let e=ve(this.rawConfig);if(this.enabled=e.enabled,!e.enabled){this.snapshot=Ce();return}this.store=new W(this.storage),this.managedResolver=new j(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}),s={...r.sources};for(let u of Object.keys(i))s[u]||(s[u]="url");let a={...Object.keys(r.values).length>0?{managed:I(r.values)}:{},...Object.keys(i).length>0?{forwarded:I(i)}:{},...Object.keys(s).length>0?{source:Object.freeze({...s})}:{}};this.snapshot={queryParams:I(o),urlContext:Object.freeze(a)};let l={...i,...r.decorateParams},c=e.managedParams.some(u=>u.param==="sid"&&u.decorateLinks!==!1);this.decorator=new X(l,e.linkDecoration,c),this.decorator.start()}destroy(){this.decorator?.destroy(),this.decorator=null,this.managedResolver=null,this.store=null,this.initialized=!1,this.enabled=!1,this.snapshot=Ce()}dispose(){this.destroy()}isEnabled(){return this.enabled}getSnapshot(){return{queryParams:I(this.snapshot.queryParams),urlContext:{...this.snapshot.urlContext.managed?{managed:I(this.snapshot.urlContext.managed)}:{},...this.snapshot.urlContext.forwarded?{forwarded:I(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 Ce(){return{queryParams:I({}),urlContext:Object.freeze({})}}var se=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new k,this.fallbackLogger=new w(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),s=this.createStorageService(t,r,o?.session),a=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 U(l,this.config.attribution??A),g=this.createStorageService(t,r,o?.attribution??"localStorage"),p=new G(this.config.modules.core.urlContext,g),m=new E(u,y,p),f=new ne(i,this.config),C=new oe(s,this.config),Q=new ee(a,this.config,u),Y=new J(e),we=new q(this.config.commerce);return{storage:c,visitor:f,session:C,fingerprint:Q,dispatcher:Y,browserMetadata:u,eventBuilder:m,attribution:y,commerce:we,urlContext:p}}createStorageService(e,t,r){return new L(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.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};0&&(module.exports={ModuleRegistry,PixelRuntime});
|
|
2
|
+
"use strict";var le=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var De=(n,e)=>{for(var t in e)le(n,t,{get:e[t],enumerable:!0})},Ue=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ae(e))!_e.call(n,o)&&o!==t&&le(n,o,{get:()=>e[o],enumerable:!(r=Re(e,o))||r.enumerable});return n};var Te=n=>Ue(le({},"__esModule",{value:!0}),n);var tt={};De(tt,{ModuleRegistry:()=>E,PixelRuntime:()=>ce});module.exports=Te(tt);var E=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:[]},de="attribution";var Me=["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 Me){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??de}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(Le(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 Le(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 Oe="fingerprint";function Ne(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 Fe(n){let e=n.getMetadata(),t=[e.userAgent??"",e.language??"",e.platform??"",String(e.screenWidth??""),String(e.screenHeight??""),String(e.colorDepth??""),e.timezone??""];return Ne(t.join("|"))}var te=class{constructor(e,t,r){this.storage=e,this.storageKey=t.storage.keys?.fingerprint??Oe,this.metadataService=r}getFingerprint(){return this.storage.get(this.storageKey)}ensureFingerprint(){let e=this.getFingerprint();if(e)return e;let t=Fe(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 Be(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(Be(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 ue(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:!1,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"}},me={enabled:!1,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=ze(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=qe(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 qe(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 ze(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}var V=class{constructor(e){this.config={...me,...e,catalog:{products:e?.catalog?.products??[]},cart:{...me.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 Ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function oe(){return`ses_${Ke()}`}var Ve="session",ne=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.session??Ve}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 $e(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):`${Date.now()}${Math.random().toString(36).slice(2)}`}function be(){return`vst_${$e()}`}var je="visitor",ie=class{constructor(e,t){this.storage=e,this.storageKey=t.storage.keys?.visitor??je}getVisitorId(){return this.storage.get(this.storageKey)}ensureVisitorId(){let e=this.getVisitorId();if(e)return e;let t=be();return this.storage.set(this.storageKey,t),t}clearVisitorId(){this.storage.remove(this.storageKey)}};var ge=["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"],fe=["facebook.com","google.com","youtube.com","instagram.com","wa.me","whatsapp.com","t.me","telegram.me"],pe=["[data-no-url-context]","[download]"],Pe="[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 ge)t.add(b(r));for(let r of n??[])typeof r=="string"&&r.trim()&&t.add(b(r));return t}function ye(n,e){let t=[];e!==!1&&t.push(...fe);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 he(n,e,t){let r=[];e!==!1&&r.push(...pe),t&&r.push(Pe);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 ke(n,e){let r=n.toLowerCase().replace(/\.$/,"").replace(/:\d+$/,""),o=e.toLowerCase().replace(/^\./,"").replace(/:\d+$/,"");return r===o||r.endsWith(`.${o}`)}function Ce(n,e,t){if(!n)return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local");for(let r of t)if(ke(n,r))return!1;return e===void 0||e==="*"?!0:e.some(r=>r.trim().toLowerCase()==="local"?!1:ke(n,r))}function ve(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 xe(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 Se(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=ve(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;xe(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 He=["mailto:","tel:","javascript:","data:","blob:"],w=class{constructor(e,t,r){this.clickHandler=null;this.started=!1;if(Xe(e)){this.forwardedParams=Object.freeze({...e.forwardedParams??{}}),this.managedParams=Object.freeze({...e.managedParams??{}}),this.config=e.config,this.excludedDomains=ye(e.config.excludedDomains,e.config.mergeDefaultExcludedDomains),this.excludeSelectors=he(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=ye(i.excludedDomains,i.mergeDefaultExcludedDomains),this.excludeSelectors=he(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=We(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 He)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(!Ce(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=Ge(r)>Object.keys(y).length;if(!u&&!g)return r;let p=H(c);return i.search=p.startsWith("?")?p.slice(1):p,Se(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 Xe(n){return typeof n=="object"&&n!==null&&"config"in n&&typeof n.config=="object"&&n.config!==null}function We(n){return n instanceof Element?n.closest("a[href]"):null}function Ge(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=Qe(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 Qe(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 we={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},Ze={enabled:!0,mode:"all_except",mergeDefaultDenylist:!0},et={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(Ee):[Ee(we)];return{enabled:!0,queryParams:{...Je,...n.queryParams,...n.queryParams?.allowlist?{allowlist:[...n.queryParams.allowlist]}:{},...n.queryParams?.denylist?{denylist:[...n.queryParams.denylist]}:{}},managedParams:e,forwardParams:{...Ze,...n.forwardParams,...n.forwardParams?.allowlist?{allowlist:[...n.forwardParams.allowlist]}:{},...n.forwardParams?.denylist?{denylist:[...n.forwardParams.denylist]}:{}},linkDecoration:{...et,...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 Ee(n){return{...n,...n.generator?{generator:{...n.generator}}:{},...n.persistence?{persistence:{...n.persistence,...n.persistence.cookie?{cookie:{...n.persistence.cookie}}:{}}}:{}}}var R=class{constructor(e,t){this.collector=new X;this.forwardResolver=new G;this.store=null;this.managedResolver=null;this.decorator=null;this.snapshot=Ie();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=Ie();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 w({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 w({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=Ie()}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 Ie(){return{queryParams:C({}),urlContext:Object.freeze({})}}var ce=class{constructor(e){this.initialized=!1;this.initializedModules=[];this.context=null;this.config=e,this.registry=new E,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 R(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(ue(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.modules.transport.enabled,integrations:this.config.modules.integrations.enabled}[e.name]}};0&&(module.exports={ModuleRegistry,PixelRuntime});
|
|
3
3
|
//# sourceMappingURL=index.cjs.js.map
|