@tolinku/web-sdk 0.5.0 → 0.6.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.
@@ -1,21 +1,21 @@
1
- (function(exports){'use strict';var re="0.5.0";var $=3,je=500,Fe=250,I=class{constructor(e){this.abortController=null;this._baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiKey=e.apiKey;}abort(){this.abortController&&(this.abortController.abort(),this.abortController=null);}get signal(){return this.abortController||(this.abortController=new AbortController),this.abortController.signal}get baseUrl(){return this._baseUrl}get key(){return this.apiKey}async get(e,t){let r=this._baseUrl+e;if(t){let n=new URLSearchParams(t).toString();n&&(r+="?"+n);}let i=await this.fetchWithRetry(r,{method:"GET",headers:this.headers(),signal:this.signal});if(!i.ok){let n=await i.json().catch(()=>({error:i.statusText}));throw new m(n.error||i.statusText,i.status,n.code)}return this.parseJson(i)}async post(e,t){let r=await this.fetchWithRetry(this._baseUrl+e,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:this.signal});if(!r.ok){let i=await r.json().catch(()=>({error:r.statusText}));throw new m(i.error||r.statusText,r.status,i.code)}return this.parseJson(r)}async getPublic(e,t){let r=this._baseUrl+e;if(t){let n=new URLSearchParams(t).toString();n&&(r+="?"+n);}let i=await this.fetchWithRetry(r,{method:"GET",signal:this.signal});if(!i.ok){let n=await i.json().catch(()=>({error:i.statusText}));throw new m(n.error||i.statusText,i.status,n.code)}return this.parseJson(i)}async postPublic(e,t){let r=await this.fetchWithRetry(this._baseUrl+e,{method:"POST",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:this.signal});if(!r.ok){let i=await r.json().catch(()=>({error:r.statusText}));throw new m(i.error||r.statusText,r.status,i.code)}return this.parseJson(r)}async fetchWithRetry(e,t){let r;for(let i=0;i<=$;i++)try{let n=await fetch(e,t);if(n.ok||n.status>=400&&n.status<500&&n.status!==429)return n;if(i<$){let o=this.computeDelay(i,n);await this.sleep(o,t.signal);continue}return n}catch(n){if(n instanceof DOMException&&n.name==="AbortError")throw n;if(r=n,i<$){let o=this.computeDelay(i);await this.sleep(o,t.signal);continue}}throw r}computeDelay(e,t){if(t&&t.status===429){let n=t.headers.get("Retry-After");if(n){let o=Number(n);if(!isNaN(o)&&o>0)return o*1e3}}let r=je*Math.pow(2,e),i=Math.random()*Fe;return r+i}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted){i(new DOMException("The operation was aborted.","AbortError"));return}let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),i(new DOMException("The operation was aborted.","AbortError"));},{once:true});})}async parseJson(e){try{return await e.json()}catch{throw new m("Invalid JSON in response body",e.status)}}headers(){return {"X-API-Key":this.apiKey,"X-Tolinku-SDK":`web/${re}`,Accept:"application/json"}}},m=class extends Error{constructor(e,t,r){super(e),this.name="TolinkuError",this.status=t,this.code=r;}};var R=class{constructor(e){this.client=e;this.queue=[];this.flushTimer=null;this.unloadHandler=null;typeof window<"u"&&(this.unloadHandler=()=>this.flushBeacon(),window.addEventListener("beforeunload",this.unloadHandler));}async track(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error("Tolinku: event name must be a non-empty string");if(e.startsWith("custom.")||(e="custom."+e),!/^custom\.[a-z0-9_]+$/.test(e))throw new Error(`Tolinku: event name "${e}" is invalid. Event names must match the pattern "custom.[a-z0-9_]+" (lowercase letters, numbers, and underscores only after "custom.")`);this.queue.push({event_type:e,properties:t||{}}),this.queue.length===1&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},5e3)),this.queue.length>=10&&await this.flush();}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;let e=this.queue.splice(0);try{let t=await this.client.post("/v1/api/analytics/batch",{events:e});t.errors&&t.errors.length>0&&console.warn("[TolinkuSDK] Batch partial failure:",t.errors);}catch{this.queue.unshift(...e),this.queue.length>1e3&&this.queue.splice(0,this.queue.length-1e3);}}flushBeacon(){if(this.queue.length===0)return;let e=this.queue.splice(0),t=this.client.baseUrl+"/v1/api/analytics/batch",r=JSON.stringify({events:e,apiKey:this.client.key});typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(t,new Blob([r],{type:"application/json"}));}destroy(){this.flushBeacon(),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null);}};var H="tolk_cart_id",B=class{constructor(e,t){this.client=e;this.queue=[];this.flushTimer=null;this.unloadHandler=null;this.memoryCartId=null;this.getUserId=t,typeof window<"u"&&(this.unloadHandler=()=>this.flushBeacon(),window.addEventListener("beforeunload",this.unloadHandler));}async viewItem(e){await this.enqueue({event_type:"view_item",items:e.items});}async addToCart(e){let t=e.cart_id||this.getOrCreateCartId();await this.enqueue({event_type:"add_to_cart",items:e.items,cart_id:t});}async removeFromCart(e){await this.enqueue({event_type:"remove_from_cart",items:e.items,cart_id:e.cart_id||this.getCartId()});}async addToWishlist(e){await this.enqueue({event_type:"add_to_wishlist",items:e.items});}async viewCart(){await this.enqueue({event_type:"view_cart",cart_id:this.getCartId()});}async addPaymentInfo(e){await this.enqueue({event_type:"add_payment_info",cart_id:e?.cart_id||this.getCartId()});}async beginCheckout(e){await this.enqueue({event_type:"begin_checkout",revenue:e.revenue,currency:e.currency,cart_id:e.cart_id||this.getCartId(),items:e.items});}async purchase(e){let t=e.cart_id||this.getCartId();await this.enqueue({event_type:"purchase",transaction_id:e.transaction_id,revenue:e.revenue,currency:e.currency,cart_id:t,coupon_code:e.coupon_code,discount:e.discount,shipping:e.shipping,tax:e.tax,items:e.items}),this.clearCartId();}async refund(e){await this.enqueue({event_type:"refund",transaction_id:e.transaction_id,revenue:e.revenue,currency:e.currency,items:e.items});}async search(e){await this.enqueue({event_type:"search",properties:{search_term:e.search_term}});}async share(e){let t={};e.item_id&&(t.item_id=e.item_id),e.url&&(t.url=e.url),e.method&&(t.method=e.method),await this.enqueue({event_type:"share",properties:t});}async rate(e){await this.enqueue({event_type:"rate",properties:{item_id:e.item_id,rating:String(e.rating),...e.max_rating!=null?{max_rating:String(e.max_rating)}:{}}});}async spendCredits(e){await this.enqueue({event_type:"spend_credits",revenue:e.revenue,currency:e.currency});}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;let e=this.queue.splice(0);try{let t=await this.client.post("/v1/api/analytics/ecommerce/batch",{events:e});t.errors&&t.errors.length>0&&console.warn("[TolinkuSDK] Ecommerce batch partial failure:",t.errors);}catch{this.queue.unshift(...e),this.queue.length>500&&this.queue.splice(0,this.queue.length-500);}}destroy(){this.flushBeacon(),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null);}async enqueue(e){let t=this.getUserId();t&&(e.user_id=t),this.queue.push(e),this.queue.length===1&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},5e3)),this.queue.length>=10&&await this.flush();}flushBeacon(){if(this.queue.length===0)return;let e=this.queue.splice(0),t=this.client.baseUrl+"/v1/api/analytics/ecommerce/batch",r=JSON.stringify({events:e,apiKey:this.client.key});typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(t,new Blob([r],{type:"application/json"}));}getOrCreateCartId(){let e=this.getCartId();if(e)return e;let t=this.generateId();return this.setCartId(t),t}getCartId(){try{if(typeof sessionStorage<"u"){let e=sessionStorage.getItem(H);if(e)return e}}catch{}return this.memoryCartId||void 0}setCartId(e){this.memoryCartId=e;try{typeof sessionStorage<"u"&&sessionStorage.setItem(H,e);}catch{}}clearCartId(){this.memoryCartId=null;try{typeof sessionStorage<"u"&&sessionStorage.removeItem(H);}catch{}}generateId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?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)})}};var A=class{constructor(e){this.client=e;}async create(e){return this.client.post("/v1/api/referral/create",{user_id:e.userId,metadata:e.metadata,user_name:e.userName})}async get(e){return this.client.get(`/v1/api/referral/${encodeURIComponent(e)}`)}async complete(e){return this.client.post("/v1/api/referral/complete",{referral_code:e.code,referred_user_id:e.referredUserId,milestone:e.milestone,referred_user_name:e.referredUserName})}async milestone(e){return this.client.post("/v1/api/referral/milestone",{referral_code:e.code,milestone:e.milestone})}async claimReward(e){return this.client.post("/v1/api/referral/claim-reward",{referral_code:e})}async leaderboard(e=25){return this.client.get("/v1/api/referral/leaderboard",{limit:String(e)})}};var ne="tolinku_deferred_claimed",M=class{constructor(e){this.client=e;}async claimByToken(e){try{return await this.client.getPublic("/v1/api/deferred/claim",{token:e})}catch(t){return console.warn("[Tolinku] Failed to claim deferred link by token:",t),null}}async claimDeferredLink(e){if(!e.appspaceId||!e.appspaceId.trim())throw new Error("Tolinku: appspaceId is required and must not be blank for claimDeferredLink.");if(!e.force&&this.alreadyAttempted())return null;let{link:t,settled:r}=await this.attemptSignals({appspaceId:e.appspaceId});return r&&this.rememberAttempt(),t}alreadyAttempted(){try{return window.localStorage.getItem(ne)!==null}catch{return false}}rememberAttempt(){try{window.localStorage.setItem(ne,new Date().toISOString());}catch{}}async claimBySignals(e){return (await this.attemptSignals(e)).link}async attemptSignals(e){try{return {link:await this.client.postPublic("/v1/api/deferred/claim-by-signals",{appspace_id:e.appspaceId,timezone:b(e.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,language:b(e.language)||navigator.language,screen_width:b(e.screenWidth)||window.screen.width,screen_height:b(e.screenHeight)||window.screen.height,device_pixel_ratio:b(e.devicePixelRatio)||window.devicePixelRatio||1}),settled:!0}}catch(t){let r=t?.statusCode??t?.status;return r===404?{link:null,settled:true}:r===403?(console.warn("[Tolinku] Failed to claim deferred link by signals: HTTP 403.","Check that appspaceId is your Appspace ID (copy it from the dashboard","under Settings), not your subdomain or slug.",t),{link:null,settled:false}):(console.warn("[Tolinku] Failed to claim deferred link by signals:",t),{link:null,settled:false})}}};function b(s){if(typeof s=="string"){let e=s.trim();return e===""?void 0:e}if(typeof s=="number")return Number.isFinite(s)&&s>0?s:void 0}function h(s){if(typeof s!="string")return false;let e=s.trim();if(!e)return false;try{let t=typeof window<"u"?window.location.href:void 0,r=new URL(e,t);return r.protocol==="http:"||r.protocol==="https:"}catch{return false}}var N="tolinku_banner_dismissed",W="tolinku_message_dismissed",j="tolinku_message_impressions",F="tolinku_message_last_shown";function g(s){try{return JSON.parse(localStorage.getItem(s)||"{}")}catch{return {}}}function z(s,e){try{localStorage.setItem(s,JSON.stringify(e));}catch{}}function ie(s,e){if(!e||e<=0)return false;let r=g(N)[s];if(!r)return false;let i=new Date(r).getTime();return Date.now()-i<e*864e5}function se(s){let e=g(N);e[s]=new Date().toISOString(),z(N,e);}function oe(s,e){if(!e||e<=0)return false;let r=g(W)[s];if(!r)return false;let i=new Date(r).getTime();return Date.now()-i<e*864e5}function K(s){let e=g(W);e[s]=new Date().toISOString(),z(W,e);}function ae(s,e,t){if(e!==null&&e>0){let r=g(j);if(parseInt(r[s]||"0",10)>=e)return true}if(t!==null&&t>0){let i=g(F)[s];if(i){let n=new Date(i).getTime(),o=t*36e5;if(Date.now()-n<o)return true}}return false}function le(s){let e=g(j),t=parseInt(e[s]||"0",10);e[s]=String(t+1),z(j,e);let r=g(F);r[s]=new Date().toISOString(),z(F,r);}function c(s){if(!s)return null;let e=s.trim();return /[;{}]/.test(e)?null:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e)||/^(rgb|rgba|hsl|hsla)\([0-9a-zA-Z,.%\s/]+\)$/.test(e)||/^[a-zA-Z-]{1,30}$/.test(e)?e:null}var ce={light:{bg:"#ffffff",border:"",shadow:"sm",title:{color:"#000000",size:14,weight:600},body:{color:"#000000",size:12,weight:400},cta:{size:13,weight:600,radius:100},icon:{size:40,radius:10}},dark:{bg:"#1B1B1B",border:"",shadow:"sm",title:{color:"#ffffff",size:14,weight:600},body:{color:"#ffffff",size:12,weight:400},cta:{size:13,weight:600,radius:100},icon:{size:40,radius:10}}},V={none:"none",sm:"0 2px 8px rgba(0,0,0,0.15)",md:"0 6px 20px rgba(0,0,0,0.18)",lg:"0 12px 36px rgba(0,0,0,0.22)"};function p(s,e,t){return s==null||isNaN(s)?null:Math.max(e,Math.min(t,Math.floor(s)))}function Ke(s){return !s||typeof s!="string"?"":s.replace(/[^a-zA-Z0-9_\-\s]/g,"").slice(0,100).trim()}var U=class{constructor(e){this.client=e;this.container=null;this.styleEl=null;this.currentAnimation="slide";this.currentStyle="pinned";this.currentPosition="top";}async show(e={},t){let r={};t&&(r.user_id=t);let i=await this.client.getPublic("/v1/api/banner/config",r);if(!i.enabled||!i.banners||i.banners.length===0)return;i.banners.sort((a,d)=>d.priority-a.priority);let n=null;for(let a of i.banners)if(!(e.label&&a.label!==e.label)&&!ie(a.id,a.dismiss_days)){n=a;break}if(!n)return;let o=p(e.delay,0,6e4);o&&o>0?setTimeout(()=>this.render(i,n,e),o):this.render(i,n,e);}dismiss(){if(!this.container)return;let e=this.container,t=this.styleEl;e.classList.remove("tolk-visible"),this.currentStyle==="pinned"&&document.body.style.removeProperty(this.currentPosition==="top"?"padding-top":"padding-bottom");let r=()=>{e.remove(),t?.remove(),this.container===e&&(this.container=null,this.styleEl=null);};this.currentAnimation==="none"?r():setTimeout(r,400);}render(e,t,r){this.container&&(this.container.remove(),this.styleEl?.remove(),this.currentStyle==="pinned"&&document.body.style.removeProperty(this.currentPosition==="top"?"padding-top":"padding-bottom"));let i=r.theme&&ce[r.theme]?r.theme:"light",n=ce[i],o="top";r.position==="top"||r.position==="bottom"?o=r.position:(t.position==="top"||t.position==="bottom")&&(o=t.position);let a="pinned";r.style==="pinned"||r.style==="floating"||r.style==="stacked"?a=r.style:(t.style==="pinned"||t.style==="floating"||t.style==="stacked")&&(a=t.style);let d=a==="floating",w=a==="stacked",f=r.animation||"slide";f==="pop"&&!d&&!w&&(f="slide"),this.currentPosition=o,this.currentStyle=a,this.currentAnimation=f;let ue=c(t.background_color),Z=c(t.text_color),me=c(r.bg),pe=c(r.border),ge=c(r.titleColor),he=c(r.bodyColor),fe=c(r.ctaBg),ye=c(r.ctaColor),J=me||ue||n.bg,Q=pe||n.border,D=ge||Z||n.title.color,be=he||Z||n.body.color,ve=fe||n.cta.bg||D,we=ye||n.cta.color||J,_e=p(r.titleSize,10,24)??n.title.size,xe=r.titleWeight??n.title.weight,Ce=p(r.bodySize,10,20)??n.body.size,ke=r.bodyWeight??n.body.weight,Se=p(r.ctaSize,10,18)??n.cta.size,Ee=r.ctaWeight??n.cta.weight,Te=p(r.ctaRadius,0,100)??n.cta.radius,X=p(r.iconSize,24,64)??n.icon.size,Pe=p(r.iconRadius,0,32)??n.icon.radius,Ie=p(r.radius,0,24),Re=typeof t.radius=="number"&&t.radius>=0&&t.radius<=24?t.radius:null,Be=p(r.margin,0,24),Ae=typeof t.margin=="number"&&t.margin>=0&&t.margin<=24?t.margin:null,Y=d?Ie??Re??12:0,_=d?Be??Ae??12:0,Me=r.shadow&&V[r.shadow]?r.shadow:t.shadow&&V[t.shadow]?t.shadow:n.shadow,ze=V[Me],Ue=!!r.hideIcon,Oe=!!r.hideClose,De=!!r.hideBody,G=Ke(r.customClass),qe=t.cta_text||"Open",ee=t.action_url||this.client.baseUrl+(e.install_url||"/install"),Le=o==="top"?"padding-top: env(safe-area-inset-top, 0px);":"",$e=o==="bottom"?"padding-bottom: env(safe-area-inset-bottom, 0px);":"",x,C;w?(x="position: sticky;",C=`${o}: 0;`):d?(x="position: fixed;",C=`left: ${_}px; right: ${_}px; ${o}: ${_}px;`):(x="position: fixed;",C=`left: 0; right: 0; ${o}: 0;`);let te=_+60,He=o==="top"?`translateY(calc(-100% - ${te}px))`:`translateY(calc(100% + ${te}px))`,k="",S="",E="";f==="slide"?(k=`transform: ${He};`,S="transform: translateY(0);",E="transition: transform 0.35s ease;"):f==="fade"?(k="opacity: 0;",S="opacity: 1;",E="transition: opacity 0.3s ease;"):f==="pop"&&(k="opacity: 0; transform: scale(0.92);",S="opacity: 1; transform: scale(1);",E="transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.25s ease;");let u=document.createElement("div");u.id="tolinku-banner",u.setAttribute("role","banner"),u.setAttribute("aria-live","polite"),u.dataset.position=o,G&&(u.className=G);let Ne=Q?`border: 1px solid ${Q};`:"",We=Y>0?`border-radius: ${Y}px;`:"",q=document.createElement("style");q.textContent=`
1
+ (function(exports){'use strict';var ne="0.6.0";var H=3,Fe=500,Ke=250,I=class{constructor(e){this.abortController=null;this._baseUrl=e.baseUrl.replace(/\/+$/,""),this.apiKey=e.apiKey;}abort(){this.abortController&&(this.abortController.abort(),this.abortController=null);}get signal(){return this.abortController||(this.abortController=new AbortController),this.abortController.signal}get baseUrl(){return this._baseUrl}get key(){return this.apiKey}async get(e,t){let r=this._baseUrl+e;if(t){let n=new URLSearchParams(t).toString();n&&(r+="?"+n);}let i=await this.fetchWithRetry(r,{method:"GET",headers:this.headers(),signal:this.signal});if(!i.ok){let n=await i.json().catch(()=>({error:i.statusText}));throw new m(n.error||i.statusText,i.status,n.code)}return this.parseJson(i)}async post(e,t){let r=await this.fetchWithRetry(this._baseUrl+e,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:this.signal});if(!r.ok){let i=await r.json().catch(()=>({error:r.statusText}));throw new m(i.error||r.statusText,r.status,i.code)}return this.parseJson(r)}async postPublicToOrigin(e,t,r){let i=await this.fetchWithRetry(e.replace(/\/+$/,"")+t,{method:"POST",headers:{"Content-Type":"application/json"},body:r?JSON.stringify(r):void 0,signal:this.signal});if(!i.ok){let n=await i.json().catch(()=>({error:i.statusText}));throw new m(n.error||i.statusText,i.status,n.code)}return this.parseJson(i)}async getPublic(e,t){let r=this._baseUrl+e;if(t){let n=new URLSearchParams(t).toString();n&&(r+="?"+n);}let i=await this.fetchWithRetry(r,{method:"GET",signal:this.signal});if(!i.ok){let n=await i.json().catch(()=>({error:i.statusText}));throw new m(n.error||i.statusText,i.status,n.code)}return this.parseJson(i)}async postPublic(e,t){let r=await this.fetchWithRetry(this._baseUrl+e,{method:"POST",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:this.signal});if(!r.ok){let i=await r.json().catch(()=>({error:r.statusText}));throw new m(i.error||r.statusText,r.status,i.code)}return this.parseJson(r)}async fetchWithRetry(e,t){let r;for(let i=0;i<=H;i++)try{let n=await fetch(e,t);if(n.ok||n.status>=400&&n.status<500&&n.status!==429)return n;if(i<H){let o=this.computeDelay(i,n);await this.sleep(o,t.signal);continue}return n}catch(n){if(n instanceof DOMException&&n.name==="AbortError")throw n;if(r=n,i<H){let o=this.computeDelay(i);await this.sleep(o,t.signal);continue}}throw r}computeDelay(e,t){if(t&&t.status===429){let n=t.headers.get("Retry-After");if(n){let o=Number(n);if(!isNaN(o)&&o>0)return o*1e3}}let r=Fe*Math.pow(2,e),i=Math.random()*Ke;return r+i}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted){i(new DOMException("The operation was aborted.","AbortError"));return}let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),i(new DOMException("The operation was aborted.","AbortError"));},{once:true});})}async parseJson(e){try{return await e.json()}catch{throw new m("Invalid JSON in response body",e.status)}}headers(){return {"X-API-Key":this.apiKey,"X-Tolinku-SDK":`web/${ne}`,Accept:"application/json"}}},m=class extends Error{constructor(e,t,r){super(e),this.name="TolinkuError",this.status=t,this.code=r;}};var R=class{constructor(e){this.client=e;this.queue=[];this.flushTimer=null;this.unloadHandler=null;typeof window<"u"&&(this.unloadHandler=()=>this.flushBeacon(),window.addEventListener("beforeunload",this.unloadHandler));}async track(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error("Tolinku: event name must be a non-empty string");if(e.startsWith("custom.")||(e="custom."+e),!/^custom\.[a-z0-9_]+$/.test(e))throw new Error(`Tolinku: event name "${e}" is invalid. Event names must match the pattern "custom.[a-z0-9_]+" (lowercase letters, numbers, and underscores only after "custom.")`);this.queue.push({event_type:e,properties:t||{}}),this.queue.length===1&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},5e3)),this.queue.length>=10&&await this.flush();}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;let e=this.queue.splice(0);try{let t=await this.client.post("/v1/api/analytics/batch",{events:e});t.errors&&t.errors.length>0&&console.warn("[TolinkuSDK] Batch partial failure:",t.errors);}catch{this.queue.unshift(...e),this.queue.length>1e3&&this.queue.splice(0,this.queue.length-1e3);}}flushBeacon(){if(this.queue.length===0)return;let e=this.queue.splice(0),t=this.client.baseUrl+"/v1/api/analytics/batch",r=JSON.stringify({events:e,apiKey:this.client.key});typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(t,new Blob([r],{type:"application/json"}));}destroy(){this.flushBeacon(),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null);}};var N="tolk_cart_id",B=class{constructor(e,t){this.client=e;this.queue=[];this.flushTimer=null;this.unloadHandler=null;this.memoryCartId=null;this.getUserId=t,typeof window<"u"&&(this.unloadHandler=()=>this.flushBeacon(),window.addEventListener("beforeunload",this.unloadHandler));}async viewItem(e){await this.enqueue({event_type:"view_item",items:e.items});}async addToCart(e){let t=e.cart_id||this.getOrCreateCartId();await this.enqueue({event_type:"add_to_cart",items:e.items,cart_id:t});}async removeFromCart(e){await this.enqueue({event_type:"remove_from_cart",items:e.items,cart_id:e.cart_id||this.getCartId()});}async addToWishlist(e){await this.enqueue({event_type:"add_to_wishlist",items:e.items});}async viewCart(){await this.enqueue({event_type:"view_cart",cart_id:this.getCartId()});}async addPaymentInfo(e){await this.enqueue({event_type:"add_payment_info",cart_id:e?.cart_id||this.getCartId()});}async beginCheckout(e){await this.enqueue({event_type:"begin_checkout",revenue:e.revenue,currency:e.currency,cart_id:e.cart_id||this.getCartId(),items:e.items});}async purchase(e){let t=e.cart_id||this.getCartId();await this.enqueue({event_type:"purchase",transaction_id:e.transaction_id,revenue:e.revenue,currency:e.currency,cart_id:t,coupon_code:e.coupon_code,discount:e.discount,shipping:e.shipping,tax:e.tax,items:e.items}),this.clearCartId();}async refund(e){await this.enqueue({event_type:"refund",transaction_id:e.transaction_id,revenue:e.revenue,currency:e.currency,items:e.items});}async search(e){await this.enqueue({event_type:"search",properties:{search_term:e.search_term}});}async share(e){let t={};e.item_id&&(t.item_id=e.item_id),e.url&&(t.url=e.url),e.method&&(t.method=e.method),await this.enqueue({event_type:"share",properties:t});}async rate(e){await this.enqueue({event_type:"rate",properties:{item_id:e.item_id,rating:String(e.rating),...e.max_rating!=null?{max_rating:String(e.max_rating)}:{}}});}async spendCredits(e){await this.enqueue({event_type:"spend_credits",revenue:e.revenue,currency:e.currency});}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;let e=this.queue.splice(0);try{let t=await this.client.post("/v1/api/analytics/ecommerce/batch",{events:e});t.errors&&t.errors.length>0&&console.warn("[TolinkuSDK] Ecommerce batch partial failure:",t.errors);}catch{this.queue.unshift(...e),this.queue.length>500&&this.queue.splice(0,this.queue.length-500);}}destroy(){this.flushBeacon(),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&this.unloadHandler&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null);}async enqueue(e){let t=this.getUserId();t&&(e.user_id=t),this.queue.push(e),this.queue.length===1&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush();},5e3)),this.queue.length>=10&&await this.flush();}flushBeacon(){if(this.queue.length===0)return;let e=this.queue.splice(0),t=this.client.baseUrl+"/v1/api/analytics/ecommerce/batch",r=JSON.stringify({events:e,apiKey:this.client.key});typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(t,new Blob([r],{type:"application/json"}));}getOrCreateCartId(){let e=this.getCartId();if(e)return e;let t=this.generateId();return this.setCartId(t),t}getCartId(){try{if(typeof sessionStorage<"u"){let e=sessionStorage.getItem(N);if(e)return e}}catch{}return this.memoryCartId||void 0}setCartId(e){this.memoryCartId=e;try{typeof sessionStorage<"u"&&sessionStorage.setItem(N,e);}catch{}}clearCartId(){this.memoryCartId=null;try{typeof sessionStorage<"u"&&sessionStorage.removeItem(N);}catch{}}generateId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?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)})}};var A=class{constructor(e){this.client=e;}async create(e){return this.client.post("/v1/api/referral/create",{user_id:e.userId,metadata:e.metadata,user_name:e.userName})}async get(e){return this.client.get(`/v1/api/referral/${encodeURIComponent(e)}`)}async complete(e){return this.client.post("/v1/api/referral/complete",{referral_code:e.code,referred_user_id:e.referredUserId,milestone:e.milestone,referred_user_name:e.referredUserName})}async milestone(e){return this.client.post("/v1/api/referral/milestone",{referral_code:e.code,milestone:e.milestone})}async claimReward(e){return this.client.post("/v1/api/referral/claim-reward",{referral_code:e})}async leaderboard(e=25){return this.client.get("/v1/api/referral/leaderboard",{limit:String(e)})}};var ie="tolinku_deferred_claimed",M=class{constructor(e){this.client=e;}async claimByToken(e){try{return await this.client.getPublic("/v1/api/deferred/claim",{token:e})}catch(t){return console.warn("[Tolinku] Failed to claim deferred link by token:",t),null}}async claimDeferredLink(e){if(!e.appspaceId||!e.appspaceId.trim())throw new Error("Tolinku: appspaceId is required and must not be blank for claimDeferredLink.");if(!e.force&&this.alreadyAttempted())return null;let{link:t,settled:r}=await this.attemptSignals({appspaceId:e.appspaceId});return r&&this.rememberAttempt(),t}alreadyAttempted(){try{return window.localStorage.getItem(ie)!==null}catch{return false}}rememberAttempt(){try{window.localStorage.setItem(ie,new Date().toISOString());}catch{}}async claimBySignals(e){return (await this.attemptSignals(e)).link}async attemptSignals(e){try{return {link:await this.client.postPublic("/v1/api/deferred/claim-by-signals",{appspace_id:e.appspaceId,timezone:b(e.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,language:b(e.language)||navigator.language,screen_width:b(e.screenWidth)||window.screen.width,screen_height:b(e.screenHeight)||window.screen.height,device_pixel_ratio:b(e.devicePixelRatio)||window.devicePixelRatio||1}),settled:!0}}catch(t){let r=t?.statusCode??t?.status;return r===404?{link:null,settled:true}:r===403?(console.warn("[Tolinku] Failed to claim deferred link by signals: HTTP 403.","Check that appspaceId is your Appspace ID (copy it from the dashboard","under Settings), not your subdomain or slug.",t),{link:null,settled:false}):(console.warn("[Tolinku] Failed to claim deferred link by signals:",t),{link:null,settled:false})}}};function b(s){if(typeof s=="string"){let e=s.trim();return e===""?void 0:e}if(typeof s=="number")return Number.isFinite(s)&&s>0?s:void 0}function Je(s){return typeof s=="string"&&s.startsWith("/")&&!s.startsWith("//")}var U=class{constructor(e){this.client=e;}async resolve(e){if(!e||typeof e!="string")return null;let t;try{t=new URL(e.trim());}catch{return null}if(t.protocol!=="https:"&&t.protocol!=="http:")return null;try{let r=await this.client.postPublicToOrigin(t.origin,"/v1/api/path",{path:t.pathname});return !r||!r.route||!Je(r.deep_link_path)?null:r}catch{return null}}};function h(s){if(typeof s!="string")return false;let e=s.trim();if(!e)return false;try{let t=typeof window<"u"?window.location.href:void 0,r=new URL(e,t);return r.protocol==="http:"||r.protocol==="https:"}catch{return false}}var W="tolinku_banner_dismissed",j="tolinku_message_dismissed",F="tolinku_message_impressions",K="tolinku_message_last_shown";function g(s){try{return JSON.parse(localStorage.getItem(s)||"{}")}catch{return {}}}function O(s,e){try{localStorage.setItem(s,JSON.stringify(e));}catch{}}function se(s,e){if(!e||e<=0)return false;let r=g(W)[s];if(!r)return false;let i=new Date(r).getTime();return Date.now()-i<e*864e5}function oe(s){let e=g(W);e[s]=new Date().toISOString(),O(W,e);}function ae(s,e){if(!e||e<=0)return false;let r=g(j)[s];if(!r)return false;let i=new Date(r).getTime();return Date.now()-i<e*864e5}function J(s){let e=g(j);e[s]=new Date().toISOString(),O(j,e);}function le(s,e,t){if(e!==null&&e>0){let r=g(F);if(parseInt(r[s]||"0",10)>=e)return true}if(t!==null&&t>0){let i=g(K)[s];if(i){let n=new Date(i).getTime(),o=t*36e5;if(Date.now()-n<o)return true}}return false}function ce(s){let e=g(F),t=parseInt(e[s]||"0",10);e[s]=String(t+1),O(F,e);let r=g(K);r[s]=new Date().toISOString(),O(K,r);}function c(s){if(!s)return null;let e=s.trim();return /[;{}]/.test(e)?null:/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e)||/^(rgb|rgba|hsl|hsla)\([0-9a-zA-Z,.%\s/]+\)$/.test(e)||/^[a-zA-Z-]{1,30}$/.test(e)?e:null}var de={light:{bg:"#ffffff",border:"",shadow:"sm",title:{color:"#000000",size:14,weight:600},body:{color:"#000000",size:12,weight:400},cta:{size:13,weight:600,radius:100},icon:{size:40,radius:10}},dark:{bg:"#1B1B1B",border:"",shadow:"sm",title:{color:"#ffffff",size:14,weight:600},body:{color:"#ffffff",size:12,weight:400},cta:{size:13,weight:600,radius:100},icon:{size:40,radius:10}}},V={none:"none",sm:"0 2px 8px rgba(0,0,0,0.15)",md:"0 6px 20px rgba(0,0,0,0.18)",lg:"0 12px 36px rgba(0,0,0,0.22)"};function p(s,e,t){return s==null||isNaN(s)?null:Math.max(e,Math.min(t,Math.floor(s)))}function Ve(s){return !s||typeof s!="string"?"":s.replace(/[^a-zA-Z0-9_\-\s]/g,"").slice(0,100).trim()}var z=class{constructor(e){this.client=e;this.container=null;this.styleEl=null;this.currentAnimation="slide";this.currentStyle="pinned";this.currentPosition="top";}async show(e={},t){let r={};t&&(r.user_id=t);let i=await this.client.getPublic("/v1/api/banner/config",r);if(!i.enabled||!i.banners||i.banners.length===0)return;i.banners.sort((a,d)=>d.priority-a.priority);let n=null;for(let a of i.banners)if(!(e.label&&a.label!==e.label)&&!se(a.id,a.dismiss_days)){n=a;break}if(!n)return;let o=p(e.delay,0,6e4);o&&o>0?setTimeout(()=>this.render(i,n,e),o):this.render(i,n,e);}dismiss(){if(!this.container)return;let e=this.container,t=this.styleEl;e.classList.remove("tolk-visible"),this.currentStyle==="pinned"&&document.body.style.removeProperty(this.currentPosition==="top"?"padding-top":"padding-bottom");let r=()=>{e.remove(),t?.remove(),this.container===e&&(this.container=null,this.styleEl=null);};this.currentAnimation==="none"?r():setTimeout(r,400);}render(e,t,r){this.container&&(this.container.remove(),this.styleEl?.remove(),this.currentStyle==="pinned"&&document.body.style.removeProperty(this.currentPosition==="top"?"padding-top":"padding-bottom"));let i=r.theme&&de[r.theme]?r.theme:"light",n=de[i],o="top";r.position==="top"||r.position==="bottom"?o=r.position:(t.position==="top"||t.position==="bottom")&&(o=t.position);let a="pinned";r.style==="pinned"||r.style==="floating"||r.style==="stacked"?a=r.style:(t.style==="pinned"||t.style==="floating"||t.style==="stacked")&&(a=t.style);let d=a==="floating",w=a==="stacked",f=r.animation||"slide";f==="pop"&&!d&&!w&&(f="slide"),this.currentPosition=o,this.currentStyle=a,this.currentAnimation=f;let me=c(t.background_color),Z=c(t.text_color),pe=c(r.bg),ge=c(r.border),he=c(r.titleColor),fe=c(r.bodyColor),ye=c(r.ctaBg),be=c(r.ctaColor),Q=pe||me||n.bg,X=ge||n.border,D=he||Z||n.title.color,ve=fe||Z||n.body.color,we=ye||n.cta.bg||D,_e=be||n.cta.color||Q,xe=p(r.titleSize,10,24)??n.title.size,ke=r.titleWeight??n.title.weight,Ce=p(r.bodySize,10,20)??n.body.size,Se=r.bodyWeight??n.body.weight,Te=p(r.ctaSize,10,18)??n.cta.size,Ee=r.ctaWeight??n.cta.weight,Pe=p(r.ctaRadius,0,100)??n.cta.radius,Y=p(r.iconSize,24,64)??n.icon.size,Ie=p(r.iconRadius,0,32)??n.icon.radius,Re=p(r.radius,0,24),Be=typeof t.radius=="number"&&t.radius>=0&&t.radius<=24?t.radius:null,Ae=p(r.margin,0,24),Me=typeof t.margin=="number"&&t.margin>=0&&t.margin<=24?t.margin:null,G=d?Re??Be??12:0,_=d?Ae??Me??12:0,Ue=r.shadow&&V[r.shadow]?r.shadow:t.shadow&&V[t.shadow]?t.shadow:n.shadow,Oe=V[Ue],ze=!!r.hideIcon,Le=!!r.hideClose,De=!!r.hideBody,ee=Ve(r.customClass),qe=t.cta_text||"Open",te=t.action_url||this.client.baseUrl+(e.install_url||"/install"),$e=o==="top"?"padding-top: env(safe-area-inset-top, 0px);":"",He=o==="bottom"?"padding-bottom: env(safe-area-inset-bottom, 0px);":"",x,k;w?(x="position: sticky;",k=`${o}: 0;`):d?(x="position: fixed;",k=`left: ${_}px; right: ${_}px; ${o}: ${_}px;`):(x="position: fixed;",k=`left: 0; right: 0; ${o}: 0;`);let re=_+60,Ne=o==="top"?`translateY(calc(-100% - ${re}px))`:`translateY(calc(100% + ${re}px))`,C="",S="",T="";f==="slide"?(C=`transform: ${Ne};`,S="transform: translateY(0);",T="transition: transform 0.35s ease;"):f==="fade"?(C="opacity: 0;",S="opacity: 1;",T="transition: opacity 0.3s ease;"):f==="pop"&&(C="opacity: 0; transform: scale(0.92);",S="opacity: 1; transform: scale(1);",T="transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.25s ease;");let u=document.createElement("div");u.id="tolinku-banner",u.setAttribute("role","banner"),u.setAttribute("aria-live","polite"),u.dataset.position=o,ee&&(u.className=ee);let We=X?`border: 1px solid ${X};`:"",je=G>0?`border-radius: ${G}px;`:"",q=document.createElement("style");q.textContent=`
2
2
  #tolinku-banner {
3
3
  ${x}
4
- ${C}
4
+ ${k}
5
5
  z-index: 999999;
6
6
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
7
- ${k}
8
- ${E}
9
- ${Le}${$e}
7
+ ${C}
8
+ ${T}
9
+ ${$e}${He}
10
10
  }
11
11
  #tolinku-banner.tolk-visible { ${S} }
12
12
  #tolinku-banner .tolk-inner {
13
13
  display: flex; align-items: center; gap: 10px;
14
14
  padding: 10px 14px;
15
- background: ${J};
16
- ${Ne}
15
+ background: ${Q};
17
16
  ${We}
18
- box-shadow: ${ze};
17
+ ${je}
18
+ box-shadow: ${Oe};
19
19
  }
