@crelora/mark 0.2.2 → 0.3.2
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/README.md +20 -3
- package/dist/browser.es.js +215 -170
- package/dist/browser.es.js.map +1 -1
- package/dist/browser.umd.js +1 -1
- package/dist/browser.umd.js.map +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.es.js +119 -95
- package/dist/node.es.js.map +1 -1
- package/dist/types/browser/BrowserStorage.d.ts +9 -0
- package/dist/types/browser/Mark.d.ts +9 -0
- package/dist/types/browser/pageEngagement.d.ts +1 -0
- package/dist/types/core/DeliveryQueue.d.ts +2 -2
- package/dist/types/core/MarkCore.d.ts +7 -1
- package/dist/types/core/adapters.d.ts +1 -0
- package/dist/types/core/visitorId.d.ts +5 -0
- package/dist/types/node/StatelessStorage.d.ts +1 -0
- package/dist/types/node/index.d.ts +6 -0
- package/dist/types/types.d.ts +9 -0
- package/package.json +2 -2
package/dist/browser.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(y,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(y=typeof globalThis<"u"?globalThis:y||self,v(y.Mark={}))})(this,(function(y){"use strict";const v="https://ingest.onelence.com";class w extends Error{status;retryAfterMs;constructor(e,t={}){super(e),this.name="TransportError",this.status=t.status,this.retryAfterMs=t.retryAfterMs}}function ve(s){return!(typeof s!="number"||s<400||s>=500||s===408||s===429)}function be(s){if(!s)return;const e=s.trim();if(!e)return;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t*1e3);const i=Date.parse(e);if(Number.isFinite(i)){const n=i-Date.now();return n>0?n:0}}const _e=5,Ae=300,Se=15e3,Ie=2880*60*1e3;class Te{constructor(e,t={}){this.transport=e,this.maxAttempts=t.maxAttempts??_e,this.baseBackoffMs=t.baseBackoffMs??Ae,this.maxBackoffMs=t.maxBackoffMs??Se,this.maxItemAgeMs=t.maxItemAgeMs??Ie,this.debug=t.debug??!1,this.loadPersisted=t.loadPersisted,this.savePersisted=t.savePersisted,this.onError=t.onError;const i=this.loadPersisted?.()??[];if(i.length>0){const n=Date.now();for(const o of i){const a=o.enqueuedAt??n;if(n-a>this.maxItemAgeMs){this.dropped+=1;continue}this.queue.push({...o,enqueuedAt:a})}this.persist()}}queue=[];flushing=!1;sent=0;failed=0;dropped=0;maxAttempts;baseBackoffMs;maxBackoffMs;maxItemAgeMs;debug;loadPersisted;savePersisted;onError;enqueue(e,t){this.queue.push({path:e,data:t,attempts:0,nextAttemptAt:Date.now(),enqueuedAt:Date.now()}),this.persist(),this.process()}async flush(){await this.process(!0),await this.transport.flush?.()}drainViaBeacon(){if(this.queue.length===0)return;const e=this.queue.splice(0,this.queue.length);this.persist();for(const t of e){const i={...t.data};delete i.__prefer_beacon;try{this.transport.send(t.path,i,{preferBeacon:!0})}catch{}}}getStats(){return{queued:this.queue.length,sent:this.sent,failed:this.failed,dropped:this.dropped}}clear(){this.queue.splice(0,this.queue.length),this.persist()}persist(){this.savePersisted?.(this.queue)}evictExpired(){if(this.queue.length===0)return;const t=Date.now()-this.maxItemAgeMs;let i=0;for(let n=this.queue.length-1;n>=0;n-=1)this.queue[n].enqueuedAt<=t&&(this.queue.splice(n,1),this.dropped+=1,i+=1);i>0&&this.persist()}async process(e=!1){if(!this.flushing){this.flushing=!0;try{for(this.evictExpired();this.queue.length>0;){const t=this.queue[0];if(!e&&t.nextAttemptAt>Date.now())break;try{const i={...t.data},n=i.__prefer_beacon===!0;delete i.__prefer_beacon,await this.transport.send(t.path,i,{preferBeacon:n}),this.queue.shift(),this.sent+=1,this.persist()}catch(i){this.failed+=1,this.onError?.(i,t.data);const n=i instanceof w?i.status:void 0;if(ve(n)){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after non-retriable status",n,t.path);continue}if(t.attempts+=1,t.attempts>=this.maxAttempts){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after max retries",t.path,i);continue}const o=i instanceof w?i.retryAfterMs:void 0;let a;if(typeof o=="number")a=Math.min(this.maxBackoffMs,Math.max(0,o));else{const c=Math.random()*this.baseBackoffMs;a=Math.min(this.maxBackoffMs,this.baseBackoffMs*2**(t.attempts-1)+c)}t.nextAttemptAt=Date.now()+a,this.persist();break}}}finally{this.flushing=!1}}}}const Ee=new Set(["event_name","user_id","consent_state","source","is_conversion"]),xe=new Set(["user_id","visitor_id","click_id","campaign_id","query","consent_state","source"]);class Ce{constructor(e,t){this.deps=t,this.validateConfig(e),this.config={endpoint:e.endpoint??v,...e,include_page_context:e.include_page_context??!0},this.consentRequirement=e.require_consent??!1,this.siteId=e.site_id,this.siteHost=e.site_host,this.sessionTimeoutMs=e.session_timeout_ms??1800*1e3,this.queue=new Te(this.deps.transport,{debug:this.config.debug,loadPersisted:()=>this.deps.storage.getOutbox?.()??[],savePersisted:i=>this.deps.storage.setOutbox?.(i),onError:(i,n)=>this.config.on_error?.(i,n)}),this.warnMisconfiguredSiteHost(),this.subscribeTcf()}config;consentRequirement;siteId;siteHost;queue;sessionTimeoutMs;batchTimer=null;batchedEvents=[];tcfCachedAllowed=!1;drainViaBeacon(){this.flushBatch(),this.queue.drainViaBeacon()}kickQueue(){this.queue.flush()}track(e,t={}){return this.trackInternal(e,t,!1)}trackInternal(e,t={},i=!1,n){if(!e)return this.config.debug&&console.warn("[Mark] track called without event name"),!1;if(!this.hasConsent()||this.isDntBlocked())return this.config.debug&&console.warn("[Mark] Tracking blocked due to consent requirement."),!1;if(!i&&!this.shouldSampleTrack())return!0;const o=this.sanitizeTrackData(t),a={...o};"query"in a&&delete a.query,"site_id"in a&&delete a.site_id,"site_host"in a&&delete a.site_host;const c={event_name:e,message_id:this.createMessageId(),...this.getIdentityFields(o),...a};i&&(c.is_conversion=!0);const l=o.site_id??this.siteId,u=o.site_host??this.siteHost;l&&(c.site_id=l),u&&(c.site_host=u),this.config.include_page_context&&typeof window<"u"&&(this.applyPageContext(c),!u&&c.site&&(c.site_host=c.site)),this.applyInternalFlag(c,o.is_internal);const d=this.config.before_send?this.config.before_send(c):c;return d?(this.ensureSession(),this.applySessionFields(d),this.config.batching?.enabled&&!i&&!n?.preferBeacon?(this.enqueueBatch(d),!0):(this.queue.enqueue("/event",{...d,__prefer_beacon:n?.preferBeacon===!0}),!0)):!0}identify(e,t={}){if(!e){this.config.debug&&console.warn("[Mark] identify called without userId");return}if(!this.hasConsent()||this.isDntBlocked()){this.config.debug&&console.warn("[Mark] Identify blocked due to consent requirement.");return}this.deps.storage.update({user_id:e});const i={user_id:e,message_id:this.createMessageId(),...this.sanitizeIdentifyTraits(t),...this.getIdentityFields()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&(this.ensureSession(),this.applySessionFields(n),this.queue.enqueue("/identify",n))}conversion(e,t={}){return this.trackInternal(e,t,!0)}trackWithOptions(e,t={},i){return this.trackInternal(e,t,!1,i)}getVisitorId(){return this.deps.storage.getVisitorId()}setConsent(e){const t=this.deps.storage.getConsentStatus();this.deps.storage.setConsentStatus(e),e==="denied"?(this.deps.storage.clearAttribution?.(),this.deps.storage.clearCookieVisitorId?.(),this.deps.storage.setInternal?.(!1)):e==="granted"&&t==="denied"&&this.config.rotate_visitor_on_consent_change&&this.deps.storage.rotateVisitorId?.();const i={visitor_id:this.deps.storage.getVisitorId(),consent_state:e,source:"sdk",message_id:this.createMessageId()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&this.queue.enqueue("/consent",n)}reset(){this.deps.storage.update({user_id:void 0,last_click_id:void 0,campaign_id:void 0,query_params:void 0,session_id:void 0,session_started_at:void 0,last_activity_at:void 0,is_internal:void 0}),this.deps.storage.rotateVisitorId?.()}setInternal(e){this.deps.storage.setInternal?.(!!e)}getInternal(){return!!this.deps.storage.getInternal?.()}flush(){return this.flushBatch(),this.queue.flush()}getStats(){return this.queue.getStats()}applyInternalFlag(e,t){if(t===!1){delete e.is_internal;return}const i=this.deps.storage.getInternal?.()===!0;t===!0||i?e.is_internal=!0:delete e.is_internal}getIdentityFields(e){const t=e?.visitor_id??this.deps.storage.getVisitorId(),i=e?.user_id??this.deps.storage.getUserId?.(),n=e?.click_id??this.deps.storage.getLastClickId(),o=e?.campaign_id??this.deps.storage.getCampaignId(),a=e?.session_id??this.deps.storage.getSessionId?.(),c=this.deps.storage.getQueryParams()??{},l=e?.query??{},u={...c,...l},d={};t&&(d.visitor_id=t),i&&(d.user_id=i),n&&(d.click_id=n),o&&(d.campaign_id=o),a&&(d.session_id=a);const h=this.deps.storage.getSessionStartedAt?.();return a&&h&&(d.session_started_at=h,d.session_elapsed_ms=Date.now()-Date.parse(h)),Object.keys(u).length>0&&(d.query=u),d}applySessionFields(e){if(!e.session_id){const i=this.deps.storage.getSessionId?.(),n=this.deps.storage.getSessionStartedAt?.();i&&(e.session_id=i),n&&(e.session_started_at=n)}const t=e.session_started_at;e.session_id&&typeof t=="string"&&(e.session_elapsed_ms=Date.now()-Date.parse(t))}hasConsent(){if(this.config.consent_source?.type==="tcf"&&typeof window<"u"&&!this.tcfCachedAllowed)return!1;if(!this.consentRequirement)return!0;const t=this.deps.storage.getConsentStatus();return this.consentRequirement==="auto",t==="granted"}sanitizeTrackData(e){const t={};for(const[i,n]of Object.entries(e))Ee.has(i)||(t[i]=n);return t}sanitizeIdentifyTraits(e){const t={};for(const[i,n]of Object.entries(e))xe.has(i)||(t[i]=n);return t}validateConfig(e){if(!e.key||!e.key.trim())throw new Error("[Mark] `key` must be a non-empty string.");if(e.endpoint)try{new URL(e.endpoint)}catch{throw new Error("[Mark] `endpoint` must be a valid absolute URL.")}if(typeof e.site_id=="string"&&!e.site_id.trim())throw new Error("[Mark] `site_id` cannot be an empty string.");if(typeof e.site_host=="string"&&!e.site_host.trim())throw new Error("[Mark] `site_host` cannot be an empty string.")}applyPageContext(e){typeof document>"u"||(e.site||(e.site=window.location.host),e.page||(e.page=window.location.pathname),e.title||(e.title=document.title),!e.referrer&&document.referrer&&(e.referrer=this.scrubReferrer(document.referrer)))}enqueueBatch(e){this.batchedEvents.push(e);const t=this.config.batching?.max_size??20;if(this.batchedEvents.length>=t){this.flushBatch();return}if(!this.batchTimer){const i=this.config.batching?.flush_interval_ms??2e3;this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushBatch()},i)}}flushBatch(){if(this.batchedEvents.length===0)return;const e=this.config.batching?.endpoint_path??"/events",t=this.batchedEvents.splice(0,this.batchedEvents.length);this.queue.enqueue(e,{events:t,message_id:this.createMessageId()})}createMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`msg_${Date.now()}_${Math.random().toString(16).slice(2)}`}ensureSession(){const e=Date.now(),t=this.deps.storage.getSessionId?.(),i=this.deps.storage.getLastActivityAt?.(),n=i?Date.parse(i):0;if(!t||!n||e-n>=this.sessionTimeoutMs||this.crossedUtcDay(n,e)){const a=this.createMessageId(),c=new Date(e).toISOString();this.deps.storage.update({session_id:a,session_started_at:c,last_activity_at:c});return}this.deps.storage.update({last_activity_at:new Date(e).toISOString()})}crossedUtcDay(e,t){const i=new Date(e),n=new Date(t);return i.getUTCFullYear()!==n.getUTCFullYear()||i.getUTCMonth()!==n.getUTCMonth()||i.getUTCDate()!==n.getUTCDate()}shouldSampleTrack(){return typeof this.config.sample_rate!="number"?!0:this.config.sample_rate<=0?!1:this.config.sample_rate>=1?!0:Math.random()<=this.config.sample_rate}isDntBlocked(){if(!this.config.honor_dnt||typeof navigator>"u")return!1;const e=navigator.doNotTrack,t=navigator.globalPrivacyControl;return e==="1"||t===!0}scrubReferrer(e){try{const t=new URL(e);if(typeof window>"u")return e;const i=new URL(window.location.href);return t.origin!==i.origin?(t.search="",t.toString()):e}catch{return e}}warnMisconfiguredSiteHost(){!this.config.debug||!this.siteHost||typeof window>"u"||(window.location.host!==this.siteHost&&console.warn("[Mark] config.site_host does not match current host",{expected:this.siteHost,actual:window.location.host}),this.siteId&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(this.siteId)&&console.warn("[Mark] config.site_id does not look like UUID v4",this.siteId))}subscribeTcf(){const e=this.config.consent_source;if(e?.type!=="tcf"||typeof window>"u")return;const t=e.purposes,i=n=>{try{const o=window;if(typeof o.__tcfapi!="function"){n>0&&setTimeout(()=>i(n-1),200);return}o.__tcfapi("addEventListener",2,(a,c)=>{if(!c||!a){this.tcfCachedAllowed=!1;return}if(a.gdprApplies===!1){this.tcfCachedAllowed=!0;return}const l=a.purpose?.consents??{};this.tcfCachedAllowed=t.every(u=>l[String(u)]===!0)})}catch{this.tcfCachedAllowed=!1}};i(10)}}class Le{config;endpoint;pending=new Set;constructor(e){this.config=e,this.endpoint=e.endpoint??v}async send(e,t,i){const n=this.sendInternal(e,t,i);this.pending.add(n);try{await n}finally{this.pending.delete(n)}}async flush(){this.pending.size!==0&&await Promise.allSettled(Array.from(this.pending))}async sendInternal(e,t,i){const n=this.joinUrl(this.endpoint,e),o=this.config.key,a={"Content-Type":"application/json",[o.startsWith("sk_")?"x-secret-key":"x-publishable-key"]:o};this.config.debug&&console.log("[Mark] Sending",n,t);const c=JSON.stringify(t);if(i?.preferBeacon&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){const f=new Blob([c],{type:"application/json"});if(navigator.sendBeacon(n,f))return}if(typeof fetch!="function")throw this.config.debug&&console.error("[Mark] Global fetch is not available in this runtime."),new w("[Mark] Global fetch is not available in this runtime.");const l=this.config.request_timeout_ms??1e4,u=new AbortController;let d=!1;const h=setTimeout(()=>{d=!0,u.abort()},l);try{const f=await fetch(n,{method:"POST",headers:a,body:c,keepalive:!0,signal:u.signal});if(!f.ok){const m=await this.readErrorSnippet(f),we=be(f.headers.get("Retry-After"));throw this.config.debug&&console.error("[Mark] Request rejected",{url:n,status:f.status,statusText:f.statusText,body:m,retryAfterMs:we}),new w(`[Mark] Request rejected with status ${f.status}: ${m}`,{status:f.status,retryAfterMs:we})}}catch(f){if(this.config.debug&&console.error("[Mark] Failed to send",n,f),f instanceof w)throw f;if(d)throw new w(`[Mark] Request timed out after ${l}ms`,{status:408});const m=f instanceof Error?f.message:String(f);throw new w(`[Mark] Network error: ${m}`)}finally{clearTimeout(h)}}joinUrl(e,t){const i=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${i}/${n}`}async readErrorSnippet(e){try{return(await e.text()).slice(0,300)}catch{return""}}}const Pe="crelora_mark_data",ke="crelora_mark_outbox",N="crelora_mark_vid";class De{data;storageKey;outboxKey;options;bridgeFrame;bridgeReady=!1;bridgeOrigin;constructor(e){if(this.options=e??{},this.storageKey=this.options.storageKey??Pe,this.outboxKey=this.options.outboxKey??ke,typeof window>"u"){this.data={};return}this.data=this.load(),this.data.visitor_id||(this.data.visitor_id=this.generateUUID(),this.save()),typeof window<"u"&&this.options.bridge?.url&&this.setupBridge(this.options.bridge),window.addEventListener("storage",this.handleStorageEvent)}getVisitorId(){return this.data.visitor_id}getLastClickId(){return this.data.last_click_id}getCampaignId(){return this.data.campaign_id}getQueryParams(){return this.data.query_params}getConsentStatus(){return this.data.consent_status}getUserId(){return this.data.user_id}getSessionId(){return this.data.session_id}getSessionStartedAt(){return this.data.session_started_at}getLastActivityAt(){return this.data.last_activity_at}getInternal(){return this.data.is_internal}setInternal(e){e?this.update({is_internal:!0}):this.update({is_internal:void 0})}update(e){this.data={...this.data,...e},this.save()}setConsentStatus(e){this.data.consent_status=e,this.save()}clearAttribution(){this.update({last_click_id:void 0,campaign_id:void 0,query_params:void 0})}clearCookieVisitorId(){this.setCookie(N,"",-1)}rotateVisitorId(){this.update({visitor_id:this.generateUUID()})}getOutbox(){if(typeof window>"u")return[];try{const e=localStorage.getItem(this.outboxKey);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}setOutbox(e){if(!(typeof window>"u"))try{localStorage.setItem(this.outboxKey,JSON.stringify(e.slice(-200)))}catch{}}load(){if(typeof window>"u")return{};try{const t=localStorage.getItem(this.storageKey);if(t)return JSON.parse(t)}catch{}const e=this.getCookie(N);return e?{visitor_id:e}:{}}save(){if(!(typeof window>"u")){try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch{}this.data.visitor_id&&this.isCookieEnabled()&&(this.setCookie(N,this.data.visitor_id,365),this.options.bridge?.url&&this.bridgeReady&&this.postBridgeMessage({type:"MARK_SYNC_UPDATE",visitorId:this.data.visitor_id}))}}getCookie(e){if(typeof document>"u")return null;try{const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));if(t)return t[2]}catch{}return null}setCookie(e,t,i){if(!(typeof document>"u"))try{const n=new Date(Date.now()+i*24*60*60*1e3),o=this.options.cookie_domain?`;domain=${this.options.cookie_domain}`:"";document.cookie=`${e}=${t};expires=${n.toUTCString()};path=/;SameSite=Lax${o}`}catch{}}generateUUID(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=(Date.now()+Math.random()*16)%16|0;return(e==="x"?t:t&3|8).toString(16)})}isCookieEnabled(){return this.options.mode?this.options.mode==="single"||this.options.mode==="subdomain":!0}setupBridge(e){if(typeof document>"u")return;let t;try{t=new URL(e.url,window.location.href)}catch{return}this.bridgeOrigin=t.origin,this.bridgeFrame=document.createElement("iframe"),this.bridgeFrame.style.display="none",this.bridgeFrame.setAttribute("aria-hidden","true"),this.bridgeFrame.src=t.toString();const i=e.timeout_ms??3e3,n=setTimeout(()=>{window.removeEventListener("message",this.handleBridgeMessage)},i);window.addEventListener("message",this.handleBridgeMessage);const o=()=>{this.bridgeFrame&&document.body&&document.body.appendChild(this.bridgeFrame)};document.body?o():document.addEventListener("DOMContentLoaded",o,{once:!0}),this.bridgeFrame.addEventListener("load",()=>{clearTimeout(n),this.bridgeReady=!0,this.postBridgeMessage({type:"MARK_SYNC_REQUEST",visitorId:this.data.visitor_id})})}handleBridgeMessage=e=>{if(!this.bridgeFrame?.contentWindow||e.source!==this.bridgeFrame.contentWindow||!this.isDomainAllowed(e.origin))return;const t=e.data;!t||!t.type||t.type==="MARK_SYNC_RESPONSE"&&t.visitorId&&t.visitorId!==this.data.visitor_id&&(this.data.visitor_id=t.visitorId,this.save())};postBridgeMessage(e){this.bridgeFrame?.contentWindow&&this.bridgeFrame.contentWindow.postMessage(e,this.bridgeOrigin??"*")}isDomainAllowed(e){try{const t=new URL(e);if(this.options.allowed_domains?.length)return this.options.allowed_domains.some(n=>t.hostname===n||t.hostname.endsWith(`.${n}`));if(!this.bridgeOrigin)return!1;const i=new URL(this.bridgeOrigin);return t.hostname===i.hostname}catch{return!1}}handleStorageEvent=e=>{if(!(e.key!==this.storageKey||typeof e.newValue!="string"))try{this.data=JSON.parse(e.newValue)}catch{}}}const qe=["click_id","ch_click_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Ue=["cid","campaign_id"],Fe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","referral","affiliate_id","click_id","ch_click_id","cid","campaign_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Be={referral:"ref",affiliate_id:"ref",ch_click_id:"click_id",cid:"campaign_id"},Re=["email","phone","token","auth","password","code"],Oe=30,Ne=256;function ne(s,e={}){const t=new URLSearchParams(s),i=Me(t),n=se(i,qe),o=se(i,Ue),a=He(t,e),c={};return n&&(c.last_click_id=n),o&&(c.campaign_id=o),Object.keys(a).length>0&&(c.query_params=a),c}function He(s,e){const t={},i=new Set(re(e.query_param_denylist,Re)),n=oe(e.max_captured_query_params,Oe),o=oe(e.max_query_param_value_length,Ne),c=e.capture_all_query_params??!1?null:new Set([...Fe.map(A),...re(e.capture_query_params,[])]);for(const[l,u]of s.entries()){const d=A(l);if(!d)continue;const h=Be[d]??d;if(i.has(d)||i.has(h)||c&&!c.has(d))continue;const f=u.trim();if(f){if(!(h in t)&&Object.keys(t).length>=n)break;t[h]=f.slice(0,o)}}return t}function se(s,e){for(const t of e){const i=A(t),n=s[i]?.trim();if(n)return n}}function Me(s){const e={};for(const[t,i]of s.entries()){const n=A(t);!n||n in e||(e[n]=i)}return e}function A(s){return s.trim().toLowerCase()}function re(s,e){const t=s??e,i=new Set;for(const n of t){if(typeof n!="string")continue;const o=A(n);o&&i.add(o)}return Array.from(i)}function oe(s,e){if(typeof s!="number"||!Number.isFinite(s))return e;const t=Math.floor(s);return t<0?e:t}function q(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function Ke(s){if(!s||s==="?")return"";const e=s.startsWith("?")?s.slice(1):s;if(!e)return"";const t=new URLSearchParams(e),i=[];t.forEach((a,c)=>{i.push([c,a])}),i.sort(([a,c],[l,u])=>{const d=a.localeCompare(l);return d!==0?d:c.localeCompare(u)});const n=new URLSearchParams;for(const[a,c]of i)n.append(a,c);const o=n.toString();return o===""?"":`?${o}`}function H(s){const e=q(s.pathname),t=Ke(s.search);return`${s.origin}${e}${t}${s.hash}`}let U=!1,S=null;const I=[],T=[],E=[];let x=null,C=null,L=null,P=null;function M(){if(typeof window>"u")return;const s=H(window.location);if(s===S)return;const e={previousKey:S,nextKey:s};for(const t of I)t(e);S=s;for(const t of T)t(e)}function $e(){for(const s of E)s()}function Ve(s={}){if(U||typeof window>"u"||typeof document>"u")return;U=!0;const e=s.trackRouteChanges??!0;S=H(window.location),P=$e,window.addEventListener("pagehide",P),e&&(x=history.pushState,C=history.replaceState,history.pushState=function(...t){const i=x.apply(this,t);return M(),i},history.replaceState=function(...t){const i=C.apply(this,t);return M(),i},L=M,window.addEventListener("popstate",L))}function ze(s){return I.push(s),()=>{const e=I.indexOf(s);e>=0&&I.splice(e,1)}}function K(s){return T.push(s),()=>{const e=T.indexOf(s);e>=0&&T.splice(e,1)}}function je(s){return E.push(s),()=>{const e=E.indexOf(s);e>=0&&E.splice(e,1)}}function Ye(){!U||typeof window>"u"||(x&&(history.pushState=x),C&&(history.replaceState=C),L&&window.removeEventListener("popstate",L),P&&window.removeEventListener("pagehide",P),x=null,C=null,L=null,P=null,I.length=0,T.length=0,E.length=0,S=null,U=!1)}let F=0;function ae(){F=0}function Qe(){return F}function We(){if(typeof document>"u"||typeof window>"u")return 0;const s=document.documentElement,e=window.scrollY||s.scrollTop,t=Math.max(1,s.scrollHeight-window.innerHeight);return Math.min(100,Math.round(e/t*100))}function ce(){const s=We();return s>F&&(F=s),s}const Ge=[25,50,75,100];function Je(s,e=Ge){if(typeof window>"u")return;const t=new Set,i=()=>{t.clear(),ae()};i(),K(()=>{i()}),window.addEventListener("scroll",()=>{const n=ce();for(const o of e)n>=o&&!t.has(o)&&(t.add(o),s.track("scroll_depth",{percent:o}))},{passive:!0})}const de=1e4;function Xe(s){return s===!0?{minActiveMs:de,useBeacon:!0}:{minActiveMs:s.min_active_ms??de,useBeacon:s.use_beacon!==!1}}function Ze(s,e){if(typeof window>"u"||typeof document>"u")return;let t=Date.now(),i=0,n=document.visibilityState==="visible"?Date.now():null,o=q(window.location.pathname),a=!1;const c=()=>{n!==null&&(i+=Date.now()-n,n=null)},l=()=>{document.visibilityState==="visible"&&n===null&&(n=Date.now())},u=h=>{if(!a){a=!0;try{if(c(),ce(),i<e.minActiveMs)return;const f=Date.now()-t,m={page:o,active_time_ms:i,total_time_ms:f,max_scroll_percent:Qe()};e.useBeacon&&h?s.trackWithOptions("page_engagement",m,{preferBeacon:!0}):s.track("page_engagement",m)}finally{a=!1}}},d=()=>{t=Date.now(),i=0,o=q(window.location.pathname),ae(),l()};d(),ze(()=>{u(!0),c()}),K(()=>{d()}),je(()=>{u(!0)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?c():l()})}class r{static client=null;static storage=null;static config=null;static pageviewTrackerInstalled=!1;static lastPageviewDedupeKey=null;static emitAutoPageview=null;static pendingAttribution={};static beaconDrainHandler=null;static visibilityHandler=null;static onlineHandler=null;static kickTimer=null;static init(e){if(!r.client){const t=new De(e.cross_domain),i=new Le(e);r.client=new Ce(e,{storage:t,transport:i}),r.storage=t,r.config=e,r.refreshAttribution(t,e),typeof window<"u"&&(r.installPageLifecycleIfNeeded(e),e.autocapture?.pageview&&r.installPageviewTracking(e,t),r.installExtendedAutocapture(e),r.installLifecycleFlushing())}return r.client}static installLifecycleFlushing(){if(typeof window>"u"||r.beaconDrainHandler)return;const e=()=>{r.client?.drainViaBeacon()},t=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&e()},i=()=>{r.client?.kickQueue()};r.beaconDrainHandler=e,r.visibilityHandler=t,r.onlineHandler=i,typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",t),typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("online",i)),typeof setInterval=="function"&&(r.kickTimer=setInterval(()=>{r.client?.kickQueue()},3e4))}static track(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.track(e,t)}static identify(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.identify(e,t)}static conversion(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.conversion(e,t)}static setConsent(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setConsent(e),e==="granted"&&(r.flushPendingAttribution(),r.emitAutoPageview?.())}static getVisitorId(){if(!(!r.client||!r.storage||!r.config||(r.config.require_consent??!1)&&r.storage.getConsentStatus()!=="granted"))return r.client.getVisitorId()}static flush(){return r.client?r.client.flush():Promise.resolve()}static setInternal(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setInternal(e)}static getInternal(){return r.client?.getInternal()??!1}static reset(){r.client?.reset(),r.pendingAttribution={},r.lastPageviewDedupeKey=null}static getStats(){return r.client?.getStats()??{queued:0,sent:0,failed:0,dropped:0}}static destroy(){typeof window>"u"||(Ye(),r.beaconDrainHandler&&(window.removeEventListener("pagehide",r.beaconDrainHandler),window.removeEventListener("beforeunload",r.beaconDrainHandler)),r.visibilityHandler&&typeof document<"u"&&document.removeEventListener("visibilitychange",r.visibilityHandler),r.onlineHandler&&window.removeEventListener("online",r.onlineHandler),r.kickTimer&&clearInterval(r.kickTimer),r.beaconDrainHandler=null,r.visibilityHandler=null,r.onlineHandler=null,r.kickTimer=null,r.pageviewTrackerInstalled=!1)}static installPageLifecycleIfNeeded(e){const t=e.autocapture;if(!(!!t?.pageview||!!t?.scroll_depth||!!t?.page_engagement))return;const n=e.track_route_changes??!0;Ve({trackRouteChanges:n})}static installPageviewTracking(e,t){if(r.pageviewTrackerInstalled)return;r.pageviewTrackerInstalled=!0;const i=()=>{if(!r.client)return;r.refreshAttribution(t,e);const o=H(window.location);if(o===r.lastPageviewDedupeKey)return;r.client.track("page_view",{site:window.location.host,page:q(window.location.pathname),title:document.title,referrer:document.referrer||void 0})&&(r.lastPageviewDedupeKey=o)};r.emitAutoPageview=i,i(),(e.track_route_changes??!0)&&K(()=>{i()})}static refreshAttribution(e,t){if(typeof window>"u")return;const i=ne(window.location.search,t);if(Object.keys(i).length!==0){if(r.shouldPersistAttribution(e,t)){const n=r.mergeAttributionUpdates(r.pendingAttribution,i);e.update(n),r.pendingAttribution={};return}r.pendingAttribution=r.mergeAttributionUpdates(r.pendingAttribution,i)}}static flushPendingAttribution(){const e=r.storage,t=r.config;if(!e||!t||typeof window>"u")return;const i=ne(window.location.search,t),n=r.mergeAttributionUpdates(r.pendingAttribution,i);Object.keys(n).length>0&&e.update(n),r.pendingAttribution={}}static shouldPersistAttribution(e,t){return t.require_consent??!1?e.getConsentStatus()==="granted":!0}static mergeAttributionUpdates(e,t){return{...e,...t,query_params:{...e.query_params??{},...t.query_params??{}}}}static installExtendedAutocapture(e){if(!r.client||typeof document>"u")return;const t=e.autocapture;t&&(t.click&&document.addEventListener("click",i=>{const n=i.target;if(!n)return;const o=typeof t.click=="object"?t.click.selector:void 0,a=o?n.closest(o):n.closest("[data-mark-event]");if(!a)return;const c=a.getAttribute("data-mark-event")||"click";r.client?.track(c,{element_id:a.id||void 0,element_classes:a.className||void 0,text:a.textContent?.trim().slice(0,120)||void 0,href:a.href||void 0})}),t.form_submit&&document.addEventListener("submit",i=>{const n=i.target;n&&r.client?.track("form_submit",{form_id:n.id||void 0,form_name:n.name||void 0,action:n.action||void 0})}),t.outbound_link&&document.addEventListener("click",i=>{const n=i.target?.closest("a[href]");if(!(!n||!n.href))try{const o=new URL(n.href,window.location.href),a=new URL(window.location.href);o.origin!==a.origin&&r.client?.trackWithOptions("outbound_link_click",{href:o.toString()},{preferBeacon:!0})}catch{}}),t.scroll_depth&&r.client&&Je(r.client),t.page_engagement&&r.client&&Ze(r.client,Xe(t.page_engagement)),t.web_vitals&&Promise.resolve().then(()=>ct).then(i=>{const n=o=>{r.client?.track("web_vital",{metric:o.name,value:o.value,rating:o.rating,metric_id:o.id})};i.onLCP(n),i.onCLS(n),i.onINP(n),i.onTTFB(n)}).catch(()=>{e.debug&&console.warn("[Mark] web-vitals package not available; skipping autocapture.web_vitals.")}))}}typeof window<"u"&&(window.Mark=r);let ue=-1;const b=s=>{addEventListener("pageshow",e=>{e.persisted&&(ue=e.timeStamp,s(e))},!0)},p=(s,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((c,l)=>c>l[1]?"poor":c>l[0]?"needs-improvement":"good")(e.value,t),s(e)))}},$=s=>{requestAnimationFrame(()=>requestAnimationFrame(s))},V=()=>{const s=performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},k=()=>V()?.activationStart??0,g=(s,e=-1)=>{const t=V();let i="navigate";return ue>=0?i="back-forward-cache":t&&(document.prerendering||k()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:s,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},z=new WeakMap;function j(s,e){return z.get(s)||z.set(s,new e),z.get(s)}class et{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const D=(s,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(s)){const i=new PerformanceObserver(n=>{queueMicrotask(()=>{e(n.getEntries())})});return i.observe({type:s,buffered:!0,...t}),i}}catch{}},Y=s=>{let e=!1;return()=>{e||(s(),e=!0)}};let _=-1;const le=new Set,fe=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,Q=s=>{if(document.visibilityState==="hidden"){if(s.type==="visibilitychange")for(const e of le)e();isFinite(_)||(_=s.type==="visibilitychange"?s.timeStamp:0,removeEventListener("prerenderingchange",Q,!0))}},B=()=>{if(_<0){const s=k();_=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(t=>t.name==="hidden"&&t.startTime>=s)?.startTime)??fe(),addEventListener("visibilitychange",Q,!0),addEventListener("prerenderingchange",Q,!0),b(()=>{setTimeout(()=>{_=fe()})})}return{get firstHiddenTime(){return _},onHidden(s){le.add(s)}}},R=s=>{document.prerendering?addEventListener("prerenderingchange",s,!0):s()},W=[1800,3e3],he=(s,e={})=>{R(()=>{const t=B();let i,n=g("FCP");const o=D("paint",a=>{for(const c of a)c.name==="first-contentful-paint"&&(o.disconnect(),c.startTime<t.firstHiddenTime&&(n.value=Math.max(c.startTime-k(),0),n.entries.push(c),i(!0)))});o&&(i=p(s,n,W,e.reportAllChanges),b(a=>{n=g("FCP"),i=p(s,n,W,e.reportAllChanges),$(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},G=[.1,.25],tt=(s,e={})=>{const t=B();he(Y(()=>{let i,n=g("CLS",0);const o=j(e,et),a=l=>{for(const u of l)o.h(u);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},c=D("layout-shift",a);c&&(i=p(s,n,G,e.reportAllChanges),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),b(()=>{o.i=0,n=g("CLS",0),i=p(s,n,G,e.reportAllChanges),$(i)}),setTimeout(i))}))};let pe=0,J=1/0,O=0;const it=s=>{for(const e of s)e.interactionId&&(J=Math.min(J,e.interactionId),O=Math.max(O,e.interactionId),pe=O?(O-J)/7+1:0)};let X;const ge=()=>X?pe:performance.interactionCount??0,nt=()=>{"interactionCount"in performance||X||(X=D("event",it,{durationThreshold:0}))};let me=0;class st{l=[];u=new Map;m;p;v(){me=ge(),this.l.length=0,this.u.clear()}T(){const e=Math.min(this.l.length-1,Math.floor((ge()-me)/50));return this.l[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;const t=this.l.at(-1);let i=this.u.get(e.interactionId);if(i||this.l.length<10||e.duration>t.L){if(i?e.duration>i.L?(i.entries=[e],i.L=e.duration):e.duration===i.L&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],L:e.duration},this.u.set(i.id,i),this.l.push(i)),this.l.sort((n,o)=>o.L-n.L),this.l.length>10){const n=this.l.splice(10);for(const o of n)this.u.delete(o.id)}this.p?.(i)}}}const ye=s=>{const e=globalThis.requestIdleCallback||setTimeout,t=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState==="hidden")s();else{const i=Y(s);let n=-1;const o=()=>{t(n),i()};addEventListener("visibilitychange",o,{once:!0,capture:!0}),n=e(()=>{removeEventListener("visibilitychange",o,{capture:!0}),i()})}},Z=[200,500],rt=(s,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const t=B();R(()=>{nt();let i,n=g("INP");const o=j(e,st),a=l=>{ye(()=>{for(const d of l)o.h(d);const u=o.T();u&&u.L!==n.value&&(n.value=u.L,n.entries=u.entries,i())})},c=D("event",a,{durationThreshold:e.durationThreshold??40});i=p(s,n,Z,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),b(()=>{o.v(),n=g("INP"),i=p(s,n,Z,e.reportAllChanges)}))})};class ot{m;h(e){this.m?.(e)}}const ee=[2500,4e3],at=(s,e={})=>{R(()=>{const t=B();let i,n=g("LCP");const o=j(e,ot),a=l=>{e.reportAllChanges||(l=l.slice(-1));for(const u of l)o.h(u),u.startTime<t.firstHiddenTime&&(n.value=Math.max(u.startTime-k(),0),n.entries=[u],i())},c=D("largest-contentful-paint",a);if(c){i=p(s,n,ee,e.reportAllChanges);const l=Y(()=>{a(c.takeRecords()),c.disconnect(),i(!0)}),u=d=>{d.isTrusted&&(ye(l),removeEventListener(d.type,u,{capture:!0}))};for(const d of["keydown","click","visibilitychange"])addEventListener(d,u,{capture:!0});b(d=>{n=g("LCP"),i=p(s,n,ee,e.reportAllChanges),$(()=>{n.value=performance.now()-d.timeStamp,i(!0)})})}})},te=[800,1800],ie=s=>{document.prerendering?R(()=>ie(s)):document.readyState!=="complete"?addEventListener("load",()=>ie(s),!0):setTimeout(s)},ct=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:G,FCPThresholds:W,INPThresholds:Z,LCPThresholds:ee,TTFBThresholds:te,onCLS:tt,onFCP:he,onINP:rt,onLCP:at,onTTFB:(s,e={})=>{let t=g("TTFB"),i=p(s,t,te,e.reportAllChanges);ie(()=>{const n=V();n&&(t.value=Math.max(n.responseStart-k(),0),t.entries=[n],i(!0),b(()=>{t=g("TTFB",0),i=p(s,t,te,e.reportAllChanges),i(!0)}))})}},Symbol.toStringTag,{value:"Module"}));y.Mark=r,y.default=r,Object.defineProperties(y,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
1
|
+
(function(m,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(m=typeof globalThis<"u"?globalThis:m||self,w(m.Mark={}))})(this,(function(m){"use strict";const w="https://ingest.onelence.com";class y extends Error{status;retryAfterMs;constructor(e,t={}){super(e),this.name="TransportError",this.status=t.status,this.retryAfterMs=t.retryAfterMs}}function be(s){return!(typeof s!="number"||s<400||s>=500||s===408||s===429)}function Ae(s){if(!s)return;const e=s.trim();if(!e)return;const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t*1e3);const i=Date.parse(e);if(Number.isFinite(i)){const n=i-Date.now();return n>0?n:0}}const Ie=5,Se=300,Te=15e3,Ee=2880*60*1e3;class xe{constructor(e,t={}){this.transport=e,this.maxAttempts=t.maxAttempts??Ie,this.baseBackoffMs=t.baseBackoffMs??Se,this.maxBackoffMs=t.maxBackoffMs??Te,this.maxItemAgeMs=t.maxItemAgeMs??Ee,this.debug=t.debug??!1,this.loadPersisted=t.loadPersisted,this.savePersisted=t.savePersisted,this.onError=t.onError;const i=this.loadPersisted?.()??[];if(i.length>0){const n=Date.now();for(const o of i){const a=o.enqueuedAt??n;if(n-a>this.maxItemAgeMs){this.dropped+=1;continue}this.queue.push({...o,enqueuedAt:a})}this.persist()}}queue=[];flushing=!1;sent=0;failed=0;dropped=0;maxAttempts;baseBackoffMs;maxBackoffMs;maxItemAgeMs;debug;loadPersisted;savePersisted;onError;enqueue(e,t){this.queue.push({path:e,data:t,attempts:0,nextAttemptAt:Date.now(),enqueuedAt:Date.now()}),this.persist(),this.process()}async flush(){await this.process(!0),await this.transport.flush?.()}drainViaBeacon(){if(this.queue.length===0)return;const e=this.queue.splice(0,this.queue.length);this.persist();for(const t of e){const i={...t.data};delete i.__prefer_beacon;try{this.transport.send(t.path,i,{preferBeacon:!0})}catch{}}}getStats(){return{queued:this.queue.length,sent:this.sent,failed:this.failed,dropped:this.dropped}}clear(){this.queue.splice(0,this.queue.length),this.persist()}persist(){this.savePersisted?.(this.queue)}evictExpired(){if(this.queue.length===0)return;const t=Date.now()-this.maxItemAgeMs;let i=0;for(let n=this.queue.length-1;n>=0;n-=1)this.queue[n].enqueuedAt<=t&&(this.queue.splice(n,1),this.dropped+=1,i+=1);i>0&&this.persist()}async process(e=!1){if(!this.flushing){this.flushing=!0;try{for(this.evictExpired();this.queue.length>0;){const t=this.queue[0];if(!e&&t.nextAttemptAt>Date.now())break;try{const i={...t.data},n=i.__prefer_beacon===!0;delete i.__prefer_beacon,await this.transport.send(t.path,i,{preferBeacon:n}),this.queue.shift(),this.sent+=1,this.persist()}catch(i){this.failed+=1,this.onError?.(i,t.data);const n=i instanceof y?i.status:void 0;if(be(n)){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after non-retriable status",n,t.path);continue}if(t.attempts+=1,t.attempts>=this.maxAttempts){this.queue.shift(),this.dropped+=1,this.persist(),this.debug&&console.error("[Mark] Dropping event after max retries",t.path,i);continue}const o=i instanceof y?i.retryAfterMs:void 0;let a;if(typeof o=="number")a=Math.min(this.maxBackoffMs,Math.max(0,o));else{const c=Math.random()*this.baseBackoffMs;a=Math.min(this.maxBackoffMs,this.baseBackoffMs*2**(t.attempts-1)+c)}t.nextAttemptAt=Date.now()+a,this.persist();break}}}finally{this.flushing=!1}}}}const Ce=256;function F(s){if(typeof s!="string")return;const e=s.trim();if(!(!e||e.length>Ce)&&!e.includes("@")&&!/\s/.test(e))return e}const Le=new Set(["event_name","user_id","consent_state","source","is_conversion"]),ke=new Set(["user_id","visitor_id","click_id","campaign_id","query","consent_state","source"]);class Pe{constructor(e,t){this.deps=t,this.validateConfig(e),this.config={endpoint:e.endpoint??w,...e,include_page_context:e.include_page_context??!0},this.consentRequirement=e.require_consent??!1,this.siteId=e.site_id,this.siteHost=e.site_host,this.sessionTimeoutMs=e.session_timeout_ms??1800*1e3,this.queue=new xe(this.deps.transport,{debug:this.config.debug,loadPersisted:()=>this.deps.storage.getOutbox?.()??[],savePersisted:i=>this.deps.storage.setOutbox?.(i),onError:(i,n)=>this.config.on_error?.(i,n)}),this.warnMisconfiguredSiteHost(),this.subscribeTcf()}config;consentRequirement;siteId;siteHost;queue;sessionTimeoutMs;batchTimer=null;batchedEvents=[];tcfCachedAllowed=!1;drainViaBeacon(){this.flushBatch(),this.queue.drainViaBeacon()}kickQueue(){this.queue.flush()}track(e,t={}){return this.trackInternal(e,t,!1)}trackInternal(e,t={},i=!1,n){if(!e)return this.config.debug&&console.warn("[Mark] track called without event name"),!1;if(!this.hasConsent()||this.isDntBlocked())return this.config.debug&&console.warn("[Mark] Tracking blocked due to consent requirement."),!1;if(!i&&!this.shouldSampleTrack())return!0;const o=this.sanitizeTrackData(t),a={...o};"query"in a&&delete a.query,"site_id"in a&&delete a.site_id,"site_host"in a&&delete a.site_host;const c={event_name:e,message_id:this.createMessageId(),...this.getIdentityFields(o),...a};i&&(c.is_conversion=!0);const l=o.site_id??this.siteId,u=o.site_host??this.siteHost;l&&(c.site_id=l),u&&(c.site_host=u),this.config.include_page_context&&typeof window<"u"&&(this.applyPageContext(c),!u&&c.site&&(c.site_host=c.site)),this.applyInternalFlag(c,o.is_internal);const d=this.config.before_send?this.config.before_send(c):c;return d?(this.ensureSession(),this.applySessionFields(d),this.config.batching?.enabled&&!i&&!n?.preferBeacon?(this.enqueueBatch(d),!0):(this.queue.enqueue("/event",{...d,__prefer_beacon:n?.preferBeacon===!0}),!0)):!0}identify(e,t={}){if(!e){this.config.debug&&console.warn("[Mark] identify called without userId");return}if(!this.hasConsent()||this.isDntBlocked()){this.config.debug&&console.warn("[Mark] Identify blocked due to consent requirement.");return}this.deps.storage.update({user_id:e});const i={user_id:e,message_id:this.createMessageId(),...this.sanitizeIdentifyTraits(t),...this.getIdentityFields()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&(this.ensureSession(),this.applySessionFields(n),this.queue.enqueue("/identify",n))}conversion(e,t={}){return this.trackInternal(e,t,!0)}trackWithOptions(e,t={},i){return this.trackInternal(e,t,!1,i)}getVisitorId(){return this.deps.storage.getVisitorId()}setVisitorId(e){const t=F(e);return t?this.deps.storage.setVisitorId?this.deps.storage.setVisitorId(t):(this.deps.storage.getVisitorId()===t||this.deps.storage.update({visitor_id:t}),!0):(this.config.debug&&console.warn("[Mark] setVisitorId called with an invalid visitor id."),!1)}setConsent(e){const t=this.deps.storage.getConsentStatus();this.deps.storage.setConsentStatus(e),e==="denied"?(this.deps.storage.clearAttribution?.(),this.deps.storage.clearCookieVisitorId?.(),this.deps.storage.setInternal?.(!1)):e==="granted"&&t==="denied"&&this.config.rotate_visitor_on_consent_change&&this.deps.storage.rotateVisitorId?.();const i={visitor_id:this.deps.storage.getVisitorId(),consent_state:e,source:"sdk",message_id:this.createMessageId()};this.siteId&&(i.site_id=this.siteId),this.siteHost&&(i.site_host=this.siteHost),this.applyInternalFlag(i);const n=this.config.before_send?this.config.before_send(i):i;n&&this.queue.enqueue("/consent",n)}reset(){this.deps.storage.update({user_id:void 0,last_click_id:void 0,campaign_id:void 0,query_params:void 0,session_id:void 0,session_started_at:void 0,last_activity_at:void 0,is_internal:void 0}),this.deps.storage.rotateVisitorId?.()}setInternal(e){this.deps.storage.setInternal?.(!!e)}getInternal(){return!!this.deps.storage.getInternal?.()}flush(){return this.flushBatch(),this.queue.flush()}getStats(){return this.queue.getStats()}applyInternalFlag(e,t){if(t===!1){delete e.is_internal;return}const i=this.deps.storage.getInternal?.()===!0;t===!0||i?e.is_internal=!0:delete e.is_internal}getIdentityFields(e){const t=e?.visitor_id??this.deps.storage.getVisitorId(),i=e?.user_id??this.deps.storage.getUserId?.(),n=e?.click_id??this.deps.storage.getLastClickId(),o=e?.campaign_id??this.deps.storage.getCampaignId(),a=e?.session_id??this.deps.storage.getSessionId?.(),c=this.deps.storage.getQueryParams()??{},l=e?.query??{},u={...c,...l},d={};t&&(d.visitor_id=t),i&&(d.user_id=i),n&&(d.click_id=n),o&&(d.campaign_id=o),a&&(d.session_id=a);const h=this.deps.storage.getSessionStartedAt?.();return a&&h&&(d.session_started_at=h,d.session_elapsed_ms=Date.now()-Date.parse(h)),Object.keys(u).length>0&&(d.query=u),d}applySessionFields(e){if(!e.session_id){const i=this.deps.storage.getSessionId?.(),n=this.deps.storage.getSessionStartedAt?.();i&&(e.session_id=i),n&&(e.session_started_at=n)}const t=e.session_started_at;e.session_id&&typeof t=="string"&&(e.session_elapsed_ms=Date.now()-Date.parse(t))}hasConsent(){if(this.config.consent_source?.type==="tcf"&&typeof window<"u"&&!this.tcfCachedAllowed)return!1;if(!this.consentRequirement)return!0;const t=this.deps.storage.getConsentStatus();return this.consentRequirement==="auto",t==="granted"}sanitizeTrackData(e){const t={};for(const[i,n]of Object.entries(e))Le.has(i)||(t[i]=n);return t}sanitizeIdentifyTraits(e){const t={};for(const[i,n]of Object.entries(e))ke.has(i)||(t[i]=n);return t}validateConfig(e){if(!e.key||!e.key.trim())throw new Error("[Mark] `key` must be a non-empty string.");if(e.endpoint)try{new URL(e.endpoint)}catch{throw new Error("[Mark] `endpoint` must be a valid absolute URL.")}if(typeof e.site_id=="string"&&!e.site_id.trim())throw new Error("[Mark] `site_id` cannot be an empty string.");if(typeof e.site_host=="string"&&!e.site_host.trim())throw new Error("[Mark] `site_host` cannot be an empty string.");if(e.visitor_id!==void 0&&!F(e.visitor_id))throw new Error("[Mark] `visitor_id` must be a non-empty string (max 256 characters).")}applyPageContext(e){typeof document>"u"||(e.site||(e.site=window.location.host),e.page||(e.page=window.location.pathname),e.title||(e.title=document.title),!e.referrer&&document.referrer&&(e.referrer=this.scrubReferrer(document.referrer)))}enqueueBatch(e){this.batchedEvents.push(e);const t=this.config.batching?.max_size??20;if(this.batchedEvents.length>=t){this.flushBatch();return}if(!this.batchTimer){const i=this.config.batching?.flush_interval_ms??2e3;this.batchTimer=setTimeout(()=>{this.batchTimer=null,this.flushBatch()},i)}}flushBatch(){if(this.batchedEvents.length===0)return;const e=this.config.batching?.endpoint_path??"/events",t=this.batchedEvents.splice(0,this.batchedEvents.length);this.queue.enqueue(e,{events:t,message_id:this.createMessageId()})}createMessageId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`msg_${Date.now()}_${Math.random().toString(16).slice(2)}`}ensureSession(){const e=Date.now(),t=this.deps.storage.getSessionId?.(),i=this.deps.storage.getLastActivityAt?.(),n=i?Date.parse(i):0;if(!t||!n||e-n>=this.sessionTimeoutMs||this.crossedUtcDay(n,e)){const a=this.createMessageId(),c=new Date(e).toISOString();this.deps.storage.update({session_id:a,session_started_at:c,last_activity_at:c});return}this.deps.storage.update({last_activity_at:new Date(e).toISOString()})}crossedUtcDay(e,t){const i=new Date(e),n=new Date(t);return i.getUTCFullYear()!==n.getUTCFullYear()||i.getUTCMonth()!==n.getUTCMonth()||i.getUTCDate()!==n.getUTCDate()}shouldSampleTrack(){return typeof this.config.sample_rate!="number"?!0:this.config.sample_rate<=0?!1:this.config.sample_rate>=1?!0:Math.random()<=this.config.sample_rate}isDntBlocked(){if(!this.config.honor_dnt||typeof navigator>"u")return!1;const e=navigator.doNotTrack,t=navigator.globalPrivacyControl;return e==="1"||t===!0}scrubReferrer(e){try{const t=new URL(e);if(typeof window>"u")return e;const i=new URL(window.location.href);return t.origin!==i.origin?(t.search="",t.toString()):e}catch{return e}}warnMisconfiguredSiteHost(){!this.config.debug||!this.siteHost||typeof window>"u"||(window.location.host!==this.siteHost&&console.warn("[Mark] config.site_host does not match current host",{expected:this.siteHost,actual:window.location.host}),this.siteId&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(this.siteId)&&console.warn("[Mark] config.site_id does not look like UUID v4",this.siteId))}subscribeTcf(){const e=this.config.consent_source;if(e?.type!=="tcf"||typeof window>"u")return;const t=e.purposes,i=n=>{try{const o=window;if(typeof o.__tcfapi!="function"){n>0&&setTimeout(()=>i(n-1),200);return}o.__tcfapi("addEventListener",2,(a,c)=>{if(!c||!a){this.tcfCachedAllowed=!1;return}if(a.gdprApplies===!1){this.tcfCachedAllowed=!0;return}const l=a.purpose?.consents??{};this.tcfCachedAllowed=t.every(u=>l[String(u)]===!0)})}catch{this.tcfCachedAllowed=!1}};i(10)}}class De{config;endpoint;pending=new Set;constructor(e){this.config=e,this.endpoint=e.endpoint??w}async send(e,t,i){const n=this.sendInternal(e,t,i);this.pending.add(n);try{await n}finally{this.pending.delete(n)}}async flush(){this.pending.size!==0&&await Promise.allSettled(Array.from(this.pending))}async sendInternal(e,t,i){const n=this.joinUrl(this.endpoint,e),o=this.config.key,a={"Content-Type":"application/json",[o.startsWith("sk_")?"x-secret-key":"x-publishable-key"]:o};if(this.config.debug&&console.log("[Mark] Sending",n,t),typeof fetch!="function")throw this.config.debug&&console.error("[Mark] Global fetch is not available in this runtime."),new y("[Mark] Global fetch is not available in this runtime.");const c=JSON.stringify(t),l=this.config.request_timeout_ms??1e4,u=new AbortController;let d=!1;const h=setTimeout(()=>{d=!0,u.abort()},l);try{const f=await fetch(n,{method:"POST",headers:a,body:c,keepalive:i?.preferBeacon===!0,signal:u.signal});if(!f.ok){const b=await this.readErrorSnippet(f),U=Ae(f.headers.get("Retry-After"));throw this.config.debug&&console.error("[Mark] Request rejected",{url:n,status:f.status,statusText:f.statusText,body:b,retryAfterMs:U}),new y(`[Mark] Request rejected with status ${f.status}: ${b}`,{status:f.status,retryAfterMs:U})}}catch(f){if(this.config.debug&&console.error("[Mark] Failed to send",n,f),f instanceof y)throw f;if(d)throw new y(`[Mark] Request timed out after ${l}ms`,{status:408});const b=f instanceof Error?f.message:String(f);throw new y(`[Mark] Network error: ${b}`)}finally{clearTimeout(h)}}joinUrl(e,t){const i=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${i}/${n}`}async readErrorSnippet(e){try{return(await e.text()).slice(0,300)}catch{return""}}}const qe="crelora_mark_data",Ue="crelora_mark_outbox",K="crelora_mark_vid";class Fe{data;storageKey;outboxKey;options;bridgeFrame;bridgeReady=!1;bridgeOrigin;constructor(e){if(this.options=e??{},this.storageKey=this.options.storageKey??qe,this.outboxKey=this.options.outboxKey??Ue,typeof window>"u"){this.data={};return}this.data=this.load();const t=F(this.options.seed_visitor_id);!this.data.visitor_id&&t&&(this.data.visitor_id=t,this.save()),this.data.visitor_id||(this.data.visitor_id=this.generateUUID(),this.save()),typeof window<"u"&&this.options.bridge?.url&&this.setupBridge(this.options.bridge),window.addEventListener("storage",this.handleStorageEvent)}getVisitorId(){return this.data.visitor_id}getLastClickId(){return this.data.last_click_id}getCampaignId(){return this.data.campaign_id}getQueryParams(){return this.data.query_params}getConsentStatus(){return this.data.consent_status}getUserId(){return this.data.user_id}getSessionId(){return this.data.session_id}getSessionStartedAt(){return this.data.session_started_at}getLastActivityAt(){return this.data.last_activity_at}getInternal(){return this.data.is_internal}setInternal(e){e?this.update({is_internal:!0}):this.update({is_internal:void 0})}update(e){this.data={...this.data,...e},this.save()}setConsentStatus(e){this.data.consent_status=e,this.save()}clearAttribution(){this.update({last_click_id:void 0,campaign_id:void 0,query_params:void 0})}clearCookieVisitorId(){this.setCookie(K,"",-1)}rotateVisitorId(){this.update({visitor_id:this.generateUUID()})}setVisitorId(e){const t=F(e);return t?(this.data.visitor_id===t||this.update({visitor_id:t}),!0):!1}getOutbox(){if(typeof window>"u")return[];try{const e=localStorage.getItem(this.outboxKey);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}setOutbox(e){if(!(typeof window>"u"))try{localStorage.setItem(this.outboxKey,JSON.stringify(e.slice(-200)))}catch{}}load(){if(typeof window>"u")return{};try{const t=localStorage.getItem(this.storageKey);if(t)return JSON.parse(t)}catch{}const e=this.getCookie(K);return e?{visitor_id:e}:{}}save(){if(!(typeof window>"u")){try{localStorage.setItem(this.storageKey,JSON.stringify(this.data))}catch{}this.data.visitor_id&&this.isCookieEnabled()&&(this.setCookie(K,this.data.visitor_id,365),this.options.bridge?.url&&this.bridgeReady&&this.postBridgeMessage({type:"MARK_SYNC_UPDATE",visitorId:this.data.visitor_id}))}}getCookie(e){if(typeof document>"u")return null;try{const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));if(t)return t[2]}catch{}return null}setCookie(e,t,i){if(!(typeof document>"u"))try{const n=new Date(Date.now()+i*24*60*60*1e3),o=this.options.cookie_domain?`;domain=${this.options.cookie_domain}`:"";document.cookie=`${e}=${t};expires=${n.toUTCString()};path=/;SameSite=Lax${o}`}catch{}}generateUUID(){if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=(Date.now()+Math.random()*16)%16|0;return(e==="x"?t:t&3|8).toString(16)})}isCookieEnabled(){return this.options.mode?this.options.mode==="single"||this.options.mode==="subdomain":!0}setupBridge(e){if(typeof document>"u")return;let t;try{t=new URL(e.url,window.location.href)}catch{return}this.bridgeOrigin=t.origin,this.bridgeFrame=document.createElement("iframe"),this.bridgeFrame.style.display="none",this.bridgeFrame.setAttribute("aria-hidden","true"),this.bridgeFrame.src=t.toString();const i=e.timeout_ms??3e3,n=setTimeout(()=>{window.removeEventListener("message",this.handleBridgeMessage)},i);window.addEventListener("message",this.handleBridgeMessage);const o=()=>{this.bridgeFrame&&document.body&&document.body.appendChild(this.bridgeFrame)};document.body?o():document.addEventListener("DOMContentLoaded",o,{once:!0}),this.bridgeFrame.addEventListener("load",()=>{clearTimeout(n),this.bridgeReady=!0,this.postBridgeMessage({type:"MARK_SYNC_REQUEST",visitorId:this.data.visitor_id})})}handleBridgeMessage=e=>{if(!this.bridgeFrame?.contentWindow||e.source!==this.bridgeFrame.contentWindow||!this.isDomainAllowed(e.origin))return;const t=e.data;!t||!t.type||t.type==="MARK_SYNC_RESPONSE"&&t.visitorId&&t.visitorId!==this.data.visitor_id&&(this.data.visitor_id=t.visitorId,this.save())};postBridgeMessage(e){this.bridgeFrame?.contentWindow&&this.bridgeFrame.contentWindow.postMessage(e,this.bridgeOrigin??"*")}isDomainAllowed(e){try{const t=new URL(e);if(this.options.allowed_domains?.length)return this.options.allowed_domains.some(n=>t.hostname===n||t.hostname.endsWith(`.${n}`));if(!this.bridgeOrigin)return!1;const i=new URL(this.bridgeOrigin);return t.hostname===i.hostname}catch{return!1}}handleStorageEvent=e=>{if(!(e.key!==this.storageKey||typeof e.newValue!="string"))try{this.data=JSON.parse(e.newValue)}catch{}}}const Re=["click_id","ch_click_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Be=["cid","campaign_id"],Oe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","ref","referral","affiliate_id","click_id","ch_click_id","cid","campaign_id","gclid","gbraid","wbraid","dclid","msclkid","fbclid","ttclid","twclid","li_fat_id"],Ne={referral:"ref",affiliate_id:"ref",ch_click_id:"click_id",cid:"campaign_id"},Me=["email","phone","token","auth","password","code"],He=30,Ve=256;function oe(s,e={}){const t=new URLSearchParams(s),i=ze(t),n=ae(i,Re),o=ae(i,Be),a=Ke(t,e),c={};return n&&(c.last_click_id=n),o&&(c.campaign_id=o),Object.keys(a).length>0&&(c.query_params=a),c}function Ke(s,e){const t={},i=new Set(ce(e.query_param_denylist,Me)),n=de(e.max_captured_query_params,He),o=de(e.max_query_param_value_length,Ve),c=e.capture_all_query_params??!1?null:new Set([...Oe.map(A),...ce(e.capture_query_params,[])]);for(const[l,u]of s.entries()){const d=A(l);if(!d)continue;const h=Ne[d]??d;if(i.has(d)||i.has(h)||c&&!c.has(d))continue;const f=u.trim();if(f){if(!(h in t)&&Object.keys(t).length>=n)break;t[h]=f.slice(0,o)}}return t}function ae(s,e){for(const t of e){const i=A(t),n=s[i]?.trim();if(n)return n}}function ze(s){const e={};for(const[t,i]of s.entries()){const n=A(t);!n||n in e||(e[n]=i)}return e}function A(s){return s.trim().toLowerCase()}function ce(s,e){const t=s??e,i=new Set;for(const n of t){if(typeof n!="string")continue;const o=A(n);o&&i.add(o)}return Array.from(i)}function de(s,e){if(typeof s!="number"||!Number.isFinite(s))return e;const t=Math.floor(s);return t<0?e:t}function R(s){return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}function $e(s){if(!s||s==="?")return"";const e=s.startsWith("?")?s.slice(1):s;if(!e)return"";const t=new URLSearchParams(e),i=[];t.forEach((a,c)=>{i.push([c,a])}),i.sort(([a,c],[l,u])=>{const d=a.localeCompare(l);return d!==0?d:c.localeCompare(u)});const n=new URLSearchParams;for(const[a,c]of i)n.append(a,c);const o=n.toString();return o===""?"":`?${o}`}function z(s){const e=R(s.pathname),t=$e(s.search);return`${s.origin}${e}${t}${s.hash}`}let B=!1,I=null;const S=[],T=[],E=[];let x=null,C=null,L=null,k=null,P=null;function O(){if(typeof window>"u")return;const s=z(window.location);if(s===I)return;const e={previousKey:I,nextKey:s};for(const t of S)t(e);I=s;for(const t of T)t(e)}function je(){for(const s of E)s()}function Ye(s={}){if(B||typeof window>"u"||typeof document>"u")return;B=!0;const e=s.trackRouteChanges??!0;I=z(window.location),P=je,window.addEventListener("pagehide",P),e&&(x=history.pushState,C=history.replaceState,history.pushState=function(...t){const i=x.apply(this,t);return O(),i},history.replaceState=function(...t){const i=C.apply(this,t);return O(),i},L=O,window.addEventListener("popstate",L),k=O,window.addEventListener("hashchange",k))}function Qe(s){return S.push(s),()=>{const e=S.indexOf(s);e>=0&&S.splice(e,1)}}function $(s){return T.push(s),()=>{const e=T.indexOf(s);e>=0&&T.splice(e,1)}}function We(s){return E.push(s),()=>{const e=E.indexOf(s);e>=0&&E.splice(e,1)}}function Ge(){!B||typeof window>"u"||(x&&(history.pushState=x),C&&(history.replaceState=C),L&&window.removeEventListener("popstate",L),k&&window.removeEventListener("hashchange",k),P&&window.removeEventListener("pagehide",P),x=null,C=null,L=null,k=null,P=null,S.length=0,T.length=0,E.length=0,I=null,B=!1)}let N=0;function ue(){N=0}function Xe(){return N}function Je(){if(typeof document>"u"||typeof window>"u")return 0;const s=document.documentElement,e=window.scrollY||s.scrollTop,t=Math.max(1,s.scrollHeight-window.innerHeight);return Math.min(100,Math.round(e/t*100))}function le(){const s=Je();return s>N&&(N=s),s}const Ze=[25,50,75,100];function et(s,e=Ze){if(typeof window>"u")return;const t=new Set,i=()=>{t.clear(),ue()};i(),$(()=>{i()}),window.addEventListener("scroll",()=>{const n=le();for(const o of e)n>=o&&!t.has(o)&&(t.add(o),s.track("scroll_depth",{percent:o}))},{passive:!0})}const fe=1e4;function tt(s){return s===!0?{minActiveMs:fe,useBeacon:!0}:{minActiveMs:s.min_active_ms??fe,useBeacon:s.use_beacon!==!1}}function it(s,e){if(typeof window>"u"||typeof document>"u")return;let t=Date.now(),i=0,n=document.visibilityState==="visible"?Date.now():null,o=R(window.location.pathname),a=!1;const c=()=>{n!==null&&(i+=Date.now()-n,n=null)},l=()=>{document.visibilityState==="visible"&&n===null&&(n=Date.now())},u=()=>{document.visibilityState==="visible"?l():c()},d=f=>{if(!a){a=!0;try{if(c(),le(),i<e.minActiveMs){e.debug&&console.debug("[Mark] page_engagement skipped (active time below min_active_ms)",{page:o,active_time_ms:i,min_active_ms:e.minActiveMs});return}const b=Date.now()-t,U={page:o,active_time_ms:i,total_time_ms:b,max_scroll_percent:Xe()};e.useBeacon&&f?s.trackWithOptions("page_engagement",U,{preferBeacon:!0}):s.track("page_engagement",U)}finally{a=!1}}},h=()=>{t=Date.now(),i=0,o=R(window.location.pathname),ue(),l()};h(),Qe(()=>{d(!1),c()}),$(()=>{h()}),We(()=>{d(!0)}),document.addEventListener("visibilitychange",u),window.addEventListener("pageshow",u),window.addEventListener("focus",u),queueMicrotask(u),typeof requestAnimationFrame=="function"&&requestAnimationFrame(u)}class r{static client=null;static storage=null;static config=null;static pageviewTrackerInstalled=!1;static lastPageviewDedupeKey=null;static emitAutoPageview=null;static pendingAttribution={};static beaconDrainHandler=null;static visibilityHandler=null;static onlineHandler=null;static kickTimer=null;static init(e){if(!r.client){const t=new Fe({...e.cross_domain,seed_visitor_id:e.visitor_id}),i=new De(e);r.client=new Pe(e,{storage:t,transport:i}),r.storage=t,r.config=e,r.refreshAttribution(t,e),typeof window<"u"&&(r.installPageLifecycleIfNeeded(e),e.autocapture?.pageview&&r.installPageviewTracking(e,t),r.installExtendedAutocapture(e),r.installLifecycleFlushing())}return r.client}static installLifecycleFlushing(){if(typeof window>"u"||r.beaconDrainHandler)return;const e=()=>{r.client?.drainViaBeacon()},t=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&e()},i=()=>{r.client?.kickQueue()};r.beaconDrainHandler=e,r.visibilityHandler=t,r.onlineHandler=i,typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",t),typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("online",i)),typeof setInterval=="function"&&(r.kickTimer=setInterval(()=>{r.client?.kickQueue()},3e4))}static track(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.track(e,t)}static identify(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.identify(e,t)}static conversion(e,t={}){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.conversion(e,t)}static setConsent(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setConsent(e),e==="granted"&&(r.flushPendingAttribution(),r.emitAutoPageview?.())}static getVisitorId(){if(!(!r.client||!r.storage||!r.config||(r.config.require_consent??!1)&&r.storage.getConsentStatus()!=="granted"))return r.client.getVisitorId()}static setVisitorId(e){return r.client?r.client.setVisitorId(e):(r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first."),!1)}static flush(){return r.client?r.client.flush():Promise.resolve()}static setInternal(e){if(!r.client){r.config?.debug&&console.warn("[Mark] Not initialized. Call init() first.");return}r.client.setInternal(e)}static getInternal(){return r.client?.getInternal()??!1}static reset(){r.client?.reset(),r.pendingAttribution={},r.lastPageviewDedupeKey=null}static getStats(){return r.client?.getStats()??{queued:0,sent:0,failed:0,dropped:0}}static destroy(){typeof window>"u"||(Ge(),r.beaconDrainHandler&&(window.removeEventListener("pagehide",r.beaconDrainHandler),window.removeEventListener("beforeunload",r.beaconDrainHandler)),r.visibilityHandler&&typeof document<"u"&&document.removeEventListener("visibilitychange",r.visibilityHandler),r.onlineHandler&&window.removeEventListener("online",r.onlineHandler),r.kickTimer&&clearInterval(r.kickTimer),r.beaconDrainHandler=null,r.visibilityHandler=null,r.onlineHandler=null,r.kickTimer=null,r.pageviewTrackerInstalled=!1)}static installPageLifecycleIfNeeded(e){const t=e.autocapture;if(!(!!t?.pageview||!!t?.scroll_depth||!!t?.page_engagement))return;const n=e.track_route_changes??!0;Ye({trackRouteChanges:n})}static installPageviewTracking(e,t){if(r.pageviewTrackerInstalled)return;r.pageviewTrackerInstalled=!0;const i=()=>{if(!r.client)return;r.refreshAttribution(t,e);const o=z(window.location);if(o===r.lastPageviewDedupeKey)return;r.client.track("page_view",{site:window.location.host,page:R(window.location.pathname),title:document.title,referrer:document.referrer||void 0})&&(r.lastPageviewDedupeKey=o)};r.emitAutoPageview=i,i(),(e.track_route_changes??!0)&&$(()=>{i()})}static refreshAttribution(e,t){if(typeof window>"u")return;const i=oe(window.location.search,t);if(Object.keys(i).length!==0){if(r.shouldPersistAttribution(e,t)){const n=r.mergeAttributionUpdates(r.pendingAttribution,i);e.update(n),r.pendingAttribution={};return}r.pendingAttribution=r.mergeAttributionUpdates(r.pendingAttribution,i)}}static flushPendingAttribution(){const e=r.storage,t=r.config;if(!e||!t||typeof window>"u")return;const i=oe(window.location.search,t),n=r.mergeAttributionUpdates(r.pendingAttribution,i);Object.keys(n).length>0&&e.update(n),r.pendingAttribution={}}static shouldPersistAttribution(e,t){return t.require_consent??!1?e.getConsentStatus()==="granted":!0}static mergeAttributionUpdates(e,t){return{...e,...t,query_params:{...e.query_params??{},...t.query_params??{}}}}static installExtendedAutocapture(e){if(!r.client||typeof document>"u")return;const t=e.autocapture;t&&(t.click&&document.addEventListener("click",i=>{const n=i.target;if(!n)return;const o=typeof t.click=="object"?t.click.selector:void 0,a=o?n.closest(o):n.closest("[data-mark-event]");if(!a)return;const c=a.getAttribute("data-mark-event")||"click";r.client?.track(c,{element_id:a.id||void 0,element_classes:a.className||void 0,text:a.textContent?.trim().slice(0,120)||void 0,href:a.href||void 0})}),t.form_submit&&document.addEventListener("submit",i=>{const n=i.target;n&&r.client?.track("form_submit",{form_id:n.id||void 0,form_name:n.name||void 0,action:n.action||void 0})}),t.outbound_link&&document.addEventListener("click",i=>{const n=i.target?.closest("a[href]");if(!(!n||!n.href))try{const o=new URL(n.href,window.location.href),a=new URL(window.location.href);o.origin!==a.origin&&r.client?.trackWithOptions("outbound_link_click",{href:o.toString()},{preferBeacon:!0})}catch{}}),t.scroll_depth&&r.client&&et(r.client),t.page_engagement&&r.client&&it(r.client,{...tt(t.page_engagement),debug:e.debug}),t.web_vitals&&Promise.resolve().then(()=>lt).then(i=>{const n=o=>{r.client?.track("web_vital",{metric:o.name,value:o.value,rating:o.rating,metric_id:o.id})};i.onLCP(n),i.onCLS(n),i.onINP(n),i.onTTFB(n)}).catch(()=>{e.debug&&console.warn("[Mark] web-vitals package not available; skipping autocapture.web_vitals.")}))}}typeof window<"u"&&(window.Mark=r);let he=-1;const v=s=>{addEventListener("pageshow",e=>{e.persisted&&(he=e.timeStamp,s(e))},!0)},p=(s,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((c,l)=>c>l[1]?"poor":c>l[0]?"needs-improvement":"good")(e.value,t),s(e)))}},j=s=>{requestAnimationFrame(()=>requestAnimationFrame(s))},Y=()=>{const s=performance.getEntriesByType("navigation")[0];if(s&&s.responseStart>0&&s.responseStart<performance.now())return s},D=()=>Y()?.activationStart??0,g=(s,e=-1)=>{const t=Y();let i="navigate";return he>=0?i="back-forward-cache":t&&(document.prerendering||D()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:s,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},Q=new WeakMap;function W(s,e){return Q.get(s)||Q.set(s,new e),Q.get(s)}class nt{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const q=(s,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(s)){const i=new PerformanceObserver(n=>{queueMicrotask(()=>{e(n.getEntries())})});return i.observe({type:s,buffered:!0,...t}),i}}catch{}},G=s=>{let e=!1;return()=>{e||(s(),e=!0)}};let _=-1;const pe=new Set,ge=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,X=s=>{if(document.visibilityState==="hidden"){if(s.type==="visibilitychange")for(const e of pe)e();isFinite(_)||(_=s.type==="visibilitychange"?s.timeStamp:0,removeEventListener("prerenderingchange",X,!0))}},M=()=>{if(_<0){const s=D();_=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(t=>t.name==="hidden"&&t.startTime>=s)?.startTime)??ge(),addEventListener("visibilitychange",X,!0),addEventListener("prerenderingchange",X,!0),v(()=>{setTimeout(()=>{_=ge()})})}return{get firstHiddenTime(){return _},onHidden(s){pe.add(s)}}},H=s=>{document.prerendering?addEventListener("prerenderingchange",s,!0):s()},J=[1800,3e3],me=(s,e={})=>{H(()=>{const t=M();let i,n=g("FCP");const o=q("paint",a=>{for(const c of a)c.name==="first-contentful-paint"&&(o.disconnect(),c.startTime<t.firstHiddenTime&&(n.value=Math.max(c.startTime-D(),0),n.entries.push(c),i(!0)))});o&&(i=p(s,n,J,e.reportAllChanges),v(a=>{n=g("FCP"),i=p(s,n,J,e.reportAllChanges),j(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},Z=[.1,.25],st=(s,e={})=>{const t=M();me(G(()=>{let i,n=g("CLS",0);const o=W(e,nt),a=l=>{for(const u of l)o.h(u);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},c=q("layout-shift",a);c&&(i=p(s,n,Z,e.reportAllChanges),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),v(()=>{o.i=0,n=g("CLS",0),i=p(s,n,Z,e.reportAllChanges),j(i)}),setTimeout(i))}))};let ye=0,ee=1/0,V=0;const rt=s=>{for(const e of s)e.interactionId&&(ee=Math.min(ee,e.interactionId),V=Math.max(V,e.interactionId),ye=V?(V-ee)/7+1:0)};let te;const we=()=>te?ye:performance.interactionCount??0,ot=()=>{"interactionCount"in performance||te||(te=q("event",rt,{durationThreshold:0}))};let ve=0;class at{l=[];u=new Map;m;p;v(){ve=we(),this.l.length=0,this.u.clear()}T(){const e=Math.min(this.l.length-1,Math.floor((we()-ve)/50));return this.l[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;const t=this.l.at(-1);let i=this.u.get(e.interactionId);if(i||this.l.length<10||e.duration>t.L){if(i?e.duration>i.L?(i.entries=[e],i.L=e.duration):e.duration===i.L&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],L:e.duration},this.u.set(i.id,i),this.l.push(i)),this.l.sort((n,o)=>o.L-n.L),this.l.length>10){const n=this.l.splice(10);for(const o of n)this.u.delete(o.id)}this.p?.(i)}}}const _e=s=>{const e=globalThis.requestIdleCallback||setTimeout,t=globalThis.cancelIdleCallback||clearTimeout;if(document.visibilityState==="hidden")s();else{const i=G(s);let n=-1;const o=()=>{t(n),i()};addEventListener("visibilitychange",o,{once:!0,capture:!0}),n=e(()=>{removeEventListener("visibilitychange",o,{capture:!0}),i()})}},ie=[200,500],ct=(s,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const t=M();H(()=>{ot();let i,n=g("INP");const o=W(e,at),a=l=>{_e(()=>{for(const d of l)o.h(d);const u=o.T();u&&u.L!==n.value&&(n.value=u.L,n.entries=u.entries,i())})},c=q("event",a,{durationThreshold:e.durationThreshold??40});i=p(s,n,ie,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden(()=>{a(c.takeRecords()),i(!0)}),v(()=>{o.v(),n=g("INP"),i=p(s,n,ie,e.reportAllChanges)}))})};class dt{m;h(e){this.m?.(e)}}const ne=[2500,4e3],ut=(s,e={})=>{H(()=>{const t=M();let i,n=g("LCP");const o=W(e,dt),a=l=>{e.reportAllChanges||(l=l.slice(-1));for(const u of l)o.h(u),u.startTime<t.firstHiddenTime&&(n.value=Math.max(u.startTime-D(),0),n.entries=[u],i())},c=q("largest-contentful-paint",a);if(c){i=p(s,n,ne,e.reportAllChanges);const l=G(()=>{a(c.takeRecords()),c.disconnect(),i(!0)}),u=d=>{d.isTrusted&&(_e(l),removeEventListener(d.type,u,{capture:!0}))};for(const d of["keydown","click","visibilitychange"])addEventListener(d,u,{capture:!0});v(d=>{n=g("LCP"),i=p(s,n,ne,e.reportAllChanges),j(()=>{n.value=performance.now()-d.timeStamp,i(!0)})})}})},se=[800,1800],re=s=>{document.prerendering?H(()=>re(s)):document.readyState!=="complete"?addEventListener("load",()=>re(s),!0):setTimeout(s)},lt=Object.freeze(Object.defineProperty({__proto__:null,CLSThresholds:Z,FCPThresholds:J,INPThresholds:ie,LCPThresholds:ne,TTFBThresholds:se,onCLS:st,onFCP:me,onINP:ct,onLCP:ut,onTTFB:(s,e={})=>{let t=g("TTFB"),i=p(s,t,se,e.reportAllChanges);re(()=>{const n=Y();n&&(t.value=Math.max(n.responseStart-D(),0),t.entries=[n],i(!0),v(()=>{t=g("TTFB",0),i=p(s,t,se,e.reportAllChanges),i(!0)}))})}},Symbol.toStringTag,{value:"Module"}));m.Mark=r,m.default=r,Object.defineProperties(m,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
2
2
|
//# sourceMappingURL=browser.umd.js.map
|