@hifilabs/pixel 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -37,7 +37,17 @@ var BalancePixel = (() => {
37
37
  // src/index.ts
38
38
  var src_exports = {};
39
39
  __export(src_exports, {
40
- BalanceAnalytics: () => BalanceAnalytics
40
+ BalanceAnalytics: () => BalanceAnalytics,
41
+ getAttribution: () => getAttribution,
42
+ getConsent: () => getConsent,
43
+ getFanIdHash: () => getFanIdHash,
44
+ getSessionId: () => getSessionId,
45
+ hasConsent: () => hasConsent,
46
+ identify: () => identify,
47
+ page: () => page,
48
+ purchase: () => purchase,
49
+ setConsent: () => setConsent,
50
+ track: () => track
41
51
  });
42
52
 
43
53
  // src/react/BalanceAnalytics.tsx
@@ -160,7 +170,7 @@ var BalancePixel = (() => {
160
170
  } catch (e) {
161
171
  }
162
172
  }
163
- function setConsent(preferences) {
173
+ function setConsent2(preferences) {
164
174
  const previousConsent = consent;
165
175
  consent = preferences;
166
176
  try {
@@ -184,10 +194,10 @@ var BalancePixel = (() => {
184
194
  });
185
195
  enqueueEvent(event);
186
196
  }
187
- function getConsent() {
197
+ function getConsent2() {
188
198
  return consent;
189
199
  }
190
- function hasConsent(type) {
200
+ function hasConsent2(type) {
191
201
  return consent?.[type] === true;
192
202
  }
193
203
  async function hashEmail(email) {
@@ -216,12 +226,6 @@ var BalancePixel = (() => {
216
226
  return base;
217
227
  }
218
228
  function enqueueEvent(event) {
219
- const essentialEvents = ["identify", "consent_updated"];
220
- const isEssential = essentialEvents.includes(event.event_name);
221
- if (!isEssential && !hasConsent("analytics")) {
222
- log(`Event '${event.event_name}' blocked - no analytics consent`);
223
- return;
224
- }
225
229
  eventQueue.push(event);
226
230
  log("Event queued:", event.event_name, "(queue:", eventQueue.length, ")");
227
231
  if (eventQueue.length >= 10) {
@@ -269,7 +273,7 @@ var BalancePixel = (() => {
269
273
  });
270
274
  enqueueEvent(event);
271
275
  }
272
- function track(eventName, properties = {}) {
276
+ function track2(eventName, properties = {}) {
273
277
  const event = buildEvent({
274
278
  event_name: "custom",
275
279
  metadata: {
@@ -279,7 +283,7 @@ var BalancePixel = (() => {
279
283
  });
280
284
  enqueueEvent(event);
281
285
  }
282
- async function identify(email, traits = {}) {
286
+ async function identify2(email, traits = {}) {
283
287
  try {
284
288
  fanIdHash = await hashEmail(email);
285
289
  localStorage.setItem(FAN_ID_KEY, fanIdHash);
@@ -305,7 +309,7 @@ var BalancePixel = (() => {
305
309
  console.error("[BALANCE Pixel] Failed to identify:", error);
306
310
  }
307
311
  }
308
- function purchase(revenue, currency = "USD", properties = {}) {
312
+ function purchase2(revenue, currency = "USD", properties = {}) {
309
313
  const event = buildEvent({
310
314
  event_name: "purchase",
311
315
  metadata: {
@@ -323,11 +327,11 @@ var BalancePixel = (() => {
323
327
  if (!consent) {
324
328
  consent = {
325
329
  analytics: true,
326
- marketing: false,
327
- personalization: false,
330
+ marketing: true,
331
+ personalization: true,
328
332
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
329
333
  };
330
- log("Using default consent (dev mode):", consent);
334
+ log("Default consent enabled (all tracking):", consent);
331
335
  }
332
336
  captureAttribution();
333
337
  startFlushTimer();
@@ -351,16 +355,16 @@ var BalancePixel = (() => {
351
355
  });
352
356
  }
353
357
  window.balance = {
354
- track,
355
- identify,
358
+ track: track2,
359
+ identify: identify2,
356
360
  page: trackPageView,
357
- purchase,
361
+ purchase: purchase2,
358
362
  getSessionId: () => sessionId,
359
363
  getFanIdHash: () => fanIdHash,
360
364
  getAttribution: () => attribution,
361
- setConsent,
362
- getConsent,
363
- hasConsent
365
+ setConsent: setConsent2,
366
+ getConsent: getConsent2,
367
+ hasConsent: hasConsent2
364
368
  };
365
369
  if (document.readyState === "loading") {
366
370
  document.addEventListener("DOMContentLoaded", init);
@@ -369,5 +373,76 @@ var BalancePixel = (() => {
369
373
  }
370
374
  log("Pixel script loaded");
371
375
  })();
376
+ var track = (eventName, properties) => {
377
+ if (typeof window === "undefined")
378
+ return;
379
+ if (window.balance) {
380
+ window.balance.track(eventName, properties);
381
+ } else {
382
+ console.warn("[Balance Pixel] track() called before pixel initialized:", eventName);
383
+ }
384
+ };
385
+ var identify = (email, traits) => {
386
+ if (typeof window === "undefined")
387
+ return Promise.resolve();
388
+ if (window.balance) {
389
+ return window.balance.identify(email, traits);
390
+ } else {
391
+ console.warn("[Balance Pixel] identify() called before pixel initialized");
392
+ return Promise.resolve();
393
+ }
394
+ };
395
+ var page = (options) => {
396
+ if (typeof window === "undefined")
397
+ return;
398
+ if (window.balance) {
399
+ window.balance.page(options);
400
+ } else {
401
+ console.warn("[Balance Pixel] page() called before pixel initialized");
402
+ }
403
+ };
404
+ var purchase = (revenue, currency, properties) => {
405
+ if (typeof window === "undefined")
406
+ return;
407
+ if (window.balance) {
408
+ window.balance.purchase(revenue, currency, properties);
409
+ } else {
410
+ console.warn("[Balance Pixel] purchase() called before pixel initialized");
411
+ }
412
+ };
413
+ var getSessionId = () => {
414
+ if (typeof window === "undefined")
415
+ return null;
416
+ return window.balance?.getSessionId() ?? null;
417
+ };
418
+ var getFanIdHash = () => {
419
+ if (typeof window === "undefined")
420
+ return null;
421
+ return window.balance?.getFanIdHash() ?? null;
422
+ };
423
+ var getAttribution = () => {
424
+ if (typeof window === "undefined")
425
+ return {};
426
+ return window.balance?.getAttribution() ?? {};
427
+ };
428
+ var setConsent = (preferences) => {
429
+ if (typeof window === "undefined")
430
+ return;
431
+ if (window.balance) {
432
+ window.balance.setConsent(preferences);
433
+ } else {
434
+ console.warn("[Balance Pixel] setConsent() called before pixel initialized");
435
+ }
436
+ };
437
+ var getConsent = () => {
438
+ if (typeof window === "undefined")
439
+ return null;
440
+ return window.balance?.getConsent() ?? null;
441
+ };
442
+ var hasConsent = (type) => {
443
+ if (typeof window === "undefined")
444
+ return false;
445
+ return window.balance?.hasConsent(type) ?? false;
446
+ };
372
447
  return __toCommonJS(src_exports);
373
448
  })();
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- var BalancePixel=(()=>{var V=Object.create;var _=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var L=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,a)=>(typeof require<"u"?require:r)[a]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var te=(n,r)=>{for(var a in r)_(n,a,{get:r[a],enumerable:!0})},D=(n,r,a,u)=>{if(r&&typeof r=="object"||typeof r=="function")for(let g of X(r))!ee.call(n,g)&&g!==a&&_(n,g,{get:()=>r[g],enumerable:!(u=W(r,g))||u.enumerable});return n};var ne=(n,r,a)=>(a=n!=null?V(Z(n)):{},D(r||!n||!n.__esModule?_(a,"default",{value:n,enumerable:!0}):a,n)),re=n=>D(_({},"__esModule",{value:!0}),n);var ae={};te(ae,{BalanceAnalytics:()=>R});var f=ne(L("react")),x=L("next/navigation");function oe(){let n=(0,x.usePathname)(),r=(0,x.useSearchParams)();return(0,f.useEffect)(()=>{if(typeof window<"u"&&window.balance){let a=window.location.href,u=document.title;window.balance.page({url:a,title:u})}},[n,r]),null}function R(){return f.default.createElement(f.Suspense,{fallback:null},f.default.createElement(oe,null))}(function(){let n=document.currentScript,r=n?.dataset.artistId,a=n?.dataset.projectId,u=n?.dataset.emulator==="true",g=n?.dataset.debug==="true";if(!r){console.error("[BALANCE Pixel] Error: data-artist-id attribute is required");return}let w="balance_session_id",v="balance_session_timestamp",A="balance_attribution",P="balance_fan_id_hash",C="balance_consent",U=60*60*1e3,I=u?"http://localhost:5001/artist-os-distro/us-central1/pixelEndpoint":"https://us-central1-artist-os-distro.cloudfunctions.net/pixelEndpoint",y=null,l=null,c=null,m={},d=[],E=null,i=(...e)=>{g&&console.log("[BALANCE Pixel]",...e)};function N(){return crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function B(){try{let e=localStorage.getItem(w),t=localStorage.getItem(v);if(e&&t&&Date.now()-parseInt(t,10)<U)return localStorage.setItem(v,Date.now().toString()),e;let o=N();return localStorage.setItem(w,o),localStorage.setItem(v,Date.now().toString()),o}catch{return N()}}function j(){let e=new URLSearchParams(window.location.search),t={};return["source","medium","campaign","content","term"].forEach(o=>{let s=e.get(`utm_${o}`);s&&(t[`utm_${o}`]=s)}),t}function F(){try{let e=localStorage.getItem(A);if(e){m=JSON.parse(e),i("Loaded attribution:",m);return}let t=j();Object.keys(t).length>0&&(m=t,localStorage.setItem(A,JSON.stringify(t)),i("Captured attribution:",m))}catch{}}function z(){try{l=localStorage.getItem(P)}catch{}}function H(){try{let e=localStorage.getItem(C);e&&(c=JSON.parse(e).preferences||null,i("Loaded consent:",c))}catch{}}function M(e){let t=c;c=e;try{let s={preferences:e,method:"explicit",version:1};localStorage.setItem(C,JSON.stringify(s)),i("Consent saved:",e)}catch(s){console.error("[BALANCE Pixel] Could not save consent:",s)}let o=p({event_name:"consent_updated",metadata:{consent_preferences:e,consent_method:"explicit",previous_consent:t||void 0}});h(o)}function J(){return c}function O(e){return c?.[e]===!0}async function K(e){let t=e.toLowerCase().trim(),s=new TextEncoder().encode(t),b=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(b)).map(Q=>Q.toString(16).padStart(2,"0")).join("")}function p(e){let t={artist_id:r,fan_session_id:y,fan_id_hash:l||void 0,timestamp:new Date().toISOString(),source_url:window.location.href,referrer_url:document.referrer||void 0,user_agent:navigator.userAgent,...e,...m};return a&&!e.projectId&&(t.projectId=a),t}function h(e){if(!["identify","consent_updated"].includes(e.event_name)&&!O("analytics")){i(`Event '${e.event_name}' blocked - no analytics consent`);return}d.push(e),i("Event queued:",e.event_name,"(queue:",d.length,")"),d.length>=10&&S()}async function S(){if(d.length===0)return;let e=[...d];d=[],i("Flushing",e.length,"events to",I);try{let t=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:e}),keepalive:!0});if(!t.ok)throw new Error(`HTTP ${t.status}`);i("Events sent successfully")}catch(t){console.error("[BALANCE Pixel] Failed to send events:",t),d.length<50&&d.push(...e)}}function Y(){E&&clearInterval(E),E=window.setInterval(()=>{d.length>0&&S()},5e3)}function T(e={}){let t=p({event_name:"pageview",page_title:e.title||document.title,source_url:e.url||window.location.href});h(t)}function q(e,t={}){let o=p({event_name:"custom",metadata:{event_type:e,...t}});h(o)}async function $(e,t={}){try{l=await K(e),localStorage.setItem(P,l);let o=e.split("@"),s=o[0].charAt(0)+"***@"+(o[1]||"");i("Fan identified:",{name:t.name||"(no name)",email:s,hash:l.substring(0,16)+"...",traits:t});let b=p({event_name:"identify",fan_id_hash:l,metadata:{email_sha256:l,traits:t,consent_preferences:c||void 0}});h(b)}catch(o){console.error("[BALANCE Pixel] Failed to identify:",o)}}function G(e,t="USD",o={}){let s=p({event_name:"purchase",metadata:{revenue:e,currency:t,...o}});h(s)}function k(){y=B(),z(),H(),c||(c={analytics:!0,marketing:!1,personalization:!1,timestamp:new Date().toISOString()},i("Using default consent (dev mode):",c)),F(),Y(),i("Initialized",{artistId:r,projectId:a||"(none - will track to all projects)",sessionId:y,fanIdHash:l,consent:c,useEmulator:u,endpoint:I}),T(),window.addEventListener("beforeunload",()=>{S()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&S()})}window.balance={track:q,identify:$,page:T,purchase:G,getSessionId:()=>y,getFanIdHash:()=>l,getAttribution:()=>m,setConsent:M,getConsent:J,hasConsent:O},document.readyState==="loading"?document.addEventListener("DOMContentLoaded",k):k(),i("Pixel script loaded")})();return re(ae);})();
1
+ var BalancePixel=(()=>{var V=Object.create;var x=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var T=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(r,o)=>(typeof require<"u"?require:r)[o]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ne=(n,r)=>{for(var o in r)x(n,o,{get:r[o],enumerable:!0})},B=(n,r,o,u)=>{if(r&&typeof r=="object"||typeof r=="function")for(let f of X(r))!ee.call(n,f)&&f!==o&&x(n,f,{get:()=>r[f],enumerable:!(u=W(r,f))||u.enumerable});return n};var te=(n,r,o)=>(o=n!=null?V(Z(n)):{},B(r||!n||!n.__esModule?x(o,"default",{value:n,enumerable:!0}):o,n)),re=n=>B(x({},"__esModule",{value:!0}),n);var me={};ne(me,{BalanceAnalytics:()=>R,getAttribution:()=>ue,getConsent:()=>ge,getFanIdHash:()=>de,getSessionId:()=>le,hasConsent:()=>pe,identify:()=>ae,page:()=>se,purchase:()=>ce,setConsent:()=>fe,track:()=>ie});var g=te(T("react")),b=T("next/navigation");function oe(){let n=(0,b.usePathname)(),r=(0,b.useSearchParams)();return(0,g.useEffect)(()=>{if(typeof window<"u"&&window.balance){let o=window.location.href,u=document.title;window.balance.page({url:o,title:u})}},[n,r]),null}function R(){return g.default.createElement(g.Suspense,{fallback:null},g.default.createElement(oe,null))}(function(){let n=document.currentScript,r=n?.dataset.artistId,o=n?.dataset.projectId,u=n?.dataset.emulator==="true",f=n?.dataset.debug==="true";if(!r){console.error("[BALANCE Pixel] Error: data-artist-id attribute is required");return}let P="balance_session_id",S="balance_session_timestamp",E="balance_attribution",C="balance_fan_id_hash",A="balance_consent",D=60*60*1e3,I=u?"http://localhost:5001/artist-os-distro/us-central1/pixelEndpoint":"https://us-central1-artist-os-distro.cloudfunctions.net/pixelEndpoint",h=null,l=null,s=null,p={},d=[],_=null,c=(...e)=>{f&&console.log("[BALANCE Pixel]",...e)};function N(){return crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function L(){try{let e=localStorage.getItem(P),t=localStorage.getItem(S);if(e&&t&&Date.now()-parseInt(t,10)<D)return localStorage.setItem(S,Date.now().toString()),e;let i=N();return localStorage.setItem(P,i),localStorage.setItem(S,Date.now().toString()),i}catch{return N()}}function z(){let e=new URLSearchParams(window.location.search),t={};return["source","medium","campaign","content","term"].forEach(i=>{let a=e.get(`utm_${i}`);a&&(t[`utm_${i}`]=a)}),t}function U(){try{let e=localStorage.getItem(E);if(e){p=JSON.parse(e),c("Loaded attribution:",p);return}let t=z();Object.keys(t).length>0&&(p=t,localStorage.setItem(E,JSON.stringify(t)),c("Captured attribution:",p))}catch{}}function F(){try{l=localStorage.getItem(C)}catch{}}function j(){try{let e=localStorage.getItem(A);e&&(s=JSON.parse(e).preferences||null,c("Loaded consent:",s))}catch{}}function H(e){let t=s;s=e;try{let a={preferences:e,method:"explicit",version:1};localStorage.setItem(A,JSON.stringify(a)),c("Consent saved:",e)}catch(a){console.error("[BALANCE Pixel] Could not save consent:",a)}let i=m({event_name:"consent_updated",metadata:{consent_preferences:e,consent_method:"explicit",previous_consent:t||void 0}});w(i)}function M(){return s}function J(e){return s?.[e]===!0}async function K(e){let t=e.toLowerCase().trim(),a=new TextEncoder().encode(t),v=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(v)).map(Q=>Q.toString(16).padStart(2,"0")).join("")}function m(e){let t={artist_id:r,fan_session_id:h,fan_id_hash:l||void 0,timestamp:new Date().toISOString(),source_url:window.location.href,referrer_url:document.referrer||void 0,user_agent:navigator.userAgent,...e,...p};return o&&!e.projectId&&(t.projectId=o),t}function w(e){d.push(e),c("Event queued:",e.event_name,"(queue:",d.length,")"),d.length>=10&&y()}async function y(){if(d.length===0)return;let e=[...d];d=[],c("Flushing",e.length,"events to",I);try{let t=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:e}),keepalive:!0});if(!t.ok)throw new Error(`HTTP ${t.status}`);c("Events sent successfully")}catch(t){console.error("[BALANCE Pixel] Failed to send events:",t),d.length<50&&d.push(...e)}}function Y(){_&&clearInterval(_),_=window.setInterval(()=>{d.length>0&&y()},5e3)}function k(e={}){let t=m({event_name:"pageview",page_title:e.title||document.title,source_url:e.url||window.location.href});w(t)}function q(e,t={}){let i=m({event_name:"custom",metadata:{event_type:e,...t}});w(i)}async function $(e,t={}){try{l=await K(e),localStorage.setItem(C,l);let i=e.split("@"),a=i[0].charAt(0)+"***@"+(i[1]||"");c("Fan identified:",{name:t.name||"(no name)",email:a,hash:l.substring(0,16)+"...",traits:t});let v=m({event_name:"identify",fan_id_hash:l,metadata:{email_sha256:l,traits:t,consent_preferences:s||void 0}});w(v)}catch(i){console.error("[BALANCE Pixel] Failed to identify:",i)}}function G(e,t="USD",i={}){let a=m({event_name:"purchase",metadata:{revenue:e,currency:t,...i}});w(a)}function O(){h=L(),F(),j(),s||(s={analytics:!0,marketing:!0,personalization:!0,timestamp:new Date().toISOString()},c("Default consent enabled (all tracking):",s)),U(),Y(),c("Initialized",{artistId:r,projectId:o||"(none - will track to all projects)",sessionId:h,fanIdHash:l,consent:s,useEmulator:u,endpoint:I}),k(),window.addEventListener("beforeunload",()=>{y()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&y()})}window.balance={track:q,identify:$,page:k,purchase:G,getSessionId:()=>h,getFanIdHash:()=>l,getAttribution:()=>p,setConsent:H,getConsent:M,hasConsent:J},document.readyState==="loading"?document.addEventListener("DOMContentLoaded",O):O(),c("Pixel script loaded")})();var ie=(n,r)=>{typeof window>"u"||(window.balance?window.balance.track(n,r):console.warn("[Balance Pixel] track() called before pixel initialized:",n))},ae=(n,r)=>typeof window>"u"?Promise.resolve():window.balance?window.balance.identify(n,r):(console.warn("[Balance Pixel] identify() called before pixel initialized"),Promise.resolve()),se=n=>{typeof window>"u"||(window.balance?window.balance.page(n):console.warn("[Balance Pixel] page() called before pixel initialized"))},ce=(n,r,o)=>{typeof window>"u"||(window.balance?window.balance.purchase(n,r,o):console.warn("[Balance Pixel] purchase() called before pixel initialized"))},le=()=>typeof window>"u"?null:window.balance?.getSessionId()??null,de=()=>typeof window>"u"?null:window.balance?.getFanIdHash()??null,ue=()=>typeof window>"u"?{}:window.balance?.getAttribution()??{},fe=n=>{typeof window>"u"||(window.balance?window.balance.setConsent(n):console.warn("[Balance Pixel] setConsent() called before pixel initialized"))},ge=()=>typeof window>"u"?null:window.balance?.getConsent()??null,pe=n=>typeof window>"u"?!1:window.balance?.hasConsent(n)??!1;return re(me);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hifilabs/pixel",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "BALANCE Pixel - Lightweight browser tracking script for artist fan analytics",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.esm.js",