@kylelogue/eventfoundry-tracker 0.5.2 → 0.5.3

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.
@@ -1 +1 @@
1
- var EventFoundry=(()=>{var m=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var T=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var P=(e,t,n)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,D=(e,t)=>{for(var n in t||(t={}))T.call(t,n)&&P(e,n,t[n]);if($)for(var n of $(t))Y.call(t,n)&&P(e,n,t[n]);return e};var Q=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0})},X=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of J(t))!T.call(e,r)&&r!==n&&m(e,r,{get:()=>t[r],enumerable:!(o=U(t,r))||o.enumerable});return e};var Z=e=>X(m({},"__esModule",{value:!0}),e);var h=(e,t,n)=>new Promise((o,r)=>{var a=i=>{try{c(n.next(i))}catch(f){r(f)}},s=i=>{try{c(n.throw(i))}catch(f){r(f)}},c=i=>i.done?o(i.value):Promise.resolve(i.value).then(a,s);c((n=n.apply(e,t)).next())});var be={};Q(be,{reloadEventDefinitions:()=>S});var w=null;function E(){return w}function ee(){return["http://localhost","https://eventfoundry.app"]}function te(e){return ee().some(n=>n==="http://localhost"?e.startsWith("http://localhost"):e===n)}function b(){try{return window.self!==window.top}catch(e){return!0}}function O(){b()&&(console.log("EventFoundry: Running in iframe, waiting for editor activation"),window.addEventListener("message",e=>{let t=e.data,n=t==null?void 0:t.type;if(!(!n||!["ENTER_EDIT_MODE","ENABLE_PREVIEW","DISABLE_PREVIEW","RELOAD_CONFIG"].includes(n))){if(!te(e.origin)){console.warn("EventFoundry: Rejected postMessage from untrusted origin:",e.origin);return}switch(w||(w=e.origin,console.log("EventFoundry: Parent origin established:",w)),t.type){case"ENTER_EDIT_MODE":console.log("\u2190 ENTER_EDIT_MODE received"),ne();break;case"ENABLE_PREVIEW":console.log("\u2190 ENABLE_PREVIEW received"),oe();break;case"DISABLE_PREVIEW":console.log("\u2190 DISABLE_PREVIEW received"),re();break;case"RELOAD_CONFIG":console.log("\u2190 RELOAD_CONFIG received"),S();break}}}),setTimeout(()=>{window.parent&&(window.parent.postMessage({type:"IFRAME_READY"},"*"),console.log("\u2192 IFRAME_READY sent to parent"))},100))}function ne(){M()}function oe(){console.log("EventFoundry: Enabling Preview Mode"),k()}function re(){console.log("EventFoundry: Disabling Preview Mode (Edit Mode active)"),R()}var g=null,y=!1,p=null,v=!1;function x(){return y}function I(){return v}function ae(){return["http://localhost","https://eventfoundry.app"]}function se(e){return ae().some(n=>n==="http://localhost"?e.startsWith("http://localhost"):e===n)}function M(){if(y)return;y=!0;let e=document.createElement("style");e.textContent=` .eventfoundry-highlight { outline: 2px solid #3498db !important; outline-offset: 2px; cursor: pointer !important; } .eventfoundry-test-highlight { outline: 3px solid #e74c3c !important; outline-offset: 3px; background-color: rgba(231, 76, 60, 0.1) !important; } .eventfoundry-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 999998; pointer-events: none; cursor: crosshair; } body.eventfoundry-edit-mode, body.eventfoundry-edit-mode * { cursor: crosshair !important; } `,document.head.appendChild(e);let t=document.createElement("div");t.className="eventfoundry-overlay",document.body.appendChild(t),p=t,document.body.classList.add("eventfoundry-edit-mode"),document.body.addEventListener("mouseover",n=>{v||n.target.classList.contains("eventfoundry-overlay")||(g&&g.classList.remove("eventfoundry-highlight"),n.target.classList.add("eventfoundry-highlight"),g=n.target)},!0),document.body.addEventListener("mouseout",n=>{v||n.target.classList.contains("eventfoundry-overlay")||n.target.classList.remove("eventfoundry-highlight")},!0),document.body.addEventListener("click",n=>{if(n.target.classList.contains("eventfoundry-overlay")||v)return;n.preventDefault(),n.stopPropagation();let o=n.target,r="";o.className&&typeof o.className=="string"&&(r=o.className.trim().split(/\s+/).filter(i=>!i.startsWith("eventfoundry-")).join(" "));let a=window.location.pathname+window.location.search+window.location.hash,s={tagName:o.tagName.toLowerCase(),text:o.textContent.trim().substring(0,50),id:o.id,className:r,selector:he(o),page_path:a},c=E();c?(window.parent.postMessage({type:"ELEMENT_SELECTED",element:s},c),console.log("\u2192 ELEMENT_SELECTED sent to parent")):console.warn("EventFoundry: Cannot send ELEMENT_SELECTED - parent origin not established")},!0),window.addEventListener("message",n=>{if(se(n.origin)&&(n.data.type==="HIGHLIGHT_SELECTOR"&&(console.log("\u2190 HIGHLIGHT_SELECTOR received:",n.data.selector),Ee(n.data.selector)),n.data.type==="COUNT_MATCHES")){let o=n.data.selector,r=0;try{r=document.querySelectorAll(o).length}catch(s){r=0}let a=E();a&&window.parent.postMessage({type:"MATCH_COUNT_RESULT",selector:o,count:r},a)}})}function l(e){return e?e.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,"\\$1"):""}function ie(e){return e?!!(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i.test(e)||/\d{13}/.test(e)||/^[a-f0-9]{16,}$/i.test(e)||/-\d{4,}$/.test(e)):!1}function ce(e,t){try{let n=document.querySelectorAll(t);return n.length===1&&n[0]===e}catch(n){return!1}}function N(e){return!e.className||typeof e.className!="string"?[]:e.className.trim().split(/\s+/).filter(t=>t&&!t.startsWith("eventfoundry-"))}function G(e,t=!0){let n=e.parentElement;if(!n)return null;let o=N(n);return t&&o.length>0?`.${l(o[0])}`:n.tagName.toLowerCase()}function d(e,t,n,o){return ce(o,t)?(e.push({selector:t,priority:n}),!0):!1}function le(e){let t=[];if(e.id&&!ie(e.id)){let n=`#${l(e.id)}`;d(t,n,100,e)}return t}function de(e){let t=[],n=Array.from(e.attributes).filter(o=>o.name.startsWith("data-")&&o.value);for(let o of n){let r=`[${o.name}="${l(o.value)}"]`;if(d(t,r,90,e))break}return t}function ue(e){let t=[],n=N(e);if(n.length===0)return t;let o=e.tagName.toLowerCase();for(let r of n){let a=`${o}.${l(r)}`;if(d(t,a,85,e))break}if(n.length>=2){let r=`.${l(n[0])}.${l(n[1])}`;if(d(t,r,82,e),n.length>=3){let a=`.${l(n[0])}.${l(n[1])}.${l(n[2])}`;d(t,a,82,e)}}for(let r of n){let a=`.${l(r)}`;if(d(t,a,80,e))break}return t}function fe(e){let t=[],n=e.tagName.toLowerCase(),o=["type","name","href","role","aria-label"];for(let r of o){let a=e.getAttribute(r);if(a){let s=`${n}[${r}="${l(a)}"]`;if(d(t,s,70,e))break}}return t}function ge(e){let t=[],n=G(e,!0);if(!n)return t;let o=e.tagName.toLowerCase(),r=N(e);if(r.length>0){let s=`${n} .${l(r[0])}`;d(t,s,75,e)}if(r.length>0){let s=`${n} ${o}.${l(r[0])}`;d(t,s,72,e)}let a=`${n} ${o}`;return d(t,a,65,e),t}function ve(e){let t=[],n=e.tagName.toLowerCase(),o=e.parentElement;if(!o)return[{selector:n,priority:10}];let r=G(e,!0),s=Array.from(o.children).indexOf(e)+1,c=`${r} ${n}:nth-child(${s})`;return d(t,c,50,e),t}function he(e){let t=[];return t.push(...le(e)),t.push(...de(e)),t.push(...ue(e)),t.push(...fe(e)),t.push(...ge(e)),t.push(...ve(e)),t.length>0?(t.sort((n,o)=>o.priority-n.priority),t[0].selector):e.tagName.toLowerCase()}function Ee(e){document.querySelectorAll(".eventfoundry-test-highlight").forEach(t=>{t.classList.remove("eventfoundry-test-highlight")});try{let t=document.querySelectorAll(e);t.forEach(n=>{n.classList.add("eventfoundry-test-highlight")}),setTimeout(()=>{t.forEach(n=>{n.classList.remove("eventfoundry-test-highlight")})},3e3)}catch(t){console.error("EventFoundry: Invalid selector",e,t)}}function k(){if(!y){console.warn("EventFoundry: Cannot enable preview - overlay not active");return}v=!0,console.log("EventFoundry: Preview Mode enabled - all interactions allowed"),p&&(p.style.display="none"),document.body.classList.remove("eventfoundry-edit-mode"),g&&(g.classList.remove("eventfoundry-highlight"),g=null)}function R(){if(!y){console.warn("EventFoundry: Cannot disable preview - overlay not active");return}v=!1,console.log("EventFoundry: Preview Mode disabled - Edit Mode active"),p&&(p.style.display=""),document.body.classList.add("eventfoundry-edit-mode")}var j=console.log;function u(e,...t){e&&j&&j(...t)}var F=null;function ye(e){let t=[],n=[];return e.forEach(o=>{try{document.querySelector(o.selector),t.push(o)}catch(r){console.warn(`EventFoundry: Invalid selector "${o.selector}" - ${r.message}`),n.push({selector:o.selector,error:r.message,name:o.name})}}),{validDefs:t,invalidDefs:n}}function C(e,t=!1){if(!e||e.length===0)return!1;F&&F.abort();let{validDefs:n,invalidDefs:o}=ye(e);return n.length===0?(console.error("\u{1F6A8} EventFoundry: No valid event selectors found - tracking disabled!"),console.error("Invalid selectors:",o),!1):(o.length>0&&console.warn(`EventFoundry: ${o.length} of ${e.length} selectors are invalid and will be skipped`),F=new AbortController,document.addEventListener("click",r=>{if(x()&&!I()){u(t,"EventFoundry: Click ignored (editor mode active, not in preview)");return}let a=n.filter(i=>r.target.closest(i.selector)!==null);if(a.length===0){u(t,"EventFoundry: Click on",r.target,"matched 0 events");return}let s=a[0],c=D({event_category:"EventFoundry",event_label:s.name,transport_type:"beacon"},s.gaEventParams);if(u(t,"EventFoundry: Firing event",s.gaEventName,c),!t){if(typeof window.gtag!="function"){console.error("EventFoundry: gtag not available - is GA4 installed?");return}window.gtag("event",s.gaEventName,c)}if(I())try{let i=E();i?(window.parent.postMessage({type:"EVENT_FIRED",timestamp:Date.now(),eventName:s.name,gaEventName:s.gaEventName,selector:s.selector,params:c,pagePath:window.location.pathname},i),console.log("\u2192 EVENT_FIRED sent to parent")):console.warn("EventFoundry: Cannot send EVENT_FIRED - parent origin not established")}catch(i){console.warn("EventFoundry: Failed to send EVENT_FIRED postMessage",i)}a.length>1&&console.warn("EventFoundry: Multiple events matched, only firing first:",a.map(i=>i.name))},{capture:!0,signal:F.signal}),!0)}var K=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",V=K?"http://localhost/api/tracking/events":"https://eventfoundry.app/api/tracking/events";function A(e){return`eventfoundry_definitions_${e}`}function _(e){return`eventfoundry_etag_${e}`}function q(){let e=document.currentScript||document.querySelector("script[data-site-key]");if(!e)return console.error("EventFoundry: Could not find script tag"),null;let t=e.getAttribute("data-dev-mode"),n=t==="false"?!1:K||t==="true";return{siteKey:e.getAttribute("data-site-key"),measurementId:e.getAttribute("data-measurement-id"),devMode:n}}function pe(e){return h(this,null,function*(){if(window.gtag&&typeof window.gtag=="function")return{hasGtag:!0,wasInjected:!1};if(!e)return console.warn("EventFoundry: No GA4 detected and no measurement ID provided. Events will not be tracked."),{hasGtag:!1,wasInjected:!1};let t=document.createElement("script");return t.async=!0,t.src=`https://www.googletagmanager.com/gtag/js?id=${e}`,document.head.appendChild(t),window.dataLayer=window.dataLayer||[],yield new Promise((n,o)=>{let r=!1;t.onload=()=>{r||(r=!0,n())},t.onerror=()=>{r||(r=!0,console.error("EventFoundry: Failed to load gtag script"),o(new Error("gtag script failed to load")))},setTimeout(()=>{r||(r=!0,console.warn("EventFoundry: gtag script load timeout after 10s"),n())},1e4)}).catch(()=>({hasGtag:!1,wasInjected:!1})),typeof window.gtag!="function"?(console.error("EventFoundry: gtag not available after load - events will not fire"),{hasGtag:!1,wasInjected:!1}):(window.gtag("js",new Date),window.gtag("config",e),{hasGtag:!0,wasInjected:!0})})}function W(){return h(this,null,function*(){let e=q();if(!e||!e.siteKey){console.error("EventFoundry: No site key provided");return}let{siteKey:t,measurementId:n,devMode:o}=e;console.log("\u2713 EventFoundry tracker loaded"),b()&&O();let{hasGtag:r,wasInjected:a}=yield pe(n),s=b();if(!r&&!s){console.error("EventFoundry: Cannot track events without GA4");return}r?console.log(a?"\u2713 GA4 injected successfully":"\u2713 GA4 detected"):s&&console.log("\u26A0 GA4 not available - editor mode will use postMessage-based event logging"),u(o,"\u26A0 Dev mode: Events disabled (v0.5.2)"),u(!o,"\u2713 Production mode: Events enabled (v0.5.2)");try{let c=yield L(t),i=c.events;if(!C(i,o)&&c._fromCache){console.log("EventFoundry: Tracking failed with cached data, clearing cache and refetching..."),B(t);let z=(yield L(t)).events;C(z,o)}}catch(c){console.error("EventFoundry: Failed to initialize:",c)}})}function L(e){return h(this,null,function*(){let t=me(e),n=we(e),o={};n&&(o["If-None-Match"]=n);let r=yield fetch(`${V}?siteKey=${e}`,{headers:o});if(r.status===304){if(t)return t;let c=yield fetch(`${V}?siteKey=${e}`);if(!c.ok)throw new Error(`API returned ${c.status}`);let i=yield c.json(),f=c.headers.get("etag");return H(e,i,f),i}if(!r.ok)throw new Error(`API returned ${r.status}`);let a=yield r.json(),s=r.headers.get("etag");return H(e,a,s),a})}function me(e){try{let t=A(e),n=localStorage.getItem(t);if(!n)return null;let o=JSON.parse(n);return o._fromCache=!0,o}catch(t){return console.warn("EventFoundry: Cache read failed:",t),null}}function we(e){try{let t=_(e);return localStorage.getItem(t)}catch(t){return console.warn("EventFoundry: ETag read failed:",t),null}}function H(e,t,n){try{let o=A(e),r=_(e);localStorage.setItem(o,JSON.stringify(t)),n&&localStorage.setItem(r,n)}catch(o){console.warn("EventFoundry: Cache write failed:",o)}}function B(e){try{let t=A(e),n=_(e);localStorage.removeItem(t),localStorage.removeItem(n)}catch(t){console.warn("EventFoundry: Failed to clear cache:",t)}}function S(){return h(this,null,function*(){let e=q();if(!e||!e.siteKey){console.error("EventFoundry: No site key available for reload");return}let{siteKey:t,devMode:n}=e;console.log("EventFoundry: Cache cleared, reloading definitions"),B(t);try{let r=(yield L(t)).events;C(r,n),console.log("EventFoundry: Definitions reloaded successfully")}catch(o){console.error("EventFoundry: Failed to reload definitions",o)}})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",W):W();return Z(be);})();
1
+ var EventFoundry=(()=>{var m=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames,P=Object.getOwnPropertySymbols;var $=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var T=(e,t,n)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,D=(e,t)=>{for(var n in t||(t={}))$.call(t,n)&&T(e,n,t[n]);if(P)for(var n of P(t))Y.call(t,n)&&T(e,n,t[n]);return e};var Q=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0})},X=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of J(t))!$.call(e,r)&&r!==n&&m(e,r,{get:()=>t[r],enumerable:!(o=U(t,r))||o.enumerable});return e};var Z=e=>X(m({},"__esModule",{value:!0}),e);var h=(e,t,n)=>new Promise((o,r)=>{var a=i=>{try{c(n.next(i))}catch(f){r(f)}},s=i=>{try{c(n.throw(i))}catch(f){r(f)}},c=i=>i.done?o(i.value):Promise.resolve(i.value).then(a,s);c((n=n.apply(e,t)).next())});var be={};Q(be,{reloadEventDefinitions:()=>I});var w=null;function y(){return w}function ee(){return["http://localhost","https://eventfoundry.app"]}function te(e){return ee().some(n=>n==="http://localhost"?e.startsWith("http://localhost"):e===n)}function b(){try{return window.self!==window.top}catch(e){return!0}}function M(){b()&&(console.log("EventFoundry: Running in iframe, waiting for editor activation"),window.addEventListener("message",e=>{let t=e.data,n=t==null?void 0:t.type;if(!(!n||!["ENTER_EDIT_MODE","ENABLE_PREVIEW","DISABLE_PREVIEW","RELOAD_CONFIG"].includes(n))){if(!te(e.origin)){console.warn("EventFoundry: Rejected postMessage from untrusted origin:",e.origin);return}switch(w||(w=e.origin,console.log("EventFoundry: Parent origin established:",w)),t.type){case"ENTER_EDIT_MODE":console.log("\u2190 ENTER_EDIT_MODE received"),ne();break;case"ENABLE_PREVIEW":console.log("\u2190 ENABLE_PREVIEW received"),oe();break;case"DISABLE_PREVIEW":console.log("\u2190 DISABLE_PREVIEW received"),re();break;case"RELOAD_CONFIG":console.log("\u2190 RELOAD_CONFIG received"),I();break}}}),setTimeout(()=>{window.parent&&(window.parent.postMessage({type:"IFRAME_READY"},"*"),console.log("\u2192 IFRAME_READY sent to parent"))},100))}function ne(){O()}function oe(){console.log("EventFoundry: Enabling Preview Mode"),k()}function re(){console.log("EventFoundry: Disabling Preview Mode (Edit Mode active)"),x()}var g=null,E=!1,p=null,v=!1;function R(){return E}function F(){return v}function ae(){return["http://localhost","https://eventfoundry.app"]}function se(e){return ae().some(n=>n==="http://localhost"?e.startsWith("http://localhost"):e===n)}function O(){if(E)return;E=!0;let e=document.createElement("style");e.textContent=` .eventfoundry-highlight { outline: 2px solid #3498db !important; outline-offset: 2px; cursor: pointer !important; } .eventfoundry-test-highlight { outline: 3px solid #e74c3c !important; outline-offset: 3px; background-color: rgba(231, 76, 60, 0.1) !important; } .eventfoundry-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 999998; pointer-events: none; cursor: crosshair; } body.eventfoundry-edit-mode, body.eventfoundry-edit-mode * { cursor: crosshair !important; } `,document.head.appendChild(e);let t=document.createElement("div");t.className="eventfoundry-overlay",document.body.appendChild(t),p=t,document.body.classList.add("eventfoundry-edit-mode"),document.body.addEventListener("mouseover",n=>{v||n.target.classList.contains("eventfoundry-overlay")||(g&&g.classList.remove("eventfoundry-highlight"),n.target.classList.add("eventfoundry-highlight"),g=n.target)},!0),document.body.addEventListener("mouseout",n=>{v||n.target.classList.contains("eventfoundry-overlay")||n.target.classList.remove("eventfoundry-highlight")},!0),document.body.addEventListener("click",n=>{if(n.target.classList.contains("eventfoundry-overlay")||v)return;n.preventDefault(),n.stopPropagation();let o=n.target,r="";o.className&&typeof o.className=="string"&&(r=o.className.trim().split(/\s+/).filter(i=>!i.startsWith("eventfoundry-")).join(" "));let a=window.location.pathname+window.location.search+window.location.hash,s={tagName:o.tagName.toLowerCase(),text:o.textContent.trim().substring(0,50),id:o.id,className:r,selector:he(o),page_path:a},c=y();c?(window.parent.postMessage({type:"ELEMENT_SELECTED",element:s},c),console.log("\u2192 ELEMENT_SELECTED sent to parent")):console.warn("EventFoundry: Cannot send ELEMENT_SELECTED - parent origin not established")},!0),window.addEventListener("message",n=>{if(se(n.origin)&&(n.data.type==="HIGHLIGHT_SELECTOR"&&(console.log("\u2190 HIGHLIGHT_SELECTOR received:",n.data.selector),ye(n.data.selector)),n.data.type==="COUNT_MATCHES")){let o=n.data.selector,r=0;try{r=document.querySelectorAll(o).length}catch(s){r=0}let a=y();a&&window.parent.postMessage({type:"MATCH_COUNT_RESULT",selector:o,count:r},a)}})}function l(e){return e?e.replace(/([!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,"\\$1"):""}function ie(e){return e?!!(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i.test(e)||/\d{13}/.test(e)||/^[a-f0-9]{16,}$/i.test(e)||/-\d{4,}$/.test(e)):!1}function ce(e,t){try{let n=document.querySelectorAll(t);return n.length===1&&n[0]===e}catch(n){return!1}}function N(e){return!e.className||typeof e.className!="string"?[]:e.className.trim().split(/\s+/).filter(t=>t&&!t.startsWith("eventfoundry-"))}function G(e,t=!0){let n=e.parentElement;if(!n)return null;let o=N(n);return t&&o.length>0?`.${l(o[0])}`:n.tagName.toLowerCase()}function d(e,t,n,o){return ce(o,t)?(e.push({selector:t,priority:n}),!0):!1}function le(e){let t=[];if(e.id&&!ie(e.id)){let n=`#${l(e.id)}`;d(t,n,100,e)}return t}function de(e){let t=[],n=Array.from(e.attributes).filter(o=>o.name.startsWith("data-")&&o.value);for(let o of n){let r=`[${o.name}="${l(o.value)}"]`;if(d(t,r,90,e))break}return t}function ue(e){let t=[],n=N(e);if(n.length===0)return t;let o=e.tagName.toLowerCase();for(let r of n){let a=`${o}.${l(r)}`;if(d(t,a,85,e))break}if(n.length>=2){let r=`.${l(n[0])}.${l(n[1])}`;if(d(t,r,82,e),n.length>=3){let a=`.${l(n[0])}.${l(n[1])}.${l(n[2])}`;d(t,a,82,e)}}for(let r of n){let a=`.${l(r)}`;if(d(t,a,80,e))break}return t}function fe(e){let t=[],n=e.tagName.toLowerCase(),o=["type","name","href","role","aria-label"];for(let r of o){let a=e.getAttribute(r);if(a){let s=`${n}[${r}="${l(a)}"]`;if(d(t,s,70,e))break}}return t}function ge(e){let t=[],n=G(e,!0);if(!n)return t;let o=e.tagName.toLowerCase(),r=N(e);if(r.length>0){let s=`${n} .${l(r[0])}`;d(t,s,75,e)}if(r.length>0){let s=`${n} ${o}.${l(r[0])}`;d(t,s,72,e)}let a=`${n} ${o}`;return d(t,a,65,e),t}function ve(e){let t=[],n=e.tagName.toLowerCase(),o=e.parentElement;if(!o)return[{selector:n,priority:10}];let r=G(e,!0),s=Array.from(o.children).indexOf(e)+1,c=`${r} ${n}:nth-child(${s})`;return d(t,c,50,e),t}function he(e){let t=[];return t.push(...le(e)),t.push(...de(e)),t.push(...ue(e)),t.push(...fe(e)),t.push(...ge(e)),t.push(...ve(e)),t.length>0?(t.sort((n,o)=>o.priority-n.priority),t[0].selector):e.tagName.toLowerCase()}function ye(e){document.querySelectorAll(".eventfoundry-test-highlight").forEach(t=>{t.classList.remove("eventfoundry-test-highlight")});try{let t=document.querySelectorAll(e);t.forEach(n=>{n.classList.add("eventfoundry-test-highlight")}),setTimeout(()=>{t.forEach(n=>{n.classList.remove("eventfoundry-test-highlight")})},3e3)}catch(t){console.error("EventFoundry: Invalid selector",e,t)}}function k(){if(!E){console.warn("EventFoundry: Cannot enable preview - overlay not active");return}v=!0,console.log("EventFoundry: Preview Mode enabled - all interactions allowed"),p&&(p.style.display="none"),document.body.classList.remove("eventfoundry-edit-mode"),g&&(g.classList.remove("eventfoundry-highlight"),g=null)}function x(){if(!E){console.warn("EventFoundry: Cannot disable preview - overlay not active");return}v=!1,console.log("EventFoundry: Preview Mode disabled - Edit Mode active"),p&&(p.style.display=""),document.body.classList.add("eventfoundry-edit-mode")}var j=console.log;function u(e,...t){e&&j&&j(...t)}var C=null;function Ee(e){let t=[],n=[];return e.forEach(o=>{try{document.querySelector(o.selector),t.push(o)}catch(r){console.warn(`EventFoundry: Invalid selector "${o.selector}" - ${r.message}`),n.push({selector:o.selector,error:r.message,name:o.name})}}),{validDefs:t,invalidDefs:n}}function S(e,t=!1){if(!e||e.length===0)return!1;C&&C.abort();let{validDefs:n,invalidDefs:o}=Ee(e);return n.length===0?(console.error("\u{1F6A8} EventFoundry: No valid event selectors found - tracking disabled!"),console.error("Invalid selectors:",o),!1):(o.length>0&&console.warn(`EventFoundry: ${o.length} of ${e.length} selectors are invalid and will be skipped`),C=new AbortController,document.addEventListener("click",r=>{if(R()&&!F()){u(t,"EventFoundry: Click ignored (editor mode active, not in preview)");return}let a=n.filter(i=>r.target.closest(i.selector)!==null);if(a.length===0){u(t,"EventFoundry: Click on",r.target,"matched 0 events");return}let s=a[0],c=D({event_category:"EventFoundry",event_label:s.name,transport_type:"beacon"},s.gaEventParams);if(u(t,"EventFoundry: Firing event",s.gaEventName,c),!t&&!F()){if(typeof window.gtag!="function"){console.error("EventFoundry: gtag not available - is GA4 installed?");return}window.gtag("event",s.gaEventName,c)}if(F())try{let i=y();i?(window.parent.postMessage({type:"EVENT_FIRED",timestamp:Date.now(),eventName:s.name,gaEventName:s.gaEventName,selector:s.selector,params:c,pagePath:window.location.pathname},i),console.log("\u2192 EVENT_FIRED sent to parent")):console.warn("EventFoundry: Cannot send EVENT_FIRED - parent origin not established")}catch(i){console.warn("EventFoundry: Failed to send EVENT_FIRED postMessage",i)}a.length>1&&console.warn("EventFoundry: Multiple events matched, only firing first:",a.map(i=>i.name))},{capture:!0,signal:C.signal}),!0)}var K=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1",V=K?"http://localhost/api/tracking/events":"https://eventfoundry.app/api/tracking/events";function A(e){return`eventfoundry_definitions_${e}`}function _(e){return`eventfoundry_etag_${e}`}function q(){let e=document.currentScript||document.querySelector("script[data-site-key]");if(!e)return console.error("EventFoundry: Could not find script tag"),null;let t=e.getAttribute("data-dev-mode"),n=t==="false"?!1:K||t==="true";return{siteKey:e.getAttribute("data-site-key"),measurementId:e.getAttribute("data-measurement-id"),devMode:n}}function pe(e){return h(this,null,function*(){if(window.gtag&&typeof window.gtag=="function")return{hasGtag:!0,wasInjected:!1};if(!e)return console.warn("EventFoundry: No GA4 detected and no measurement ID provided. Events will not be tracked."),{hasGtag:!1,wasInjected:!1};let t=document.createElement("script");return t.async=!0,t.src=`https://www.googletagmanager.com/gtag/js?id=${e}`,document.head.appendChild(t),window.dataLayer=window.dataLayer||[],yield new Promise((n,o)=>{let r=!1;t.onload=()=>{r||(r=!0,n())},t.onerror=()=>{r||(r=!0,console.error("EventFoundry: Failed to load gtag script"),o(new Error("gtag script failed to load")))},setTimeout(()=>{r||(r=!0,console.warn("EventFoundry: gtag script load timeout after 10s"),n())},1e4)}).catch(()=>({hasGtag:!1,wasInjected:!1})),typeof window.gtag!="function"?(console.error("EventFoundry: gtag not available after load - events will not fire"),{hasGtag:!1,wasInjected:!1}):(window.gtag("js",new Date),window.gtag("config",e),{hasGtag:!0,wasInjected:!0})})}function W(){return h(this,null,function*(){let e=q();if(!e||!e.siteKey){console.error("EventFoundry: No site key provided");return}let{siteKey:t,measurementId:n,devMode:o}=e;console.log("\u2713 EventFoundry tracker loaded (v0.5.3)"),b()&&M();let{hasGtag:r,wasInjected:a}=yield pe(n),s=b();if(!r&&!s){console.error("EventFoundry: Cannot track events without GA4");return}r?console.log(a?"\u2713 GA4 injected successfully":"\u2713 GA4 detected"):s&&console.log("\u26A0 GA4 not available - editor mode will use postMessage-based event logging"),u(o,"\u26A0 Dev mode: Events disabled"),u(!o,"\u2713 Production mode: Events enabled");try{let c=yield L(t),i=c.events;if(!S(i,o)&&c._fromCache){console.log("EventFoundry: Tracking failed with cached data, clearing cache and refetching..."),B(t);let z=(yield L(t)).events;S(z,o)}}catch(c){console.error("EventFoundry: Failed to initialize:",c)}})}function L(e){return h(this,null,function*(){let t=me(e),n=we(e),o={};n&&(o["If-None-Match"]=n);let r=yield fetch(`${V}?siteKey=${e}`,{headers:o});if(r.status===304){if(t)return t;let c=yield fetch(`${V}?siteKey=${e}`);if(!c.ok)throw new Error(`API returned ${c.status}`);let i=yield c.json(),f=c.headers.get("etag");return H(e,i,f),i}if(!r.ok)throw new Error(`API returned ${r.status}`);let a=yield r.json(),s=r.headers.get("etag");return H(e,a,s),a})}function me(e){try{let t=A(e),n=localStorage.getItem(t);if(!n)return null;let o=JSON.parse(n);return o._fromCache=!0,o}catch(t){return console.warn("EventFoundry: Cache read failed:",t),null}}function we(e){try{let t=_(e);return localStorage.getItem(t)}catch(t){return console.warn("EventFoundry: ETag read failed:",t),null}}function H(e,t,n){try{let o=A(e),r=_(e);localStorage.setItem(o,JSON.stringify(t)),n&&localStorage.setItem(r,n)}catch(o){console.warn("EventFoundry: Cache write failed:",o)}}function B(e){try{let t=A(e),n=_(e);localStorage.removeItem(t),localStorage.removeItem(n)}catch(t){console.warn("EventFoundry: Failed to clear cache:",t)}}function I(){return h(this,null,function*(){let e=q();if(!e||!e.siteKey){console.error("EventFoundry: No site key available for reload");return}let{siteKey:t,devMode:n}=e;console.log("EventFoundry: Cache cleared, reloading definitions"),B(t);try{let r=(yield L(t)).events;S(r,n),console.log("EventFoundry: Definitions reloaded successfully")}catch(o){console.error("EventFoundry: Failed to reload definitions",o)}})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",W):W();return Z(be);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kylelogue/eventfoundry-tracker",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "EventFoundry tracking script for custom GA4 event tracking",
5
5
  "main": "dist/tracker.min.js",
6
6
  "files": [