@bilyai/js 1.0.32 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0 - 2026-07-13
4
+
5
+ - Added exact `scriptUrl` initialization with query-string preservation.
6
+ - Added bounded pre-load event queuing, readiness checks, load errors, and timeouts.
7
+ - Added SSR-safe initialization, tracking, identity, and readiness calls.
8
+ - Added custom event names while retaining autocomplete for known Bily events.
9
+ - Fixed top-level product payloads, optional quantities, zero-valued totals and fees, product images, and client groups.
10
+ - Added the current event catalog and normalized legacy aliases before delivery routing, including `Pageview` to
11
+ `PageView`.
12
+ - Corrected `getBilyTrackingId()` to return `string | null`.
13
+ - Removed obsolete browser-global declarations from the public TypeScript surface. Use the exported SDK methods instead.
14
+ - Exported all public payload types from `@bilyai/js`.
15
+ - Added ESM and CommonJS exports with zero runtime dependencies.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Bily
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,161 +1,64 @@
1
- <!-- markdownlint-disable MD033 -->
2
- <p align="center">
3
- <svg width="96" height="54" fill="none" xmlns="http://www.w3.org/2000/svg"><g opacity=".99" fill-rule="evenodd" clip-rule="evenodd" fill="#000"><path d="M10.81 16.206l2.22 1.643L16 9.187l-5.19 7.02zm0 0l-2.221-1.64 7.41-5.379-5.189 7.02z"/><path d="M21.187 16.206l-2.22 1.643-2.969-8.662 5.19 7.02zm0 0l2.222-1.64L16 9.187l5.189 7.02zm1.697-13.039l-6.886 6.02 9.081-.997 6.918-5.988h.001l-9.114.965z"/><path d="M9.114 3.167L16 9.187 6.919 8.19v-.001L0 2.202l9.115.964z"/></g></svg>
4
- </p>
5
- <!-- markdownlint-enable MD033 -->
1
+ # Bily JavaScript SDK
6
2
 
7
- # Official Bily SDK for Browser
3
+ The official browser SDK for sending page views, product activity, and custom application events to Bily.
8
4
 