20
20
  #tolinku-banner .tolk-close {
21
21
  background: none; border: none; font-size: 20px; line-height: 1;
@@ -23,27 +23,27 @@
23
23
  }
24
24
  #tolinku-banner .tolk-close:hover { opacity: 1; }
25
25
  #tolinku-banner .tolk-icon {
26
- width: ${X}px; height: ${X}px; border-radius: ${Pe}px;
26
+ width: ${Y}px; height: ${Y}px; border-radius: ${Ie}px;
27
27
  flex-shrink: 0; object-fit: cover;
28
28
  }
29
29
  #tolinku-banner .tolk-text { flex: 1; min-width: 0; }
30
30
  #tolinku-banner .tolk-title {
31
- font-size: ${_e}px; font-weight: ${xe}; line-height: 1.3;
31
+ font-size: ${xe}px; font-weight: ${ke}; line-height: 1.3;
32
32
  color: ${D}; margin: 0;
33
33
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
34
34
  }
35
35
  #tolinku-banner .tolk-body {
36
- font-size: ${Ce}px; font-weight: ${ke}; line-height: 1.3;
37
- color: ${be}; margin: 0; opacity: 0.75;
36
+ font-size: ${Ce}px; font-weight: ${Se}; line-height: 1.3;
37
+ color: ${ve}; margin: 0; opacity: 0.75;
38
38
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
39
39
  }
