UNPKG

@tiun/sdk

Version:

tiun SDK for payments and subscriptions

606 lines (605 loc) • 20.1 kB
var R = Object.defineProperty; var P = (i, e, t) => e in i ? R(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t; var o = (i, e, t) => (P(i, typeof e != "symbol" ? e + "" : e, t), t); const g = ["en", "de", "fr"], f = /* @__PURE__ */ new Set(); function I(i) { if (i == null || i === "") return "en"; const e = i.trim().toLowerCase(); return g.includes(e) ? e : (f.has(e) || (f.add(e), console.warn( `[tiun] Unsupported language "${i}" passed to tiun.init(). Falling back to "en". Supported languages: ${g.join(", ")}.` )), "en"); } const y = ["formal", "informal"], m = /* @__PURE__ */ new Set(); function v(i) { if (i == null || i === "") return; const e = i.trim().toLowerCase(); if (y.includes(e)) return e; m.has(e) || (m.add(e), console.warn( `[tiun] Unsupported tone "${i}" passed to tiun.init(). Falling back to the snippet default ("informal"). Supported tones: ${y.join(", ")}.` )); } const T = ["light", "dark", "auto"], _ = /* @__PURE__ */ new Set(); function w(i) { if (i == null || i === "") return; const e = i.trim().toLowerCase(); if (T.includes(e)) return e; _.has(e) || (_.add(e), console.warn( `[tiun] Unsupported appearance "${i}". Supported appearances: ${T.join(", ")}.` )); } const A = "https://api.tiun.live/live_api", N = "https://api-sandbox.tiun.live/live_api"; function S(i, e) { return e || (i ? N : A); } function L(i) { typeof window < "u" && (window.__TIUN_CONFIG__ = i); } function b() { typeof window < "u" && delete window.__TIUN_CONFIG__; } const O = 1e4; class z { constructor(e) { o(this, "pending", /* @__PURE__ */ new Map()); this.send = e; } /** Post `content` with a fresh requestId and wait for the matching reply. */ request(e, t = {}, { timeoutMs: n = O, whenReady: s } = {}) { const r = `req_${Math.random().toString(36).slice(2)}_${Date.now()}`; return new Promise((a, u) => { const d = { resolve: a, reject: u }; this.pending.set(r, d); const l = () => { this.pending.get(r) === d && (d.timer = setTimeout(() => { this.pending.delete(r), u({ code: "timeout", message: `${e} timed out` }); }, n), this.send(e, { ...t, requestId: r })); }; s ? s.then(l) : l(); }); } /** Settle the call waiting on `requestId`; replies nobody waits for are ignored. */ settle(e, t, n) { const s = e ? this.pending.get(e) : void 0; s && (clearTimeout(s.timer), this.pending.delete(e), n ? s.reject(n) : s.resolve(t)); } /** Reject every waiting call, sent or not yet sent, e.g. on destroy(). */ rejectAll(e) { this.pending.forEach(({ reject: t, timer: n }) => { clearTimeout(n), t(e); }), this.pending.clear(); } } const q = 5e3; class F { constructor() { o(this, "config", {}); o(this, "initialized", !1); o(this, "ready", !1); o(this, "readyPromise", null); o(this, "readyResolve", null); o(this, "readyReplayTimer", null); o(this, "eventListeners", /* @__PURE__ */ new Map()); o(this, "boundMessageHandler", null); o(this, "requests", new z( (e, t) => this.emit(e, t) )); // Auth state (populated by TIUN_USER_CHANGE events from the snippet) o(this, "_isAuthenticated", !1); o(this, "_user", null); } // =========================================================================== // Initialization // =========================================================================== /** * Initialize the tiun SDK. * Call this once at app startup. * * @example NPM package usage (snippetId required) * ```typescript * tiun.init({ * snippetId: 'your-snippet-id', * language: 'en', * debug: true, * }); * ``` * * @example Legacy script tag usage (no config needed) * ```typescript * tiun.init(); * ``` */ 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 || (this.readyPromise = new Promise((t) => { this.readyResolve = t; })), this.boundMessageHandler = this.handleMessage.bind(this), window.addEventListener("message", this.boundMessageHandler), this.ready && (this.readyReplayTimer = setTimeout(() => { var t, n; this.readyReplayTimer = null, this.triggerEvent("ready", void 0), (n = (t = this.config).onReady) == null || n.call(t), this.log("Snippet ready (re-initialized)"); }, 0)), 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); } /** * Convert TiunConfig to TiunRuntimeConfig. Only public init fields are set. * webView, preview, previewProductId, enableLogs are never set here – * they are only set via direct snippet URL query params or legacy env. */ setRuntimeConfigFromTiunConfig(e) { const t = e.baseUrl, n = { snippetId: e.snippetId, baseUrl: S(e.sandbox, t), // Normalize (and warn once) here so any language/tone issue surfaces at // init() on the host page, and the snippet receives an already-valid value // instead of re-normalizing and warning a second time in its own console. language: I(e.language), tone: v(e.tone), appearance: w(e.appearance), debug: e.debug }; L(n); } // =========================================================================== // Public Methods // =========================================================================== /** * Open the time-based connect flow. * Use this for publishers with time-based access (no specific product). * * @example * ```typescript * tiun.start(); * ``` */ async start() { this.ensureInitialized(), await this.waitForReady(), this.emit("TIUN_START"), this.log("Start triggered"); } /** * Open the checkout flow for a specific product. * * @example * ```typescript * // Default checkout * tiun.checkout(); * * // With specific product * tiun.checkout({ productId: 'prod_premium_monthly' }); * * // Repeatable product: tie this purchase to your own reference * tiun.checkout({ productId: 'prod_ticket', referenceId: 'order-1042' }); * ``` */ async checkout(e = {}) { this.ensureInitialized(), await this.waitForReady(), this.emit("TIUN_CHECKOUT", { productId: e.productId, // Empty string means "no reference" — don't send a value the BE rejects. referenceId: e.referenceId || void 0 }), this.log("Checkout triggered", e); } /** * Update the current content context. * Use this to tell tiun what content the user is viewing. * * @example * ```typescript * tiun.setContent({ type: 'premium', contentId: 'article-123' }); * ``` */ 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); } /** * Switch the snippet's color theme at runtime. * Safe to call before init() or before the snippet is ready: a snippet that * hasn't booted picks the value up from the runtime config, a running one * from the event. * * @example * ```typescript * tiun.setAppearance('dark'); * ``` */ setAppearance(e) { const t = w(e); if (!t || (this.config.appearance = t, !this.initialized || typeof window > "u")) return; const n = window.__TIUN_CONFIG__; n && (n.appearance = t), this.emit("TIUN_SET_APPEARANCE", { appearance: t }), this.log("Appearance set", t); } /** * Open the OTP login modal for returning subscribers. */ async login() { this.ensureInitialized(), await this.waitForReady(), this.emit("TIUN_LOGIN"), this.log("Login triggered"); } /** * Clear session and fire logout + userChange events. */ logout() { this.ensureInitialized(), this.emit("TIUN_LOGOUT"), this.log("Logout triggered"); } /** * Returns the cached user state. * The snippet keeps this in sync automatically via TIUN_USER_CHANGE events. */ getUser() { return { isAuthenticated: this._isAuthenticated, user: this._user }; } /** * Returns a signed JWT for server-to-server user verification. * Valid for 5 minutes. Returns null if the user is not authenticated. * * The JWT is generated by the snippet (which owns the ECDSA key pair) * via a postMessage round-trip. */ async getUserVerificationToken() { return this._isAuthenticated ? this.requests.request( "TIUN_GET_VERIFICATION_TOKEN", {}, { timeoutMs: q } ).catch(() => null) : null; } // =========================================================================== // Products // =========================================================================== /** * List the products available on this snippet. * * @example * ```typescript * const products = await tiun.listProducts(); * ``` */ listProducts() { return this.requestProductFromSnippet("TIUN_LIST_PRODUCTS"); } /** * Get a product's details and localized pricing. * Rejects with a TiunError if the product doesn't exist. * * @example * ```typescript * const { name, pricingLine } = await tiun.getProduct('prod_premium_monthly'); * ``` */ getProduct(e) { return e ? this.requestProductFromSnippet("TIUN_GET_PRODUCT", { productId: e }) : this.rejectInvalidProductId(); } /** * List the current user's active product access, fetched from the backend. * Resolves to [] when the user is not authenticated. * * Unlike `user.productAccess` (cached product IDs), each entry carries its * referenceId, activatedAt and expiresAt. * * @example * ```typescript * const access = await tiun.listProductAccess(); * ``` */ listProductAccess() { return this.requestProductFromSnippet( "TIUN_LIST_PRODUCT_ACCESS" ); } /** * Check whether the current user has access to a product. * Resolves to { hasAccess: false, access: null } when the user is not authenticated. * * @example * ```typescript * const { hasAccess } = await tiun.checkProductAccess('prod_premium_monthly'); * * // Repeatable product: check a specific purchase * await tiun.checkProductAccess('prod_ticket', { referenceId: 'order-1042' }); * ``` */ checkProductAccess(e, t = {}) { return e ? this.requestProductFromSnippet( "TIUN_CHECK_PRODUCT_ACCESS", { productId: e, // Empty string means "no reference" — don't send a value the BE rejects. referenceId: t.referenceId || void 0 } ) : this.rejectInvalidProductId(); } // =========================================================================== // Event System // =========================================================================== /** * Subscribe to SDK events. * Returns an unsubscribe function. * * @example * ```typescript * // Subscribe * const unsubscribe = tiun.on('userChange', (event) => { * console.log('User state changed:', event); * }); * * // Unsubscribe when done * unsubscribe(); * ``` */ on(e, t) { return this.eventListeners.has(e) || this.eventListeners.set(e, /* @__PURE__ */ new Set()), this.eventListeners.get(e).add(t), () => { var n; (n = this.eventListeners.get(e)) == null || n.delete(t); }; } /** * Subscribe to an event for a single invocation. */ once(e, t) { const n = this.on(e, (s) => { n(), t(s); }); return n; } /** * Remove all listeners for an event, or all listeners if no event specified. */ off(e) { e ? this.eventListeners.delete(e) : this.eventListeners.clear(); } // =========================================================================== // Lifecycle // =========================================================================== /** * Wait for the SDK to be ready. * Resolves immediately if already ready. */ async waitForReady() { if (!this.ready) return this.readyPromise || (this.readyPromise = new Promise((e) => { this.readyResolve = e; })), this.readyPromise; } /** * Remove the SDK's listeners and reset its state. The snippet stays on the * page; calling init() again works, but `user` stays empty until the next * login, logout or checkout. */ destroy() { typeof window > "u" || (this.boundMessageHandler && (window.removeEventListener("message", this.boundMessageHandler), this.boundMessageHandler = null), this.eventListeners.clear(), b(), this.requests.rejectAll({ code: "destroyed", message: "tiun SDK was destroyed" }), this.readyReplayTimer && (clearTimeout(this.readyReplayTimer), this.readyReplayTimer = null), this.initialized = !1, this.ready || (this.readyPromise = null, this.readyResolve = null), this.config = {}, this._isAuthenticated = !1, this._user = null, this.log("SDK destroyed")); } // =========================================================================== // Static Properties // =========================================================================== /** * SDK version */ get version() { return "0.12.0"; } /** * Whether SDK is initialized */ get isInitialized() { return this.initialized; } /** * Whether SDK is ready (snippet loaded) */ get isReady() { return this.ready; } /** * Whether running in browser */ get isBrowser() { return typeof window < "u"; } /** * Whether the user is identified (has valid session) */ get isAuthenticated() { return this._isAuthenticated; } /** * Current user info or null */ get user() { return this._user; } // =========================================================================== // Internal Methods // =========================================================================== async requestProductFromSnippet(e, t = {}) { if (typeof window > "u") throw { code: "ssr", message: "tiun is not available during SSR" }; return this.ensureInitialized(), this.log("Product request", e, t), this.requests.request(e, t, { whenReady: this.waitForReady() }); } rejectInvalidProductId() { return Promise.reject({ code: "invalid_argument", message: "productId is required" }); } ensureInitialized() { this.initialized || this.init(); } handleMessage(e) { var n, s, r, a, u, d; 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 }), (s = (n = this.config).onPaywallShow) == null || s.call(n, { isConnected: t.isConnected ?? !1 }); break; case "TIUN_HIDE_PAYWALL": this.triggerEvent("paywallHide", { sessionId: t.sessionId ?? "", isConnected: t.isConnected ?? !0 }), (a = (r = this.config).onPaywallHide) == null || a.call(r, { sessionId: t.sessionId ?? "", isConnected: t.isConnected ?? !0 }); break; case "TIUN_ERROR": t.error && (this.triggerEvent("error", t.error), (d = (u = this.config).onError) == null || d.call(u, t.error)); break; case "TIUN_USER_CHANGE": this.handleUserChange(t); break; case "TIUN_VERIFICATION_TOKEN": this.requests.settle(t.requestId, t.token ?? null); break; case "TIUN_PRODUCT_RESULT": this.requests.settle(t.requestId, t.result, t.error); break; } } handleReady() { var e, t, n; this.ready || (this.ready = !0, (e = this.readyResolve) == null || e.call(this), this.triggerEvent("ready", void 0), (n = (t = this.config).onReady) == null || n.call(t), this.log("Snippet ready")); } triggerEvent(e, t) { const n = this.eventListeners.get(e); n && n.forEach((s) => { try { s(t); } catch (r) { console.error(`[Tiun] Error in ${e} listener:`, r); } }); } handleUserChange(e) { var s, r, a, u, d, l; const t = e.userEvent ?? "update"; this._isAuthenticated = e.isAuthenticated ?? !1, this._user = e.user ?? null; const n = { event: t, isAuthenticated: this._isAuthenticated, user: this._user }; if (this.triggerEvent("userChange", n), (r = (s = this.config).onUserChange) == null || r.call(s, n), t === "login" && this._user) { const p = { user: this._user }; this.triggerEvent("login", p), (u = (a = this.config).onLogin) == null || u.call(a, p); } t === "logout" && (this.triggerEvent("logout", void 0), (l = (d = this.config).onLogout) == null || l.call(d)); } 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 c = new F(), E = "script[data-tiun-snippet][data-snippet-id]", U = "link[data-tiun-snippet][data-snippet-id]"; function $(i) { const e = new URLSearchParams(); i.language != null && i.language !== "" && e.set("language", I(i.language)), i.tone === "formal" && e.set("formal", "true"); const t = e.toString(); return t ? `?${t}` : ""; } function k(i, e, t) { const n = i.replace(/\/$/, ""), s = $(t); return { scriptUrl: `${n}/v2/snippets/${e}/background_js${s}`, cssUrl: `${n}/v2/snippets/${e}/background_css${s}` }; } function C(i) { if (typeof document > "u") return !1; const e = document.querySelector( `${E}[data-snippet-id="${i}"]` ), t = document.querySelector( `${U}[data-snippet-id="${i}"]` ); return !!e || !!t; } function D() { return typeof document > "u" ? !1 : !!document.querySelector( `${E}, ${U}` ); } let h = !1; function M(i, e, t) { if (!(typeof document > "u") && !C(e) && !h) { h = !0; try { const { scriptUrl: n, cssUrl: s } = k( i, e, t ), r = document.createElement("link"); r.rel = "stylesheet", r.href = s, r.setAttribute("data-tiun-snippet", ""), r.setAttribute("data-snippet-id", e), document.head.appendChild(r); const a = document.createElement("script"); a.src = n, a.async = !0, a.setAttribute("data-tiun-snippet", ""), a.setAttribute("data-snippet-id", e), document.head.appendChild(a); } finally { h = !1; } } } const H = c.init.bind(c); c.init = function(i = {}) { const e = H(i); if (typeof window < "u") if (i.snippetId) { if (!C(i.snippetId)) { const t = i.baseUrl, n = S(i.sandbox, t); M(n, i.snippetId, { language: i.language, tone: i.tone }); } } else D() || 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 = c); export { c as default, c as tiun };