9
- [![npm version](https://img.shields.io/npm/v/@bilyai/js.svg)](https://www.npmjs.com/package/@bilyai/js)
10
- [![npm dm](https://img.shields.io/npm/dm/@bilyai/js.svg)](https://www.npmjs.com/package/@bilyai/js)
11
- [![npm dt](https://img.shields.io/npm/dt/@bilyai/js.svg)](https://www.npmjs.com/package/@bilyai/js)
5
+ ## Install
12
6
 
13
- Don't already have an account and store added ? Head over to [Bily](https://app.bily.ai), then return to this page.
14
-
15
- # ☕ Install package
16
-
17
- ```shell Npm
7
+ ```bash
18
8
  npm install @bilyai/js
19
9
  ```
20
10
 
21
- ```shell Yarn
22
- yarn add @bilyai/js
23
- ```
24
-
25
- # 🚦 Configurations
11
+ ## Initialize once
26
12
 
27
- Configuration should happen as early as possible in your application's lifecycle.
13
+ Copy the exact script URL from **Bily > Settings > Tracking**. Keep every query parameter in the URL.
28
14
 
29
- ```javascript Init Bily
30
- import { init } from '@bilyai/js';
15
+ ```ts
16
+ import { init } from "@bilyai/js";
31
17
 
32
- init('https://b.magnetor.net');
18
+ init({
19
+ scriptUrl: "https://tracking.example.com/b.js?shop=store.example.com",
20
+ });
33
21
  ```
34
22
 
35
- Once implemented, Bily's JavaScript SDK will automatically track all pageviews. You can now begin tracking all other
36
- events as well.
23
+ The SDK safely queues calls made while the browser script loads. Repeated `init()` calls with the same URL do not
24
+ load it twice.
37
25
 
38
- # 🚀 Start tracking events
26
+ ## Track an event
39
27
 
40
- ```javascript Product Viewed
41
- import { track } from '@bilyai/js';
28
+ ```ts
29
+ import { track } from "@bilyai/js";
42
30
 
43
- track('Product Viewed', {
44
- client: {
45
- firstname: 'John',
46
- lastname: 'Doe',
47
- // ... other attributes here
48
- },
31
+ track("Product Viewed", {
49
32
  products: [
50
33
  {
51
- id: '123',
52
- name: 'Product 1',
53
- price: 100,
34
+ id: "product_123",
35
+ name: "Everyday Tee",
36
+ price: 39,
37
+ currency: "USD",
54
38
  quantity: 1,
55
- currency: 'USD',
56
- sku: '123',
57
- category: 'Category 1',
58
- brand: 'Brand 1',
59
39
  },
60
40
  ],
61
- // ...other attributes here
62
41
  });
63
42
  ```
64
43
 
65
- ```javascript Add to cart
66
- import { track } from '@bilyai/js';
44
+ Custom application events are supported:
67
45
 
68
- track('Product Added', {
69
- client: {
70
- firstname: 'John',
71
- lastname: 'Doe',
72
- // ... other attributes here
73
- },
74
- products: [
75
- {
76
- id: '123',
77
- name: 'Product 1',
78
- price: 100,
79
- quantity: 1,
80
- currency: 'USD',
81
- sku: '123',
82
- category: 'Category 1',
83
- brand: 'Brand 1',
84
- },
85
- ],
86
- // ...other attributes here
46
+ ```ts
47
+ track("workspace_created", {
48
+ user_id: "user_123",
49
+ workspace_id: "workspace_456",
87
50
  });
88
51
  ```
89
52
 
90
- ```javascript Checkout Started
91
- import { track } from '@bilyai/js';
92
-
93
- track('Checkout Started', {
94
- client: {
95
- firstname: 'John',
96
- lastname: 'Doe',
97
- email: 'john@doe.com',
98
- // ... other attributes here
99
- },
100
- products: [
101
- {
102
- id: '123',
103
- name: 'Product 1',
104
- price: 100,
105
- quantity: 1,
106
- currency: 'USD',
107
- sku: '123',
108
- category: 'Category 1',
109
- brand: 'Brand 1',
110
- },
111
- ],
112
- // ...other attributes here
113
- });
114
- ```
53
+ ## Verify loading
115
54
 
116
- ```javascript Order Completed
117
- import { track } from '@bilyai/js';
118
-
119
- track('Order Completed', {
120
- client: {
121
- firstname: 'John',
122
- lastname: 'Doe',
123
- email: 'john@doe.com',
124
- phone: '1234567890',
125
- gender: 'male',
126
- dateOfBirth: '1990-01-01',
127
- address: {
128
- city: 'New York',
129
- state: 'NY',
130
- country: 'US',
131
- zip: '10002',
132
- },
133
- // ... other attributes here
134
- },
135
- order: {
136
- id: '123',
137
- currency: 'USD',
138
- total: 100,
139
- products: [
140
- {
141
- id: '123',
142
- name: 'Product 1',
143
- price: 100,
144
- quantity: 1,
145
- currency: 'USD',
146
- sku: '123',
147
- category: 'Category 1',
148
- brand: 'Brand 1',
149
- },
150
- ],
151
- },
152
- // ...other attributes here
153
- });
154
- ```
55
+ `ready()` resolves when Bily can accept queued events and rejects if the browser script fails to load.
155
56
 
156
- If you get stuck, [shoot us an email](mailto:support@bily.ai) or use the Intercom widget on the bottom right of any
157
- page.
57
+ ```ts
58
+ import { ready } from "@bilyai/js";
158
59
 
159
- We're excited you're here! :blue-heart:
60
+ await ready();
61
+ ```
160
62
 
161
- ![This won't be fun to clean up...](https://owlbert.io/images/popper.gif)
63
+ See the [JavaScript SDK documentation](https://docs.bily.ai/sdk/javascript) for React, Next.js, event payload, and
64
+ troubleshooting guides.
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';var ge=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function a(){return typeof window!="undefined"&&typeof document!="undefined"}function m(){if(!a())return null;let e=window[ge];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function p(e,...n){if(typeof e=="function")return e(...n)}var E="sh_client_id",U=null;function we(){var r,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((r=n[6])!=null?r:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let t=Array.from(n,o=>o.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)}`}function pe(){if(!a())return null;try{let e=window.localStorage.getItem(E);return (e==null?void 0:e.trim())||null}catch{return null}}function he(e){if(a())try{window.localStorage.setItem(E,e);}catch{}}function ve(e){try{let n=p(e==null?void 0:e.get,E);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function D(e,n){try{let t=p(e==null?void 0:e.set,E,n);t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{});}catch{}}function L(e){var t,r;if(!a())return null;let n=(r=(t=U!=null?U:pe())!=null?t:ve(e))!=null?r:we();return U=n,he(n),D(e,n),n}var Ee={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},be=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),ke={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},Be={city:"ct",country:"cn",state:"st",zip:"zp"};function f(e){return e!=null&&e!==""}function Ie(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function b(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function Re(e){return Ie({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:b(e.price),product_id:e.id,quantity:b(e.quantity,1),sku:e.sku})}function Y(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null).map(Re):[]}function F(e){var n;return (n=Ee[e])!=null?n:e}function Z(e){return be.has(F(e))}function Se(){var t;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function G(e={},n){var K,W;let{client:t,order:r,pageTitle:i,products:o,searchQuery:c,sourceUrl:s,userAgent:H,...R}=e,u={...R};if(n&&(u.sh_client_id=n),t){for(let[l,v]of Object.entries(ke)){let g=t[l];f(g)&&(u[v]=g);}if(t.address)for(let[l,v]of Object.entries(Be)){let g=t.address[l];f(g)&&(u[v]=g);}}if(f(i)&&(u.page_title=i),f(s)&&(u.event_source_url=s,u.dl=s,u.landing_url=s),f(H)&&(u.uA=H),r){u.order_id=r.id;let l=Y(r.products);l.length>0&&(u.products=l);let v=l.reduce((C,_)=>{let me=typeof _.price=="number"?_.price:0,ye=typeof _.quantity=="number"?_.quantity:1;return C+me*ye},0),g=(K=b(r.total,v))!=null?K:v;u.value=g,u.revenue=g,b(r.tax)!==void 0&&(u.tax=r.tax),b(r.shippingFees)!==void 0&&(u.shippingFees=r.shippingFees),b(r.discount)!==void 0&&(u.discount=r.discount),f(r.discountCode)&&(u.discountCode=r.discountCode);let fe=(W=l.find(C=>f(C.currency)))==null?void 0:W.currency,X=f(r.currency)?r.currency:fe;f(X)&&(u.currency=X);}else {let l=Y(o);l.length>0&&(u.products=l);}return f(c)&&(u.search_query=c,u.query=c),u.ts=typeof R.ts=="string"?R.ts:new Date().toISOString(),u.event_id=f(R.event_id)?R.event_id:Se(),u}var O=100,Pe=1e3,J=15e3,Te=1e3,_e=6e4,Q="bily-tracking-script",ee="__bilySdkFacade",h=null,A=false,d="idle",S=O,w=[],P=N(),ue=0,x=null,B=null,k=null;function N(){let e,n,t=new Promise((r,i)=>{e=r,n=i;});return t.catch(()=>{}),{promise:t,reject:n,resolve:e}}function y(e,n,t){if(!(!A||typeof console=="undefined")){if(e==="warn"){t===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,t);return}t===void 0?console.info("[Bily]",n):console.info("[Bily]",n,t);}}function ne(e){return Number.isFinite(e)?Math.min(Pe,Math.max(1,Math.floor(e!=null?e:O))):O}function te(e){return Number.isFinite(e)?Math.min(_e,Math.max(Te,Math.floor(e!=null?e:J))):J}function z(e){let n=new URL(e),t=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function re(e){let n=z(e.trim()),t=n.pathname.replace(/\/+$/,"");return n.pathname=`${t}/b.js`.replace(/^\/\//,"/"),n.toString()}function ie(e){let n=e.trim();return z(n),n}function Ue(e){try{return /\.m?js$/i.test(z(e.trim()).pathname)}catch{return false}}function Le(e,n){var r,i,o;if(typeof e=="string"){let c=Ue(e)?ie(e):re(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:te(n==null?void 0:n.loadTimeoutMs),maxQueueSize:ne(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:c}}let t=(r=e.scriptUrl)!=null?r:e.trackingDomain;if(!(t!=null&&t.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:te(e.loadTimeoutMs),maxQueueSize:ne(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?ie(e.scriptUrl):re(t)}}function M(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Ae(e){let n=document.getElementById(Q);if(n instanceof HTMLScriptElement&&M(n.src,e))return n;for(let t of Array.from(document.querySelectorAll("script[src]")))if(M(t.src,e))return t;return null}function ce(e,n){let t=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let r=p(t,n.event,n.payload);r&&typeof r.then=="function"&&Promise.resolve(r).catch(i=>y("warn","Event delivery failed.",i));}catch(r){y("warn","Event delivery failed.",r);}}function xe(e){let n=w;w=[];for(let t of n)ce(e,t);}function $(){x!==null&&window.clearTimeout(x),x=null,B!==null&&window.clearTimeout(B),B=null;}function V(e){return e===ue&&d==="loading"}function I(e,n){if(n!==void 0&&!V(n))return;d==="error"&&(P=N()),$(),d="ready",k=null;let t=L(e);t&&D(e,t),xe(e),P.resolve(),y("info","Ready.");}function T(e,n){n!==void 0&&!V(n)||($(),d="error",k&&k.dataset.bilySdkOwned==="true"&&k.remove(),k=null,P.reject(e),y("warn",e.message));}function j(e){if(!V(e))return;let n=m();if(n){I(n,e);return}B===null&&(B=window.setTimeout(()=>{B=null,j(e);},16));}function Me(e){j(e);}function oe(e,n){let t=++ue;k=e,$(),x=window.setTimeout(()=>{let r=m();if(r){I(r,t);return}T(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Me(t),{once:true}),e.addEventListener("error",()=>T(new Error(`Unable to load the Bily browser script from ${h!=null?h:"the configured URL"}.`),t),{once:true}),j(t);}function Ce(e){var o,c;let n=document.getElementById(Q);if(n instanceof HTMLScriptElement&&!M(n.src,e.scriptUrl)){T(new Error("A Bily browser script is already installed with a different URL."));return}let t=Ae(e.scriptUrl);if(t){oe(t,e.loadTimeoutMs);let s=m();s&&I(s);return}let r=document.createElement("script");r.id=Q,r.src=e.scriptUrl,r.async=true,r.referrerPolicy="strict-origin-when-cross-origin",r.dataset.bilySdkOwned="true",e.nonce&&(r.nonce=e.nonce),oe(r,e.loadTimeoutMs);let i=(c=(o=document.head)!=null?o:document.body)!=null?c:document.documentElement;if(!i){T(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(r);}function De(e){w.length>=S&&(w.shift(),y("warn",`Event queue reached ${S}; the oldest event was discarded.`)),w.push(e);}function de(e,n,t){if(!a())return;let r;try{r=String(e!=null?e:"").trim();}catch(s){y("warn","Ignored an event whose name could not be read.",s);return}if(!r){y("warn","Ignored an event with an empty name.");return}q();let i=m(),o=L(i),c;try{c={channel:t!=null?t:Z(r)?"ecommerce":"track",event:F(r),payload:{...G(n!=null?n:{},o),source:"web"}};}catch(s){y("warn",`Ignored ${r} because its payload could not be read.`,s);return}i?(d!=="ready"&&I(i),ce(i,c)):De(c);}function q(){if(!a())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[ee])===true)return;let t={[ee]:true,ecommerce:(r,i)=>de(r,i,"ecommerce"),get:r=>{if(r===E)return ae();let i=m();return p(i==null?void 0:i.get,r)},set:(r,i)=>{let o=m();return p(o==null?void 0:o.set,r,i)},track:(r,i)=>le(r,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:t,writable:!0});}catch{try{e.bily=t;}catch{}}}function se(e,n){var i;if(!a())return;let t;try{t=Le(e,n);}catch(o){if(h&&(d==="loading"||d==="ready")){y("warn","An invalid second initialization was ignored.");return}try{A=typeof e=="object"&&e!==null&&((i=e.debug)!=null?i:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{A=false;}let c=o instanceof Error?o:new Error(String(o));T(c);return}if(h&&!M(h,t.scriptUrl)&&d!=="error"){y("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}A=t.debug,S=t.maxQueueSize,w.length>S&&(w=w.slice(-S)),q(),d==="error"&&(P=N(),d="idle"),h=t.scriptUrl;let r=m();if(r){I(r);return}d==="loading"||d==="ready"||(d="loading",Ce(t));}function le(e,n){de(e,n);}function ae(){return a()?(q(),L(m())):null}function Fe(){if(!a())return Promise.resolve();let e=m();return e&&d!=="ready"&&I(e),P.promise}function We(e,n){se(e,n);}
2
+ exports.getBilyTrackingId=ae;exports.init=We;exports.ready=Fe;exports.track=le;
@@ -0,0 +1,96 @@
1
+ type KnownBilyEvent = "AddContactInfo" | "AddShippingInfo" | "Checkout Address Info Submitted" | "Contact" | "New Customer Purchase" | "PageView" | "Pageview" | "Product Removed From Cart" | "Product Removed From Wishlist" | "ViewCategory" | "Product List Viewed" | "Products Searched" | "Product Clicked" | "Product Added" | "Product Added to Wishlist" | "Product Removed" | "Product Viewed" | "Checkout Step Viewed" | "Checkout Step Completed" | "Shipping Info Entered" | "Order Refunded" | "Clicked Promotion" | "Viewed Promotion" | "Category Viewed" | "Checkout Started" | "Payment Info Entered" | "Payment Add Contact Info" | "Payment Add Shipping Info" | "Payment Add Address Info" | "Subscription" | "New Customer Order" | "New Customer Subscription" | "Order Completed" | "Cart Viewed" | "Remove from Cart" | "Cart Updated" | "Order Updated" | "Order Cancelled" | "Lead" | "Login" | "Logout" | "Search" | "Add to Wishlist" | "Remove from Wishlist" | "View Wishlist" | "Newsletter" | "Contact Form Submitted" | "Subscription Cancelled" | "Subscription Updated" | "Subscription Renewed";
2
+ /** Known Bily events retain autocomplete while custom application events remain valid. */
3
+ type BilyEvent = KnownBilyEvent | (string & Record<never, never>);
4
+ type BilyAddress = {
5
+ city?: string;
6
+ state?: string;
7
+ zip?: string;
8
+ country?: string;
9
+ };
10
+ type BilyClient = {
11
+ firstname?: string;
12
+ lastname?: string;
13
+ dateOfBirth?: string;
14
+ email?: string;
15
+ phone?: string;
16
+ gender?: string;
17
+ address?: BilyAddress;
18
+ userId?: string;
19
+ userGroup?: string;
20
+ };
21
+ type BilyProduct = {
22
+ id: string | number;
23
+ name: string;
24
+ price: number;
25
+ currency: string;
26
+ quantity?: number;
27
+ sku?: string;
28
+ category?: string;
29
+ brand?: string;
30
+ image?: string;
31
+ };
32
+ type BilyOrder = {
33
+ id: string | number;
34
+ products?: BilyProduct[];
35
+ currency?: string;
36
+ total?: number;
37
+ tax?: number;
38
+ discount?: number;
39
+ discountCode?: string;
40
+ shippingFees?: number;
41
+ };
42
+ type BilyPayload = {
43
+ client?: BilyClient;
44
+ order?: BilyOrder;
45
+ products?: BilyProduct[];
46
+ pageTitle?: string;
47
+ userAgent?: string;
48
+ ip?: string;
49
+ referrer?: string;
50
+ sourceUrl?: string;
51
+ source?: "app" | "web";
52
+ category?: string;
53
+ searchQuery?: string;
54
+ eventAlias?: string;
55
+ [key: string]: unknown;
56
+ };
57
+ type BilyInitCommonOptions = {
58
+ /** Print lifecycle diagnostics. Event payloads are never logged. */
59
+ debug?: boolean;
60
+ /** Maximum number of calls retained while the browser script loads. Defaults to 100. */
61
+ maxQueueSize?: number;
62
+ /** Maximum browser-script load time in milliseconds. Defaults to 15000. */
63
+ loadTimeoutMs?: number;
64
+ /** Optional CSP nonce copied onto the injected script element. */
65
+ nonce?: string;
66
+ /** @deprecated Use debug. */
67
+ verbose?: boolean;
68
+ };
69
+ type BilyInitOptions = BilyInitCommonOptions & ({
70
+ /** Exact script URL copied from Bily. Query parameters are preserved. */
71
+ scriptUrl: string;
72
+ trackingDomain?: never;
73
+ } | {
74
+ /** Legacy tracking origin. The SDK loads b.js from this origin. */
75
+ trackingDomain: string;
76
+ scriptUrl?: never;
77
+ });
78
+ type BilyLegacyInitOptions = {
79
+ verbose?: boolean;
80
+ maxQueueSize?: number;
81
+ loadTimeoutMs?: number;
82
+ nonce?: string;
83
+ };
84
+
85
+ declare function track(event: BilyEvent, payload?: BilyPayload): void;
86
+ declare function getBilyTrackingId(): string | null;
87
+ declare function ready(): Promise<void>;
88
+
89
+ /**
90
+ * Initialize Bily with an exact script URL or the legacy tracking-domain form.
91
+ * Repeated calls with the same URL are idempotent.
92
+ */
93
+ declare function init(options: BilyInitOptions): void;
94
+ declare function init(trackingDomainOrScriptUrl: string, options?: BilyLegacyInitOptions): void;
95
+
96
+ export { type BilyAddress, type BilyClient, type BilyEvent, type BilyInitOptions, type BilyLegacyInitOptions, type BilyOrder, type BilyPayload, type BilyProduct, type KnownBilyEvent, getBilyTrackingId, init, ready, track };
@@ -0,0 +1,96 @@
1
+ type KnownBilyEvent = "AddContactInfo" | "AddShippingInfo" | "Checkout Address Info Submitted" | "Contact" | "New Customer Purchase" | "PageView" | "Pageview" | "Product Removed From Cart" | "Product Removed From Wishlist" | "ViewCategory" | "Product List Viewed" | "Products Searched" | "Product Clicked" | "Product Added" | "Product Added to Wishlist" | "Product Removed" | "Product Viewed" | "Checkout Step Viewed" | "Checkout Step Completed" | "Shipping Info Entered" | "Order Refunded" | "Clicked Promotion" | "Viewed Promotion" | "Category Viewed" | "Checkout Started" | "Payment Info Entered" | "Payment Add Contact Info" | "Payment Add Shipping Info" | "Payment Add Address Info" | "Subscription" | "New Customer Order" | "New Customer Subscription" | "Order Completed" | "Cart Viewed" | "Remove from Cart" | "Cart Updated" | "Order Updated" | "Order Cancelled" | "Lead" | "Login" | "Logout" | "Search" | "Add to Wishlist" | "Remove from Wishlist" | "View Wishlist" | "Newsletter" | "Contact Form Submitted" | "Subscription Cancelled" | "Subscription Updated" | "Subscription Renewed";
2
+ /** Known Bily events retain autocomplete while custom application events remain valid. */
3
+ type BilyEvent = KnownBilyEvent | (string & Record<never, never>);
4
+ type BilyAddress = {
5
+ city?: string;
6
+ state?: string;
7
+ zip?: string;
8
+ country?: string;
9
+ };
10
+ type BilyClient = {
11
+ firstname?: string;
12
+ lastname?: string;
13
+ dateOfBirth?: string;
14
+ email?: string;
15
+ phone?: string;
16
+ gender?: string;
17
+ address?: BilyAddress;
18
+ userId?: string;
19
+ userGroup?: string;
20
+ };
21
+ type BilyProduct = {
22
+ id: string | number;
23
+ name: string;
24
+ price: number;
25
+ currency: string;
26
+ quantity?: number;
27
+ sku?: string;
28
+ category?: string;
29
+ brand?: string;
30
+ image?: string;
31
+ };
32
+ type BilyOrder = {
33
+ id: string | number;
34
+ products?: BilyProduct[];
35
+ currency?: string;
36
+ total?: number;
37
+ tax?: number;
38
+ discount?: number;
39
+ discountCode?: string;
40
+ shippingFees?: number;
41
+ };
42
+ type BilyPayload = {
43
+ client?: BilyClient;
44
+ order?: BilyOrder;
45
+ products?: BilyProduct[];
46
+ pageTitle?: string;
47
+ userAgent?: string;
48
+ ip?: string;
49
+ referrer?: string;
50
+ sourceUrl?: string;
51
+ source?: "app" | "web";
52
+ category?: string;
53
+ searchQuery?: string;
54
+ eventAlias?: string;
55
+ [key: string]: unknown;
56
+ };
57
+ type BilyInitCommonOptions = {
58
+ /** Print lifecycle diagnostics. Event payloads are never logged. */
59
+ debug?: boolean;
60
+ /** Maximum number of calls retained while the browser script loads. Defaults to 100. */
61
+ maxQueueSize?: number;
62
+ /** Maximum browser-script load time in milliseconds. Defaults to 15000. */
63
+ loadTimeoutMs?: number;
64
+ /** Optional CSP nonce copied onto the injected script element. */
65
+ nonce?: string;
66
+ /** @deprecated Use debug. */
67
+ verbose?: boolean;
68
+ };
69
+ type BilyInitOptions = BilyInitCommonOptions & ({
70
+ /** Exact script URL copied from Bily. Query parameters are preserved. */
71
+ scriptUrl: string;
72
+ trackingDomain?: never;
73
+ } | {
74
+ /** Legacy tracking origin. The SDK loads b.js from this origin. */
75
+ trackingDomain: string;
76
+ scriptUrl?: never;
77
+ });
78
+ type BilyLegacyInitOptions = {
79
+ verbose?: boolean;
80
+ maxQueueSize?: number;
81
+ loadTimeoutMs?: number;
82
+ nonce?: string;
83
+ };
84
+
85
+ declare function track(event: BilyEvent, payload?: BilyPayload): void;
86
+ declare function getBilyTrackingId(): string | null;
87
+ declare function ready(): Promise<void>;
88
+
89
+ /**
90
+ * Initialize Bily with an exact script URL or the legacy tracking-domain form.
91
+ * Repeated calls with the same URL are idempotent.
92
+ */
93
+ declare function init(options: BilyInitOptions): void;
94
+ declare function init(trackingDomainOrScriptUrl: string, options?: BilyLegacyInitOptions): void;
95
+
96
+ export { type BilyAddress, type BilyClient, type BilyEvent, type BilyInitOptions, type BilyLegacyInitOptions, type BilyOrder, type BilyPayload, type BilyProduct, type KnownBilyEvent, getBilyTrackingId, init, ready, track };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ var ge=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function a(){return typeof window!="undefined"&&typeof document!="undefined"}function m(){if(!a())return null;let e=window[ge];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function p(e,...n){if(typeof e=="function")return e(...n)}var E="sh_client_id",U=null;function we(){var r,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((r=n[6])!=null?r:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let t=Array.from(n,o=>o.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)}`}function pe(){if(!a())return null;try{let e=window.localStorage.getItem(E);return (e==null?void 0:e.trim())||null}catch{return null}}function he(e){if(a())try{window.localStorage.setItem(E,e);}catch{}}function ve(e){try{let n=p(e==null?void 0:e.get,E);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function D(e,n){try{let t=p(e==null?void 0:e.set,E,n);t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{});}catch{}}function L(e){var t,r;if(!a())return null;let n=(r=(t=U!=null?U:pe())!=null?t:ve(e))!=null?r:we();return U=n,he(n),D(e,n),n}var Ee={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},be=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),ke={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},Be={city:"ct",country:"cn",state:"st",zip:"zp"};function f(e){return e!=null&&e!==""}function Ie(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function b(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function Re(e){return Ie({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:b(e.price),product_id:e.id,quantity:b(e.quantity,1),sku:e.sku})}function Y(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null).map(Re):[]}function F(e){var n;return (n=Ee[e])!=null?n:e}function Z(e){return be.has(F(e))}function Se(){var t;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function G(e={},n){var K,W;let{client:t,order:r,pageTitle:i,products:o,searchQuery:c,sourceUrl:s,userAgent:H,...R}=e,u={...R};if(n&&(u.sh_client_id=n),t){for(let[l,v]of Object.entries(ke)){let g=t[l];f(g)&&(u[v]=g);}if(t.address)for(let[l,v]of Object.entries(Be)){let g=t.address[l];f(g)&&(u[v]=g);}}if(f(i)&&(u.page_title=i),f(s)&&(u.event_source_url=s,u.dl=s,u.landing_url=s),f(H)&&(u.uA=H),r){u.order_id=r.id;let l=Y(r.products);l.length>0&&(u.products=l);let v=l.reduce((C,_)=>{let me=typeof _.price=="number"?_.price:0,ye=typeof _.quantity=="number"?_.quantity:1;return C+me*ye},0),g=(K=b(r.total,v))!=null?K:v;u.value=g,u.revenue=g,b(r.tax)!==void 0&&(u.tax=r.tax),b(r.shippingFees)!==void 0&&(u.shippingFees=r.shippingFees),b(r.discount)!==void 0&&(u.discount=r.discount),f(r.discountCode)&&(u.discountCode=r.discountCode);let fe=(W=l.find(C=>f(C.currency)))==null?void 0:W.currency,X=f(r.currency)?r.currency:fe;f(X)&&(u.currency=X);}else {let l=Y(o);l.length>0&&(u.products=l);}return f(c)&&(u.search_query=c,u.query=c),u.ts=typeof R.ts=="string"?R.ts:new Date().toISOString(),u.event_id=f(R.event_id)?R.event_id:Se(),u}var O=100,Pe=1e3,J=15e3,Te=1e3,_e=6e4,Q="bily-tracking-script",ee="__bilySdkFacade",h=null,A=false,d="idle",S=O,w=[],P=N(),ue=0,x=null,B=null,k=null;function N(){let e,n,t=new Promise((r,i)=>{e=r,n=i;});return t.catch(()=>{}),{promise:t,reject:n,resolve:e}}function y(e,n,t){if(!(!A||typeof console=="undefined")){if(e==="warn"){t===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,t);return}t===void 0?console.info("[Bily]",n):console.info("[Bily]",n,t);}}function ne(e){return Number.isFinite(e)?Math.min(Pe,Math.max(1,Math.floor(e!=null?e:O))):O}function te(e){return Number.isFinite(e)?Math.min(_e,Math.max(Te,Math.floor(e!=null?e:J))):J}function z(e){let n=new URL(e),t=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function re(e){let n=z(e.trim()),t=n.pathname.replace(/\/+$/,"");return n.pathname=`${t}/b.js`.replace(/^\/\//,"/"),n.toString()}function ie(e){let n=e.trim();return z(n),n}function Ue(e){try{return /\.m?js$/i.test(z(e.trim()).pathname)}catch{return false}}function Le(e,n){var r,i,o;if(typeof e=="string"){let c=Ue(e)?ie(e):re(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:te(n==null?void 0:n.loadTimeoutMs),maxQueueSize:ne(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:c}}let t=(r=e.scriptUrl)!=null?r:e.trackingDomain;if(!(t!=null&&t.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:te(e.loadTimeoutMs),maxQueueSize:ne(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?ie(e.scriptUrl):re(t)}}function M(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Ae(e){let n=document.getElementById(Q);if(n instanceof HTMLScriptElement&&M(n.src,e))return n;for(let t of Array.from(document.querySelectorAll("script[src]")))if(M(t.src,e))return t;return null}function ce(e,n){let t=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let r=p(t,n.event,n.payload);r&&typeof r.then=="function"&&Promise.resolve(r).catch(i=>y("warn","Event delivery failed.",i));}catch(r){y("warn","Event delivery failed.",r);}}function xe(e){let n=w;w=[];for(let t of n)ce(e,t);}function $(){x!==null&&window.clearTimeout(x),x=null,B!==null&&window.clearTimeout(B),B=null;}function V(e){return e===ue&&d==="loading"}function I(e,n){if(n!==void 0&&!V(n))return;d==="error"&&(P=N()),$(),d="ready",k=null;let t=L(e);t&&D(e,t),xe(e),P.resolve(),y("info","Ready.");}function T(e,n){n!==void 0&&!V(n)||($(),d="error",k&&k.dataset.bilySdkOwned==="true"&&k.remove(),k=null,P.reject(e),y("warn",e.message));}function j(e){if(!V(e))return;let n=m();if(n){I(n,e);return}B===null&&(B=window.setTimeout(()=>{B=null,j(e);},16));}function Me(e){j(e);}function oe(e,n){let t=++ue;k=e,$(),x=window.setTimeout(()=>{let r=m();if(r){I(r,t);return}T(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Me(t),{once:true}),e.addEventListener("error",()=>T(new Error(`Unable to load the Bily browser script from ${h!=null?h:"the configured URL"}.`),t),{once:true}),j(t);}function Ce(e){var o,c;let n=document.getElementById(Q);if(n instanceof HTMLScriptElement&&!M(n.src,e.scriptUrl)){T(new Error("A Bily browser script is already installed with a different URL."));return}let t=Ae(e.scriptUrl);if(t){oe(t,e.loadTimeoutMs);let s=m();s&&I(s);return}let r=document.createElement("script");r.id=Q,r.src=e.scriptUrl,r.async=true,r.referrerPolicy="strict-origin-when-cross-origin",r.dataset.bilySdkOwned="true",e.nonce&&(r.nonce=e.nonce),oe(r,e.loadTimeoutMs);let i=(c=(o=document.head)!=null?o:document.body)!=null?c:document.documentElement;if(!i){T(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(r);}function De(e){w.length>=S&&(w.shift(),y("warn",`Event queue reached ${S}; the oldest event was discarded.`)),w.push(e);}function de(e,n,t){if(!a())return;let r;try{r=String(e!=null?e:"").trim();}catch(s){y("warn","Ignored an event whose name could not be read.",s);return}if(!r){y("warn","Ignored an event with an empty name.");return}q();let i=m(),o=L(i),c;try{c={channel:t!=null?t:Z(r)?"ecommerce":"track",event:F(r),payload:{...G(n!=null?n:{},o),source:"web"}};}catch(s){y("warn",`Ignored ${r} because its payload could not be read.`,s);return}i?(d!=="ready"&&I(i),ce(i,c)):De(c);}function q(){if(!a())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[ee])===true)return;let t={[ee]:true,ecommerce:(r,i)=>de(r,i,"ecommerce"),get:r=>{if(r===E)return ae();let i=m();return p(i==null?void 0:i.get,r)},set:(r,i)=>{let o=m();return p(o==null?void 0:o.set,r,i)},track:(r,i)=>le(r,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:t,writable:!0});}catch{try{e.bily=t;}catch{}}}function se(e,n){var i;if(!a())return;let t;try{t=Le(e,n);}catch(o){if(h&&(d==="loading"||d==="ready")){y("warn","An invalid second initialization was ignored.");return}try{A=typeof e=="object"&&e!==null&&((i=e.debug)!=null?i:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{A=false;}let c=o instanceof Error?o:new Error(String(o));T(c);return}if(h&&!M(h,t.scriptUrl)&&d!=="error"){y("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}A=t.debug,S=t.maxQueueSize,w.length>S&&(w=w.slice(-S)),q(),d==="error"&&(P=N(),d="idle"),h=t.scriptUrl;let r=m();if(r){I(r);return}d==="loading"||d==="ready"||(d="loading",Ce(t));}function le(e,n){de(e,n);}function ae(){return a()?(q(),L(m())):null}function Fe(){if(!a())return Promise.resolve();let e=m();return e&&d!=="ready"&&I(e),P.promise}function We(e,n){se(e,n);}
2
+ export{ae as getBilyTrackingId,We as init,Fe as ready,le as track};
package/package.json CHANGED
@@ -1,37 +1,73 @@
1
1
  {
2
2
  "name": "@bilyai/js",
3
- "private": false,
4
- "version": "1.0.32",
5
- "description": "> TODO: description",
6
- "author": "Babacar NIANG <babacar.basse.niang@gmail.com>",
7
- "homepage": "https://github.com/usepixl/bily-javascript#readme",
3
+ "version": "2.0.0",
4
+ "description": "Official Bily browser SDK for page views, product events, and custom application events.",
8
5
  "license": "ISC",
9
- "main": "lib/index.js",
10
- "typings": "lib/index.d.ts",
11
- "directories": {
12
- "lib": "lib",
13
- "test": "__tests__"
14
- },
15
- "files": [
16
- "lib"
6
+ "author": "Bily <support@bily.ai>",
7
+ "keywords": [
8
+ "analytics",
9
+ "bily",
10
+ "browser",
11
+ "ecommerce",
12
+ "tracking"
17
13
  ],
18
- "repository": {
19
- "type": "git",
20
- "url": "git+https://github.com/usepixl/bily-javascript.git"
14
+ "homepage": "https://docs.bily.ai/sdk/javascript",
15
+ "bugs": {
16
+ "email": "support@bily.ai",
17
+ "url": "https://docs.bily.ai/sdk/troubleshooting"
21
18
  },
22
- "scripts": {
23
- "tsc": "tsc",
24
- "test": "node ./__tests__/browser.test.js"
19
+ "type": "module",
20
+ "main": "./dist/index.cjs",
21
+ "module": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "engines": {
24
+ "node": ">=16"
25
25
  },
26
- "bugs": {
27
- "url": "https://github.com/usepixl/bily-javascript/issues"
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/index.d.cts",
34
+ "default": "./dist/index.cjs"
35
+ }
36
+ },
37
+ "./package.json": "./package.json"
28
38
  },
29
- "gitHead": "2b2b67b083adc4e426228ceac6ed0e2634404a84",
39
+ "files": [
40
+ "dist",
41
+ "README.md",
42
+ "LICENSE",
43
+ "CHANGELOG.md"
44
+ ],
30
45
  "publishConfig": {
31
46
  "access": "public"
32
47
  },
33
- "dependencies": {
34
- "@bilyai/core": "^1.0.32",
35
- "@bilyai/types": "^1.0.32"
48
+ "overrides": {
49
+ "esbuild": "0.28.1"
50
+ },
51
+ "sideEffects": false,
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "typecheck": "tsc --noEmit",
55
+ "test": "vitest run",
56
+ "test:coverage": "vitest run --coverage",
57
+ "check:public": "node scripts/check-public-language.mjs",
58
+ "check:package": "publint && attw --pack .",
59
+ "check:smoke": "node scripts/package-smoke.mjs",
60
+ "check": "npm run typecheck && npm run test:coverage && npm run build && npm run check:public && npm run check:package && npm run check:smoke",
61
+ "prepublishOnly": "npm run check"
62
+ },
63
+ "devDependencies": {
64
+ "@arethetypeswrong/cli": "^0.18.5",
65
+ "@vitest/coverage-v8": "3.2.7",
66
+ "jsdom": "26.1.0",
67
+ "publint": "^0.3.21",
68
+ "tsup": "^8.5.1",
69
+ "typescript": "5.9.3",
70
+ "vite": "6.4.3",
71
+ "vitest": "3.2.7"
36
72
  }
37
73
  }
package/lib/index.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { BilyEvent, BilyPayload } from '@bilyai/types';
2
- declare global {
3
- interface Window {
4
- zaraz: any;
5
- bily: any;
6
- bilyConfig: any;
7
- }
8
- }
9
- declare const getBilyTrackingId: () => string;
10
- declare const init: (domainTracking: string, config?: {
11
- verbose: boolean;
12
- }) => void;
13
- declare const track: (event: BilyEvent, payload: BilyPayload) => void;
14
- export { init, track, getBilyTrackingId };
package/lib/index.js DELETED
@@ -1,96 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getBilyTrackingId = exports.track = exports.init = void 0;
4
- const core_1 = require("@bilyai/core");
5
- const types_1 = require("@bilyai/types");
6
- const initBilyClient = () => {
7
- window.bily = window.zaraz;
8
- };
9
- const getBilyTrackingId = () => {
10
- var _a;
11
- try {
12
- let bilyId = localStorage.getItem(types_1.BILY_EXTERNAL_ID_KEY);
13
- if (!bilyId &&
14
- typeof window !== 'undefined' &&
15
- typeof window.bily !== 'undefined' &&
16
- typeof window.bily.get === 'function') {
17
- bilyId = window.bily.get(types_1.BILY_EXTERNAL_ID_KEY);
18
- }
19
- if (bilyId) {
20
- try {
21
- (_a = window === null || window === void 0 ? void 0 : window.bily) === null || _a === void 0 ? void 0 : _a.set(types_1.BILY_EXTERNAL_ID_KEY, bilyId);
22
- }
23
- catch (error) { }
24
- return bilyId;
25
- }
26
- const newBilyId = (0, core_1.generateExternalId)();
27
- localStorage.setItem(types_1.BILY_EXTERNAL_ID_KEY, newBilyId);
28
- window.bily.set(types_1.BILY_EXTERNAL_ID_KEY, newBilyId);
29
- return newBilyId;
30
- }
31
- catch (error) {
32
- return null;
33
- }
34
- };
35
- exports.getBilyTrackingId = getBilyTrackingId;
36
- const init = (domainTracking, config) => {
37
- if (typeof document === 'undefined' || typeof window === 'undefined') {
38
- console.warn('bily', 'init', 'document or window is undefined');
39
- return;
40
- }
41
- if (document.querySelector('script[id="bily-tracking-script"]')) {
42
- return;
43
- }
44
- if (config) {
45
- window.bilyConfig = config;
46
- }
47
- if (config === null || config === void 0 ? void 0 : config.verbose) {
48
- console.info('bily', 'init', domainTracking, config);
49
- }
50
- const trackingUrl = (0, core_1.getTrackingScriptTagUrl)(domainTracking);
51
- const script = document.createElement('script');
52
- script.id = 'bily-tracking-script';
53
- script.src = trackingUrl;
54
- document.body.appendChild(script);
55
- script.onload = () => {
56
- initBilyClient();
57
- if (typeof window !== 'undefined') {
58
- getBilyTrackingId();
59
- }
60
- };
61
- };
62
- exports.init = init;
63
- const track = (event, payload) => {
64
- var _a, _b;
65
- initBilyClient();
66
- if (typeof window !== 'undefined' && (window === null || window === void 0 ? void 0 : window.bily)) {
67
- const bilyId = getBilyTrackingId();
68
- const data = (0, core_1.mapPayload)(payload, bilyId);
69
- data.source = 'web';
70
- const eventName = (0, core_1.getEventName)(event);
71
- const ecommerce = (0, core_1.isEcommerceEvent)(event);
72
- if (ecommerce) {
73
- window.bily.ecommerce(eventName, data);
74
- }
75
- else {
76
- window.bily.track(eventName, data);
77
- }
78
- if ((_a = window === null || window === void 0 ? void 0 : window.bilyConfig) === null || _a === void 0 ? void 0 : _a.verbose) {
79
- console.info('bily', 'event tracked', event, data);
80
- }
81
- }
82
- else {
83
- if (document.querySelector('script[id="bily-tracking-script"]')) {
84
- setTimeout(() => {
85
- track(event, payload);
86
- }, 1000);
87
- }
88
- else {
89
- if ((_b = window === null || window === void 0 ? void 0 : window.bilyConfig) === null || _b === void 0 ? void 0 : _b.verbose) {
90
- console.warn('bily', 'module not loaded');
91
- }
92
- }
93
- }
94
- };
95
- exports.track = track;
96
- //# sourceMappingURL=index.js.map
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uCAAuH;AACvH,yCAA6E;AAU7E,MAAM,cAAc,GAAG,GAAG,EAAE;IAC1B,MAAM,CAAC,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC;AAC7B,CAAC,CAAC;AAEF,MAAM,iBAAiB,GAAG,GAAW,EAAE;;IACrC,IAAI,CAAC;QACH,IAAI,MAAM,GAAG,YAAY,CAAC,OAAO,CAAC,4BAAoB,CAAC,CAAC;QACxD,IACE,CAAC,MA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