UNPKG

@tiun/sdk

Version:

tiun SDK for payments and subscriptions

2 lines (1 loc) • 9.23 kB
(function(o,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(o=typeof globalThis<"u"?globalThis:o||self,s(o.tiun={}))})(this,function(o){"use strict";var M=Object.defineProperty;var H=(o,s,l)=>s in o?M(o,s,{enumerable:!0,configurable:!0,writable:!0,value:l}):o[s]=l;var d=(o,s,l)=>(H(o,typeof s!="symbol"?s+"":s,l),l);const s=["en","de","fr"],l=new Set;function g(n){if(n==null||n==="")return"en";const e=n.trim().toLowerCase();return s.includes(e)?e:(l.has(e)||(l.add(e),console.warn(`[tiun] Unsupported language "${n}" passed to tiun.init(). Falling back to "en". Supported languages: ${s.join(", ")}.`)),"en")}const T=["formal","informal"],y=new Set;function C(n){if(n==null||n==="")return;const e=n.trim().toLowerCase();if(T.includes(e))return e;y.has(e)||(y.add(e),console.warn(`[tiun] Unsupported tone "${n}" passed to tiun.init(). Falling back to the snippet default ("informal"). Supported tones: ${T.join(", ")}.`))}const w=["light","dark","auto"],m=new Set;function _(n){if(n==null||n==="")return;const e=n.trim().toLowerCase();if(w.includes(e))return e;m.has(e)||(m.add(e),console.warn(`[tiun] Unsupported appearance "${n}". Supported appearances: ${w.join(", ")}.`))}const A="https://api.tiun.live/live_api",N="https://api-sandbox.tiun.live/live_api";function I(n,e){return e||(n?N:A)}function b(n){typeof window<"u"&&(window.__TIUN_CONFIG__=n)}function P(){typeof window<"u"&&delete window.__TIUN_CONFIG__}class k{constructor(){d(this,"config",{});d(this,"initialized",!1);d(this,"ready",!1);d(this,"readyPromise",null);d(this,"readyResolve",null);d(this,"eventListeners",new Map);d(this,"boundMessageHandler",null);d(this,"_isAuthenticated",!1);d(this,"_user",null);d(this,"pendingTokenResolve",null);d(this,"pendingTokenTimeout",null)}init(e={}){return typeof window>"u"?(this.log("SSR detected, skipping initialization"),this):this.initialized?(this.log("Already initialized, updating config"),this.config={...this.config,...e},this.setRuntimeConfigFromTiunConfig(e),e.appearance!==void 0&&this.setAppearance(e.appearance),this):(this.config={...e,appearance:e.appearance??this.config.appearance},e=this.config,this.initialized=!0,this.readyPromise=new Promise(t=>{this.readyResolve=t}),this.boundMessageHandler=this.handleMessage.bind(this),window.addEventListener("message",this.boundMessageHandler),this.setRuntimeConfigFromTiunConfig(e),this.log("SDK initialized",e.snippetId?"(NPM mode)":"(legacy mode)"),e.snippetId&&window.dispatchEvent(new CustomEvent("tiun:config-ready",{detail:e})),this)}setRuntimeConfigFromTiunConfig(e){const t=e.baseUrl,i={snippetId:e.snippetId,baseUrl:I(e.sandbox,t),language:g(e.language),tone:C(e.tone),appearance:_(e.appearance),debug:e.debug};b(i)}async start(){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_START"),this.log("Start triggered")}async checkout(e={}){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_CHECKOUT",{productId:e.productId}),this.log("Checkout triggered",e)}async setContent(e){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_UPDATE_CONTENT",{contentId:e.contentId,contentType:e.type,mediaType:e.mediaType||"text"}),this.log("Content updated",e)}setAppearance(e){const t=_(e);if(!t||(this.config.appearance=t,!this.initialized||typeof window>"u"))return;const i=window.__TIUN_CONFIG__;i&&(i.appearance=t),this.emit("TIUN_SET_APPEARANCE",{appearance:t}),this.log("Appearance set",t)}async login(){this.ensureInitialized(),await this.waitForReady(),this.emit("TIUN_LOGIN"),this.log("Login triggered")}logout(){this.ensureInitialized(),this.emit("TIUN_LOGOUT"),this.log("Logout triggered")}getUser(){return{isAuthenticated:this._isAuthenticated,user:this._user}}async getUserVerificationToken(){return this._isAuthenticated?this.requestTokenFromSnippet():null}on(e,t){return this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t),()=>{var i;(i=this.eventListeners.get(e))==null||i.delete(t)}}once(e,t){const i=this.on(e,r=>{i(),t(r)});return i}off(e){e?this.eventListeners.delete(e):this.eventListeners.clear()}async waitForReady(){if(!this.ready)return this.readyPromise||(this.readyPromise=new Promise(e=>{this.readyResolve=e})),this.readyPromise}destroy(){typeof window>"u"||(this.boundMessageHandler&&(window.removeEventListener("message",this.boundMessageHandler),this.boundMessageHandler=null),this.eventListeners.clear(),P(),this.handleVerificationTokenResponse(null),this.initialized=!1,this.ready=!1,this.readyPromise=null,this.readyResolve=null,this.config={},this._isAuthenticated=!1,this._user=null,this.log("SDK destroyed"))}get version(){return"0.10.1"}get isInitialized(){return this.initialized}get isReady(){return this.ready}get isBrowser(){return typeof window<"u"}get isAuthenticated(){return this._isAuthenticated}get user(){return this._user}requestTokenFromSnippet(){return typeof window>"u"?Promise.resolve(null):(this.handleVerificationTokenResponse(null),new Promise(e=>{this.pendingTokenResolve=e,this.pendingTokenTimeout=setTimeout(()=>{this.pendingTokenResolve=null,e(null)},5e3),this.emit("TIUN_GET_VERIFICATION_TOKEN")}))}handleVerificationTokenResponse(e){this.pendingTokenResolve&&(this.pendingTokenTimeout&&(clearTimeout(this.pendingTokenTimeout),this.pendingTokenTimeout=null),this.pendingTokenResolve(e),this.pendingTokenResolve=null)}ensureInitialized(){this.initialized||this.init()}handleMessage(e){var i,r,a,u,c,p;if(typeof window<"u"&&e.origin!==window.location.origin)return;const t=e.data;if((t==null?void 0:t.type)==="TIUN_EVENT")switch(this.log("Received event",t.content,t),t.content){case"TIUN_SNIPPET_INITIALIZED":this.handleReady();break;case"TIUN_SHOW_PAYWALL":this.triggerEvent("paywallShow",{isConnected:t.isConnected??!1}),(r=(i=this.config).onPaywallShow)==null||r.call(i,{isConnected:t.isConnected??!1});break;case"TIUN_HIDE_PAYWALL":this.triggerEvent("paywallHide",{sessionId:t.sessionId??"",isConnected:t.isConnected??!0}),(u=(a=this.config).onPaywallHide)==null||u.call(a,{sessionId:t.sessionId??"",isConnected:t.isConnected??!0});break;case"TIUN_ERROR":t.error&&(this.triggerEvent("error",t.error),(p=(c=this.config).onError)==null||p.call(c,t.error));break;case"TIUN_USER_CHANGE":this.handleUserChange(t);break;case"TIUN_VERIFICATION_TOKEN":this.handleVerificationTokenResponse(t.token??null);break}}handleReady(){var e,t,i;this.ready||(this.ready=!0,(e=this.readyResolve)==null||e.call(this),this.triggerEvent("ready",void 0),(i=(t=this.config).onReady)==null||i.call(t),this.log("Snippet ready"))}triggerEvent(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>{try{r(t)}catch(a){console.error(`[Tiun] Error in ${e} listener:`,a)}})}handleUserChange(e){var r,a,u,c,p,v;const t=e.userEvent??"update";this._isAuthenticated=e.isAuthenticated??!1,this._user=e.user??null;const i={event:t,isAuthenticated:this._isAuthenticated,user:this._user};if(this.triggerEvent("userChange",i),(a=(r=this.config).onUserChange)==null||a.call(r,i),t==="login"&&this._user){const U={user:this._user};this.triggerEvent("login",U),(c=(u=this.config).onLogin)==null||c.call(u,U)}t==="logout"&&(this.triggerEvent("logout",void 0),(v=(p=this.config).onLogout)==null||v.call(p))}emit(e,t={}){if(typeof window>"u"){this.log("Cannot emit in SSR");return}window.postMessage({type:"TIUN_EVENT",content:e,...t},window.location.origin)}log(...e){this.config.debug&&console.log("[tiun]",...e)}}const h=new k,E="script[data-tiun-snippet][data-snippet-id]",S="link[data-tiun-snippet][data-snippet-id]";function L(n){const e=new URLSearchParams;n.language!=null&&n.language!==""&&e.set("language",g(n.language)),n.tone==="formal"&&e.set("formal","true");const t=e.toString();return t?`?${t}`:""}function z(n,e,t){const i=n.replace(/\/$/,""),r=L(t);return{scriptUrl:`${i}/v2/snippets/${e}/background_js${r}`,cssUrl:`${i}/v2/snippets/${e}/background_css${r}`}}function R(n){if(typeof document>"u")return!1;const e=document.querySelector(`${E}[data-snippet-id="${n}"]`),t=document.querySelector(`${S}[data-snippet-id="${n}"]`);return!!e||!!t}function O(){return typeof document>"u"?!1:!!document.querySelector(`${E}, ${S}`)}let f=!1;function $(n,e,t){if(!(typeof document>"u")&&!R(e)&&!f){f=!0;try{const{scriptUrl:i,cssUrl:r}=z(n,e,t),a=document.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-tiun-snippet",""),a.setAttribute("data-snippet-id",e),document.head.appendChild(a);const u=document.createElement("script");u.src=i,u.async=!0,u.setAttribute("data-tiun-snippet",""),u.setAttribute("data-snippet-id",e),document.head.appendChild(u)}finally{f=!1}}}const F=h.init.bind(h);h.init=function(n={}){const e=F(n);if(typeof window<"u")if(n.snippetId){if(!R(n.snippetId)){const t=n.baseUrl,i=I(n.sandbox,t);$(i,n.snippetId,{language:n.language,tone:n.tone})}}else O()||console.warn(`[tiun] No "snippetId" was provided to tiun.init(), so the snippet cannot load. Pass it as tiun.init({ snippetId: 'your-id' }). (If you use the legacy script-tag integration, you can ignore this.)`);return e},typeof window<"u"&&(window.tiun=h),o.default=h,o.tiun=h,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});