40
40
  #tolinku-banner .tolk-cta {
41
- display: inline-block; padding: 0.5em 1.2em; border-radius: ${Te}px;
42
- font-size: ${Se}px; font-weight: ${Ee}; line-height: 1.2;
43
- text-decoration: none; background: ${ve}; color: ${we};
41
+ display: inline-block; padding: 0.5em 1.2em; border-radius: ${Pe}px;
42
+ font-size: ${Te}px; font-weight: ${Ee}; line-height: 1.2;
43
+ text-decoration: none; background: ${we}; color: ${_e};
44
44
  flex-shrink: 0; text-align: center;
45
45
  }
46
- `;let y=document.createElement("div");if(y.className="tolk-inner",!Oe){let l=document.createElement("button");l.className="tolk-close",l.setAttribute("aria-label","Dismiss banner"),l.textContent="\xD7",l.addEventListener("click",()=>{se(t.id),this.dismiss();}),y.appendChild(l);}if(!Ue&&e.app_icon&&h(e.app_icon)){let l=document.createElement("img");l.className="tolk-icon",l.src=e.app_icon,l.alt=e.app_name||"App",y.appendChild(l);}let T=document.createElement("div");T.className="tolk-text";let L=document.createElement("p");if(L.className="tolk-title",L.textContent=t.title||e.app_name||"Get the App",T.appendChild(L),!De&&t.body){let l=document.createElement("p");l.className="tolk-body",l.textContent=t.body,T.appendChild(l);}y.appendChild(T);let P=document.createElement("a");if(P.className="tolk-cta",P.href=h(ee)?ee:"#",P.textContent=qe,y.appendChild(P),u.appendChild(y),document.head.appendChild(q),w){let l=Ve(o,r.anchor);l&&l.parentNode?o==="top"?l.parentNode.insertBefore(u,l):l.nextSibling?l.parentNode.insertBefore(u,l.nextSibling):l.parentNode.appendChild(u):document.body&&(o==="top"?document.body.insertBefore(u,document.body.firstChild):document.body.appendChild(u));}else document.body.appendChild(u);this.container=u,this.styleEl=q,requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(u.classList.add("tolk-visible"),!d&&!w){let l=u.offsetHeight+"px";o==="top"?document.body.style.paddingTop=l:document.body.style.paddingBottom=l;}});});}};function Ve(s,e){if(e)try{let r=document.querySelector(e);if(r)return r}catch{}let t=s==="top"?["header",'[role="banner"]',"nav",".header","#header",".navbar"]:["footer",'[role="contentinfo"]',".footer","#footer"];for(let r of t){let i=document.body?.querySelector(r);if(i)return i}return null}var O=class{constructor(e){this.client=e;this.overlay=null;this.styleEl=null;}async show(e={},t){let r={};e.trigger&&(r.trigger=e.trigger),t&&(r.user_id=t);let i=await this.client.get("/v1/api/messages",r);if(!i.messages||i.messages.length===0)return;let n=i.messages.filter(a=>!oe(a.id,a.dismiss_days)).filter(a=>!ae(a.id,a.max_impressions,a.min_interval_hours)).filter(a=>!e.triggerValue||a.trigger_value===e.triggerValue).sort((a,d)=>d.priority-a.priority);if(n.length===0)return;let o=n[0];le(o.id),this.render(o,e);}dismiss(){this.overlay&&(this.overlay.style.opacity="0",setTimeout(()=>{this.overlay?.remove(),this.styleEl?.remove(),this.overlay=null,this.styleEl=null;},300));}render(e,t){this.overlay&&(this.overlay.remove(),this.styleEl?.remove());let r=document.createElement("style");r.textContent=`
46
+ `;let y=document.createElement("div");if(y.className="tolk-inner",!Le){let l=document.createElement("button");l.className="tolk-close",l.setAttribute("aria-label","Dismiss banner"),l.textContent="\xD7",l.addEventListener("click",()=>{oe(t.id),this.dismiss();}),y.appendChild(l);}if(!ze&&e.app_icon&&h(e.app_icon)){let l=document.createElement("img");l.className="tolk-icon",l.src=e.app_icon,l.alt=e.app_name||"App",y.appendChild(l);}let E=document.createElement("div");E.className="tolk-text";let $=document.createElement("p");if($.className="tolk-title",$.textContent=t.title||e.app_name||"Get the App",E.appendChild($),!De&&t.body){let l=document.createElement("p");l.className="tolk-body",l.textContent=t.body,E.appendChild(l);}y.appendChild(E);let P=document.createElement("a");if(P.className="tolk-cta",P.href=h(te)?te:"#",P.textContent=qe,y.appendChild(P),u.appendChild(y),document.head.appendChild(q),w){let l=Ze(o,r.anchor);l&&l.parentNode?o==="top"?l.parentNode.insertBefore(u,l):l.nextSibling?l.parentNode.insertBefore(u,l.nextSibling):l.parentNode.appendChild(u):document.body&&(o==="top"?document.body.insertBefore(u,document.body.firstChild):document.body.appendChild(u));}else document.body.appendChild(u);this.container=u,this.styleEl=q,requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(u.classList.add("tolk-visible"),!d&&!w){let l=u.offsetHeight+"px";o==="top"?document.body.style.paddingTop=l:document.body.style.paddingBottom=l;}});});}};function Ze(s,e){if(e)try{let r=document.querySelector(e);if(r)return r}catch{}let t=s==="top"?["header",'[role="banner"]',"nav",".header","#header",".navbar"]:["footer",'[role="contentinfo"]',".footer","#footer"];for(let r of t){let i=document.body?.querySelector(r);if(i)return i}return null}var L=class{constructor(e){this.client=e;this.overlay=null;this.styleEl=null;}async show(e={},t){let r={};e.trigger&&(r.trigger=e.trigger),t&&(r.user_id=t);let i=await this.client.get("/v1/api/messages",r);if(!i.messages||i.messages.length===0)return;let n=i.messages.filter(a=>!ae(a.id,a.dismiss_days)).filter(a=>!le(a.id,a.max_impressions,a.min_interval_hours)).filter(a=>!e.triggerValue||a.trigger_value===e.triggerValue).sort((a,d)=>d.priority-a.priority);if(n.length===0)return;let o=n[0];ce(o.id),this.render(o,e);}dismiss(){this.overlay&&(this.overlay.style.opacity="0",setTimeout(()=>{this.overlay?.remove(),this.styleEl?.remove(),this.overlay=null,this.styleEl=null;},300));}render(e,t){this.overlay&&(this.overlay.remove(),this.styleEl?.remove());let r=document.createElement("style");r.textContent=`
47
47
  .tolk-msg-overlay {
48
48
  position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1000000;
49
49
  display: flex; align-items: center; justify-content: center;
@@ -66,6 +66,6 @@
66
66
  color: inherit; opacity: 0.6;
67
67
  }
68
68
  .tolk-msg-close:hover { opacity: 1; }
69
- `;let i=document.createElement("div");i.className="tolk-msg-overlay",i.addEventListener("click",a=>{a.target===i&&(K(e.id),t.onDismiss?.(e.id),this.dismiss());});let n=document.createElement("div");n.className="tolk-msg-card",n.style.background=c(e.background_color)||"#ffffff";let o=document.createElement("button");if(o.className="tolk-msg-close",o.setAttribute("aria-label","Close message"),o.textContent="\xD7",o.addEventListener("click",()=>{K(e.id),t.onDismiss?.(e.id),this.dismiss();}),n.appendChild(o),e.content&&e.content.content)for(let a of e.content.content){let d=this.renderComponent(a,e.id,t);d&&n.appendChild(d);}i.appendChild(n),document.head.appendChild(r),document.body.appendChild(i),this.overlay=i,this.styleEl=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{i.classList.add("tolk-visible");});});}renderComponent(e,t,r){let i=e.props;switch(e.type){case "Heading":{let n=document.createElement("h2");return n.textContent=i.text||"",n.style.fontSize=(i.fontSize||28)+"px",n.style.fontWeight="700",n.style.color=c(i.color)||"#1B1B1B",n.style.textAlign=de(i.alignment),n.style.lineHeight="1.2",n.style.margin="0 0 8px 0",n}case "TextBlock":{let n=document.createElement("p");return n.textContent=i.content||"",n.style.fontSize=(i.fontSize||15)+"px",n.style.color=c(i.color)||"#555555",n.style.textAlign=de(i.alignment),n.style.lineHeight="1.5",n.style.margin="0 0 8px 0",n}case "Image":{let n=i.url||"";if(!h(n))return null;let o=document.createElement("img");o.src=n,o.alt=i.alt||"";let a=i.width||"100%";return o.style.width=a.endsWith("px")||a.endsWith("%")?a:a+"px",o.style.borderRadius=(i.borderRadius||8)+"px",o.style.display="block",o.style.margin="0 auto 8px auto",o}case "Button":{let n=document.createElement("button");return n.textContent=i.label||"Click",n.style.backgroundColor=c(i.bgColor)||"#1B1B1B",n.style.color=c(i.textColor)||"#ffffff",n.style.fontSize=(i.fontSize||16)+"px",n.style.borderRadius=(i.borderRadius||8)+"px",n.style.border="none",n.style.padding="10px 20px",n.style.cursor="pointer",n.style.fontWeight="600",n.style.margin="8px 0",i.fullWidth&&(n.style.width="100%"),n.addEventListener("click",()=>{let o=i.action||"";r.onButtonPress?r.onButtonPress(o,t):o&&h(o)&&(window.location.href=o);}),n}case "Section":{let n=document.createElement("div");if(i.bgColor&&(n.style.backgroundColor=c(i.bgColor)||""),n.style.padding=(i.padding||16)+"px",n.style.borderRadius=(i.borderRadius||0)+"px",n.style.margin="8px 0",i.bgImage){let a=Ze(i.bgImage);a&&(n.style.backgroundImage=`url("${a}")`,n.style.backgroundSize=Je(i.bgSize),n.style.backgroundPosition="center");}let o=i.children||[];for(let a of o){let d=this.renderComponent(a,t,r);d&&n.appendChild(d);}return n}case "Spacer":{let n=document.createElement("div");return n.style.height=(i.height||24)+"px",n}case "Divider":{let n=document.createElement("hr");return n.style.border="none",n.style.borderTop=`${i.thickness||1}px solid ${c(i.color)||"#e5e5e5"}`,n.style.margin="8px 0",n}default:return null}}};function Ze(s){return h(s)?s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"").replace(/\r/g,""):null}function de(s){return s&&["left","center","right","justify"].includes(s)?s:"left"}function Je(s){return s&&(["cover","contain","auto"].includes(s)||/^(\d+(\.\d+)?(px|%|em|rem|vh|vw)(\s+\d+(\.\d+)?(px|%|em|rem|vh|vw))?)$/.test(s))?s:"cover"}var v=class{constructor(e){this._userId=null;if(!e.apiKey||typeof e.apiKey!="string")throw new Error("Tolinku: apiKey is required and must be a non-empty string");let t={...e,baseUrl:e.baseUrl||"https://api.tolinku.com"};try{let r=new URL(t.baseUrl);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error("Tolinku: baseUrl must use http: or https: protocol")}catch(r){throw r instanceof Error&&r.message.startsWith("Tolinku:")?r:new Error("Tolinku: baseUrl must be a valid URL (e.g. https://api.tolinku.com)")}this.client=new I(t),this.analytics=new R(this.client),this.ecommerce=new B(this.client,()=>this._userId),this.referrals=new A(this.client),this.deferred=new M(this.client),this.banners=new U(this.client),this.messages=new O(this.client);}setUserId(e){this._userId=e;}async track(e,t){let r=this._userId?{user_id:this._userId,...t}:t;return this.analytics.track(e,r)}async showBanner(e){return this.banners.show(e,this._userId)}dismissBanner(){this.banners.dismiss();}async showMessage(e){return this.messages.show(e,this._userId)}dismissMessage(){this.messages.dismiss();}async flush(){await Promise.all([this.analytics.flush(),this.ecommerce.flush()]);}destroy(){this.analytics.destroy(),this.ecommerce.destroy(),this.client.abort(),this.banners.dismiss(),this.messages.dismiss();}};v.TolinkuError=m;globalThis.Tolinku=v;
69
+ `;let i=document.createElement("div");i.className="tolk-msg-overlay",i.addEventListener("click",a=>{a.target===i&&(J(e.id),t.onDismiss?.(e.id),this.dismiss());});let n=document.createElement("div");n.className="tolk-msg-card",n.style.background=c(e.background_color)||"#ffffff";let o=document.createElement("button");if(o.className="tolk-msg-close",o.setAttribute("aria-label","Close message"),o.textContent="\xD7",o.addEventListener("click",()=>{J(e.id),t.onDismiss?.(e.id),this.dismiss();}),n.appendChild(o),e.content&&e.content.content)for(let a of e.content.content){let d=this.renderComponent(a,e.id,t);d&&n.appendChild(d);}i.appendChild(n),document.head.appendChild(r),document.body.appendChild(i),this.overlay=i,this.styleEl=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{i.classList.add("tolk-visible");});});}renderComponent(e,t,r){let i=e.props;switch(e.type){case "Heading":{let n=document.createElement("h2");return n.textContent=i.text||"",n.style.fontSize=(i.fontSize||28)+"px",n.style.fontWeight="700",n.style.color=c(i.color)||"#1B1B1B",n.style.textAlign=ue(i.alignment),n.style.lineHeight="1.2",n.style.margin="0 0 8px 0",n}case "TextBlock":{let n=document.createElement("p");return n.textContent=i.content||"",n.style.fontSize=(i.fontSize||15)+"px",n.style.color=c(i.color)||"#555555",n.style.textAlign=ue(i.alignment),n.style.lineHeight="1.5",n.style.margin="0 0 8px 0",n}case "Image":{let n=i.url||"";if(!h(n))return null;let o=document.createElement("img");o.src=n,o.alt=i.alt||"";let a=i.width||"100%";return o.style.width=a.endsWith("px")||a.endsWith("%")?a:a+"px",o.style.borderRadius=(i.borderRadius||8)+"px",o.style.display="block",o.style.margin="0 auto 8px auto",o}case "Button":{let n=document.createElement("button");return n.textContent=i.label||"Click",n.style.backgroundColor=c(i.bgColor)||"#1B1B1B",n.style.color=c(i.textColor)||"#ffffff",n.style.fontSize=(i.fontSize||16)+"px",n.style.borderRadius=(i.borderRadius||8)+"px",n.style.border="none",n.style.padding="10px 20px",n.style.cursor="pointer",n.style.fontWeight="600",n.style.margin="8px 0",i.fullWidth&&(n.style.width="100%"),n.addEventListener("click",()=>{let o=i.action||"";r.onButtonPress?r.onButtonPress(o,t):o&&h(o)&&(window.location.href=o);}),n}case "Section":{let n=document.createElement("div");if(i.bgColor&&(n.style.backgroundColor=c(i.bgColor)||""),n.style.padding=(i.padding||16)+"px",n.style.borderRadius=(i.borderRadius||0)+"px",n.style.margin="8px 0",i.bgImage){let a=Qe(i.bgImage);a&&(n.style.backgroundImage=`url("${a}")`,n.style.backgroundSize=Xe(i.bgSize),n.style.backgroundPosition="center");}let o=i.children||[];for(let a of o){let d=this.renderComponent(a,t,r);d&&n.appendChild(d);}return n}case "Spacer":{let n=document.createElement("div");return n.style.height=(i.height||24)+"px",n}case "Divider":{let n=document.createElement("hr");return n.style.border="none",n.style.borderTop=`${i.thickness||1}px solid ${c(i.color)||"#e5e5e5"}`,n.style.margin="8px 0",n}default:return null}}};function Qe(s){return h(s)?s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"").replace(/\r/g,""):null}function ue(s){return s&&["left","center","right","justify"].includes(s)?s:"left"}function Xe(s){return s&&(["cover","contain","auto"].includes(s)||/^(\d+(\.\d+)?(px|%|em|rem|vh|vw)(\s+\d+(\.\d+)?(px|%|em|rem|vh|vw))?)$/.test(s))?s:"cover"}var v=class{constructor(e){this._userId=null;if(!e.apiKey||typeof e.apiKey!="string")throw new Error("Tolinku: apiKey is required and must be a non-empty string");let t={...e,baseUrl:e.baseUrl||"https://api.tolinku.com"};try{let r=new URL(t.baseUrl);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error("Tolinku: baseUrl must use http: or https: protocol")}catch(r){throw r instanceof Error&&r.message.startsWith("Tolinku:")?r:new Error("Tolinku: baseUrl must be a valid URL (e.g. https://api.tolinku.com)")}this.client=new I(t),this.analytics=new R(this.client),this.ecommerce=new B(this.client,()=>this._userId),this.referrals=new A(this.client),this.deferred=new M(this.client),this.links=new U(this.client),this.banners=new z(this.client),this.messages=new L(this.client);}setUserId(e){this._userId=e;}async track(e,t){let r=this._userId?{user_id:this._userId,...t}:t;return this.analytics.track(e,r)}async showBanner(e){return this.banners.show(e,this._userId)}dismissBanner(){this.banners.dismiss();}async showMessage(e){return this.messages.show(e,this._userId)}dismissMessage(){this.messages.dismiss();}async flush(){await Promise.all([this.analytics.flush(),this.ecommerce.flush()]);}destroy(){this.analytics.destroy(),this.ecommerce.destroy(),this.client.abort(),this.banners.dismiss(),this.messages.dismiss();}};v.TolinkuError=m;globalThis.Tolinku=v;
70
70
  exports.Tolinku=v;exports.TolinkuError=m;return exports;})({});//# sourceMappingURL=tolinku.min.js.map
71
71
  //# sourceMappingURL=tolinku.min.global.js.map