@tolinku/react-native-sdk 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/debug.ts","../src/client.ts","../src/validation.ts","../src/analytics.ts","../src/ecommerce.ts","../src/referrals.ts","../src/install-referrer.ts","../src/deferred.ts","../src/links.ts","../src/storage.ts","../src/Tolinku.ts","../src/messages/components.tsx","../src/messages/MessageModal.tsx","../src/messages/MessageProvider.tsx"],"names":["AppState","Platform","BATCH_SIZE","FLUSH_INTERVAL_MS","MAX_QUEUE_SIZE","AsyncStorage","NativeModules","Dimensions","PixelRatio","jsx","Text","React","Image","TouchableOpacity","Linking","View","ImageBackground","alignment","jsxs","Fragment","Modal","Pressable","ScrollView","StyleSheet","useState","useRef","useMemo","useEffect","useCallback"],"mappings":";;;;;;;;;;;;;AACO,IAAM,WAAA,GAAc,OAAA;;;ACA3B,IAAI,aAAA,GAAgB,KAAA;AAEb,SAAS,gBAAgB,OAAA,EAAwB;AACtD,EAAA,aAAA,GAAgB,OAAA;AAClB;AAOO,SAAS,SAAS,OAAA,EAAuB;AAC9C,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAE,CAAA;AAAA,EACvC;AACF;AAGO,SAAS,UAAU,OAAA,EAAuB;AAC/C,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAE,CAAA;AAAA,EACxC;AACF;;;AClBA,IAAM,WAAA,GAAc,CAAA;AAEpB,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,aAAA,GAAgB,GAAA;AAetB,SAAS,aAAa,GAAA,EAAuB;AAC3C,EAAA,OACE,OAAO,GAAA,KAAQ,QAAA,IACf,GAAA,K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MACjE;AAAA,IACF;AAEA,IAAA,aAAA,EAAc;AAEd,IAAA,OAAO,MAAM;AACX,MAAA,SAAA,GAAY,IAAA;AAAA,IACd,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,OAAA,EAAS,YAAY,CAAC,CAAA;AAE1B,EAAA,MAAM,WAAA,GAAcC,kBAAY,MAAM;AACpC,IAAA,UAAA,CAAW,KAAK,CAAA;AAChB,IAAA,UAAA,CAAW,IAAI,CAAA;AAAA,EACjB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,uBACEnB,cAAAA;AAAA,IAAC,YAAA;AAAA,IAAA;AAAA,MACC,OAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA,EAAS,WAAA;AAAA,MACT,OAAA;AAAA,MACA;AAAA;AAAA,GACF;AAEJ","file":"index.js","sourcesContent":["/** SDK version */\nexport const SDK_VERSION = '0.7.1';\n\n/** Configuration options for the Tolinku SDK */\nexport interface TolinkuConfig {\n /** Your Tolinku publishable API key (starts with tolk_pub_) */\n apiKey: string;\n /** Base URL of your Tolinku domain. Defaults to https://api.tolinku.com */\n baseUrl?: string;\n /** Enable debug logging to the console. Defaults to false. */\n debug?: boolean;\n /** Request timeout in milliseconds. Defaults to 30000 (30 seconds). */\n timeout?: number;\n}\n\n/** Resolved configuration with all defaults applied */\nexport interface ResolvedTolinkuConfig {\n apiKey: string;\n baseUrl: string;\n debug: boolean;\n timeout: number;\n}\n\n/** Properties for custom event tracking */\nexport interface TrackProperties {\n campaign?: string;\n source?: string;\n medium?: string;\n platform?: string;\n [key: string]: string | undefined;\n}\n\n/** Options for creating a referral */\nexport interface CreateReferralOptions {\n userId: string;\n metadata?: Record<string, string>;\n userName?: string;\n}\n\n/** Response from creating a referral */\nexport interface CreateReferralResult {\n referral_code: string;\n referral_url: string | null;\n referral_id: string;\n}\n\n/** Options for completing a referral */\nexport interface CompleteReferralOptions {\n code: string;\n referredUserId: string;\n milestone?: string;\n referredUserName?: string;\n}\n\n/** Response from completing a referral */\nexport interface CompleteReferralResult {\n referral: {\n id: string;\n referrer_id: string;\n referred_user_id: string;\n status: string;\n milestone: string;\n completed_at: string;\n reward_type: string | null;\n reward_value: string | null;\n };\n}\n\n/** Options for updating a referral milestone */\nexport interface MilestoneOptions {\n code: string;\n milestone: string;\n}\n\n/** Response from updating a milestone */\nexport interface MilestoneResult {\n referral: {\n id: string;\n referral_code: string;\n milestone: string;\n status: string;\n reward_type: string | null;\n reward_value: string | null;\n };\n}\n\n/** Referral info returned by GET /api/referral/:code */\nexport interface ReferralInfo {\n referrer_id: string;\n status: string;\n milestone: string;\n milestone_history: Array<{ milestone: string; timestamp: string }>;\n reward_type: string | null;\n reward_value: string | null;\n reward_claimed: boolean;\n created_at: string;\n}\n\n/** Leaderboard entry */\nexport interface LeaderboardEntry {\n referrer_id: string;\n referrer_name: string | null;\n total: number;\n completed: number;\n pending: number;\n total_reward_value: string | null;\n}\n\n/** Deferred deep link result */\nexport interface DeferredLink {\n deep_link_path: string;\n appspace_id: string;\n referrer_id?: string;\n referral_code?: string;\n}\n\n/**\n * What a Tolinku link turned out to mean.\n *\n * The same shape in every SDK, so an app moving between them reads one thing.\n * The Appspace the link belongs to is deliberately not here: the app already\n * knows which Appspace it is, and nothing about routing a link needs it.\n */\nexport interface ResolvedLink {\n /** The route that answers this link. */\n route: {\n prefix: string;\n name: string;\n template: string;\n link_type?: string;\n };\n /** The token the link carried, or '' where it carried none. */\n token: string;\n /** The canonical path, with the token wherever the route's prefix puts it. */\n deep_link_path: string;\n}\n\n/** Options for claiming deferred link by signals */\nexport interface ClaimBySignalsOptions {\n appspaceId: string;\n timezone?: string;\n language?: string;\n screenWidth?: number;\n screenHeight?: number;\n /** Defaults to `PixelRatio.get()`. Override only if you report a custom screen size. */\n devicePixelRatio?: number;\n /** Defaults to `Platform.Version`. Compared on the major component only. */\n osVersion?: string;\n}\n\n/** In-app message from the API */\nexport interface Message {\n id: string;\n name: string;\n title: string;\n body: string | null;\n trigger: string;\n trigger_value: string | null;\n content: MessageContent | null;\n background_color: string;\n priority: number;\n dismiss_days: number | null;\n max_impressions: number | null;\n min_interval_hours: number | null;\n}\n\n/** Puck component content tree */\nexport interface MessageContent {\n root: { props: Record<string, unknown> };\n content: MessageComponent[];\n /**\n * A Section's children, keyed \"<component id>:content\".\n *\n * Puck keeps nested content here rather than on the parent's props, so a\n * renderer that reads props.children finds nothing and draws every Section\n * as an empty box. This was missing from the type entirely, which is part of\n * how that went unnoticed.\n */\n zones?: Record<string, MessageComponent[]>;\n}\n\n/**\n * The app a message belongs to, sent alongside it.\n *\n * AppIcon, StoreButtons and DeepLinkButton describe the app rather than the\n * message, so the content has nothing to draw them from.\n */\nexport interface MessageAppContext {\n name: string;\n icon_url: string | null;\n ios_store_url: string | null;\n android_store_url: string | null;\n deep_link_url: string | null;\n ios_badge_url: string;\n android_badge_url: string;\n}\n\n/** A single Puck component */\nexport interface MessageComponent {\n type: string;\n props: Record<string, unknown>;\n}\n\n/** Options for showing an in-app message */\nexport interface ShowMessageOptions {\n trigger?: string;\n triggerValue?: string;\n onDismiss?: (messageId: string) => void;\n onButtonPress?: (action: string, messageId: string) => void;\n}\n\n// ─── Ecommerce Types ─────────────────────────────────────\n\nexport interface EcommerceItem {\n item_id: string;\n item_name?: string;\n item_category?: string;\n item_brand?: string;\n item_variant?: string;\n item_list_name?: string;\n item_list_id?: string;\n item_image_url?: string;\n price?: number;\n quantity?: number;\n currency?: string;\n coupon_code?: string;\n discount?: number;\n}\n\nexport interface PurchaseParams {\n transaction_id: string;\n revenue: number;\n currency: string;\n items?: EcommerceItem[];\n cart_id?: string;\n coupon_code?: string;\n discount?: number;\n shipping?: number;\n tax?: number;\n}\n\nexport interface AddToCartParams {\n items: EcommerceItem[];\n cart_id?: string;\n}\n\nexport interface RemoveFromCartParams {\n items: EcommerceItem[];\n cart_id?: string;\n}\n\nexport interface AddToWishlistParams {\n items: EcommerceItem[];\n}\n\nexport interface BeginCheckoutParams {\n revenue?: number;\n currency?: string;\n cart_id?: string;\n items?: EcommerceItem[];\n}\n\nexport interface RefundParams {\n transaction_id: string;\n revenue: number;\n currency?: string;\n items?: EcommerceItem[];\n}\n\nexport interface ViewItemParams {\n items: EcommerceItem[];\n}\n\nexport interface SearchParams {\n search_term: string;\n}\n\nexport interface AddPaymentInfoParams {\n cart_id?: string;\n}\n\nexport interface ShareParams {\n item_id?: string;\n url?: string;\n method?: string;\n}\n\nexport interface RateParams {\n item_id: string;\n rating: number;\n max_rating?: number;\n}\n\nexport interface SpendCreditsParams {\n revenue: number;\n currency: string;\n}\n","/** Global debug flag, controlled by Tolinku.init({ debug: true }) */\nlet _debugEnabled = false;\n\nexport function setDebugEnabled(enabled: boolean): void {\n _debugEnabled = enabled;\n}\n\nexport function isDebugEnabled(): boolean {\n return _debugEnabled;\n}\n\n/** Log a message to the console if debug mode is enabled. */\nexport function debugLog(message: string): void {\n if (_debugEnabled) {\n console.log(`[TolinkuSDK] ${message}`);\n }\n}\n\n/** Log a warning to the console if debug mode is enabled. */\nexport function debugWarn(message: string): void {\n if (_debugEnabled) {\n console.warn(`[TolinkuSDK] ${message}`);\n }\n}\n","import type { ResolvedTolinkuConfig } from './types';\nimport { SDK_VERSION } from './types';\nimport { debugLog } from './debug';\n\n/** Maximum number of retry attempts after the initial request. */\nconst MAX_RETRIES = 3;\n/** Base delay in milliseconds before the first retry. */\nconst BASE_DELAY_MS = 500;\n/** Maximum random jitter added to each retry delay, in milliseconds. */\nconst MAX_JITTER_MS = 250;\n\n/**\n * Whether a caught value is an abort, from either the timeout or destroy().\n *\n * Read off the name rather than tested with `instanceof DOMException`. React\n * Native has no DOM, so whether `DOMException` exists as a global at all\n * depends on the engine and on which AbortController implementation is in\n * play: Hermes supplies its own, a polyfill supplies another, and neither is\n * obliged to reject with a real DOMException. The name is the one part every\n * implementation agrees on, including the browser's. The previous check\n * compiled only because React Native's older type definitions pulled DOM\n * globals in behind our backs, and it would have quietly stopped recognising\n * a timeout on any engine without that global.\n */\nfunction isAbortError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'AbortError'\n );\n}\n\nexport class HttpClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n\n /** Set of AbortControllers for in-flight requests. Used by destroy() to cancel all. */\n private pendingControllers: Set<AbortController> = new Set();\n private destroyed = false;\n\n constructor(config: ResolvedTolinkuConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.timeout = config.timeout;\n }\n\n async get<T>(path: string, params?: Record<string, string>): Promise<T> {\n let url = this.baseUrl + path;\n if (params) {\n const qs = new URLSearchParams(params).toString();\n if (qs) url += '?' + qs;\n }\n\n return this.executeWithRetry<T>(url, {\n method: 'GET',\n headers: this.authenticatedHeaders(),\n });\n }\n\n async post<T>(path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(this.baseUrl + path, {\n method: 'POST',\n headers: {\n ...this.authenticatedHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /** GET without API key auth (for public endpoints like deferred claim) */\n async getPublic<T>(path: string, params?: Record<string, string>): Promise<T> {\n let url = this.baseUrl + path;\n if (params) {\n const qs = new URLSearchParams(params).toString();\n if (qs) url += '?' + qs;\n }\n\n return this.executeWithRetry<T>(url, {\n method: 'GET',\n headers: this.publicHeaders(),\n });\n }\n\n /**\n * POST to a host other than the configured one, without the API key.\n *\n * A few public endpoints work out which Appspace they belong to from the\n * hostname the request arrived on rather than from a key or an id, so a\n * question about a link on a customer's own domain has to be asked on that\n * domain. Everything else about the request is unchanged: same timeout, same\n * retries, same headers.\n */\n async postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(origin.replace(/\\/+$/, '') + path, {\n method: 'POST',\n headers: {\n ...this.publicHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /** POST without API key auth (for public endpoints like deferred claim) */\n async postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(this.baseUrl + path, {\n method: 'POST',\n headers: {\n ...this.publicHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /**\n * Abort all in-flight requests and mark the client as destroyed.\n * After calling this, all future requests will throw immediately.\n */\n abort(): void {\n this.destroyed = true;\n for (const controller of this.pendingControllers) {\n controller.abort();\n }\n this.pendingControllers.clear();\n }\n\n private authenticatedHeaders(): Record<string, string> {\n return {\n 'X-API-Key': this.apiKey,\n 'Accept': 'application/json',\n 'User-Agent': `TolinkuReactNativeSDK/${SDK_VERSION}`,\n };\n }\n\n private publicHeaders(): Record<string, string> {\n return {\n 'Accept': 'application/json',\n 'User-Agent': `TolinkuReactNativeSDK/${SDK_VERSION}`,\n };\n }\n\n /**\n * Execute a fetch request with retry logic. Retries on:\n * - Network errors (fetch throws)\n * - HTTP 429 (Too Many Requests), respecting the Retry-After header\n * - HTTP 5xx (server errors)\n *\n * Does NOT retry on 4xx errors (except 429).\n * Uses exponential backoff: BASE_DELAY_MS * 2^attempt + random jitter (0..MAX_JITTER_MS).\n */\n private async executeWithRetry<T>(\n url: string,\n init: RequestInit\n ): Promise<T> {\n if (this.destroyed) {\n throw new TolinkuError('Tolinku: client has been destroyed. Call Tolinku.init() to reinitialize.', 0);\n }\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n this.pendingControllers.add(controller);\n\n // Set up timeout\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const res = await fetch(url, {\n ...init,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n this.pendingControllers.delete(controller);\n\n if (res.ok) {\n return res.json();\n }\n\n // Parse error body\n const errorBody = await res.json().catch(() => ({ error: res.statusText }));\n const errorMessage = errorBody.error || res.statusText;\n const errorCode = errorBody.code;\n\n // Determine if we should retry\n const isRetryable = res.status === 429 || (res.status >= 500 && res.status < 600);\n\n if (!isRetryable || attempt === MAX_RETRIES) {\n throw new TolinkuError(errorMessage, res.status, errorCode);\n }\n\n lastError = new TolinkuError(errorMessage, res.status, errorCode);\n\n // Calculate delay: respect Retry-After for 429, otherwise exponential backoff\n let delayMs: number;\n if (res.status === 429) {\n const retryAfter = res.headers.get('Retry-After');\n const retryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : NaN;\n if (!isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {\n delayMs = retryAfterSeconds * 1000;\n } else {\n delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n }\n } else {\n delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n }\n\n const jitter = Math.random() * MAX_JITTER_MS;\n const totalDelay = delayMs + jitter;\n\n debugLog(`Retry ${attempt + 1}/${MAX_RETRIES} after ${Math.round(totalDelay)}ms (status=${res.status})`);\n\n await sleep(totalDelay);\n } catch (err) {\n clearTimeout(timeoutId);\n this.pendingControllers.delete(controller);\n\n // If the client was destroyed, rethrow immediately\n if (this.destroyed) {\n throw new TolinkuError('Tolinku: request aborted (client destroyed).', 0);\n }\n\n // AbortController timeout\n if (isAbortError(err)) {\n const timeoutErr = new TolinkuError(`Tolinku: request timed out after ${this.timeout}ms`, 0);\n if (attempt === MAX_RETRIES) throw timeoutErr;\n lastError = timeoutErr;\n } else if (err instanceof TolinkuError) {\n // Already a TolinkuError (from the non-retryable branch above); rethrow\n throw err;\n } else {\n // Network error; retry\n if (attempt === MAX_RETRIES) {\n throw new TolinkuError(\n `Tolinku: network error after ${MAX_RETRIES + 1} attempts: ${(err as Error).message}`,\n 0\n );\n }\n lastError = err as Error;\n }\n\n const delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n const jitter = Math.random() * MAX_JITTER_MS;\n const totalDelay = delayMs + jitter;\n\n debugLog(`Retry ${attempt + 1}/${MAX_RETRIES} after ${Math.round(totalDelay)}ms (${(err as Error).message})`);\n\n await sleep(totalDelay);\n }\n }\n\n // Should not reach here, but just in case\n throw lastError || new TolinkuError('Tolinku: request failed after retries', 0);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class TolinkuError extends Error {\n status: number;\n code: string | undefined;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'TolinkuError';\n this.status = status;\n this.code = code;\n }\n}\n","/**\n * A URL's scheme, lowercased and with its colon, or null when it has none.\n *\n * Deliberately not `new URL(x).protocol`. React Native ships its own URL, and\n * for most of this package's supported range that URL is a stub whose getters\n * throw: `protocol`, `hostname`, `host` and `origin` are all\n * `throw new Error('… is not implemented')` in 0.73, and only gained real\n * implementations much later. Every call here sat inside a try/catch, so the\n * throw was swallowed as \"unparseable\", and everything this guards was refused\n * on device while passing every test, because Jest runs on Node's URL.\n *\n * That is why this parses the scheme itself. Whitespace and control characters\n * are stripped the way a URL parser strips them, from the ends and from inside\n * the scheme, so `java\\tscript:` is recognised as javascript: rather than\n * waved through as something unparseable.\n */\nexport function urlScheme(url: string): string | null {\n if (!url || typeof url !== 'string') return null;\n\n // Tabs and newlines are removed anywhere in a URL; spaces and C0 controls\n // are stripped from the ends.\n const cleaned = url.replace(/[\\t\\n\\r]/g, '').replace(/^[\\u0000-\\u0020]+|[\\u0000-\\u0020]+$/g, '');\n // The underscore is not RFC 3986, and Android registers it in a manifest\n // and iOS in CFBundleURLSchemes, so real apps have schemes carrying one.\n const match = /^([a-zA-Z][a-zA-Z\\d+\\-._]*):/.exec(cleaned);\n return match ? `${match[1]!.toLowerCase()}:` : null;\n}\n\n/**\n * The pieces of an http(s) URL this package needs, or null.\n *\n * Same reason as {@link urlScheme}: React Native's own URL throws from\n * `origin` and `hostname` for most of the versions this package supports, so\n * asking it for them turned a working link into a silent failure on device.\n */\nexport function parseHttpUrl(url: string): { origin: string; pathname: string } | null {\n if (!url || typeof url !== 'string') return null;\n const cleaned = url.replace(/[\\t\\n\\r]/g, '').trim();\n\n const match = /^(https?):\\/\\/([^/?#]+)([^?#]*)/i.exec(cleaned);\n if (!match) return null;\n\n const [, scheme, authority, path] = match;\n if (!authority) return null;\n\n return {\n origin: `${scheme!.toLowerCase()}://${authority.toLowerCase()}`,\n // A URL with no path means the root, which is what a server expects to be\n // asked about.\n pathname: path || '/',\n };\n}\n\n/**\n * Check if a URL is safe to open or render. Only allows http: and https: protocols.\n * Blocks javascript:, data:, file:, and other potentially dangerous protocols.\n */\nexport function isSafeUrl(url: string): boolean {\n const scheme = urlScheme(url);\n return scheme === 'http:' || scheme === 'https:';\n}\n\n/**\n * The schemes that can run code, read local storage, or hide another scheme.\n *\n * Longer than the platform's own list because this package ends up somewhere\n * the platform does not. `Linking.openURL` on Android becomes an Intent, so\n * `content:` reads a ContentProvider, which includes another app's private\n * files wherever a permission has been granted, and `jar:` and `filesystem:`\n * each carry a second URL inside them, so allowing either hands back whatever\n * the rest of this set refuses. None of the three mean anything in a browser,\n * which is why safe-url.ts does not name them.\n */\nconst EXECUTABLE_SCHEMES = new Set([\n 'javascript:',\n 'vbscript:',\n 'data:',\n 'blob:',\n 'file:',\n 'content:',\n 'jar:',\n 'filesystem:',\n]);\n\n/**\n * Check whether a URL is safe to follow when someone taps it.\n *\n * Deliberately not {@link isSafeUrl}. That one allows http and https only,\n * which is right for an image source and wrong for a call to action: this is a\n * deep linking product, so the most natural button in an in-app message is one\n * that opens a screen in the app, `myapp://order/4821`. An allowlist blocked\n * exactly that, silently, before the host app's own handler was even called,\n * while the platform that authored the message has always permitted it.\n *\n * Every customer's scheme is different, so there is no list to allow. The small\n * known set of dangerous schemes is named instead, matching the platform's own\n * rule, and everything else is left to open.\n *\n * Parsing first is what makes this hold: tabs and newlines inside a scheme are\n * ignored by the things that follow URLs, so \"java\\tscript:alert(1)\" would run,\n * and the URL parser strips them the same way before reporting the protocol.\n */\nexport function isSafeActionUrl(url: string): boolean {\n const scheme = urlScheme(url);\n // No scheme means relative or a fragment. There is no base to resolve it\n // against on a device, so it is not something to open.\n if (!scheme) return false;\n return !EXECUTABLE_SCHEMES.has(scheme);\n}\n\n/**\n * Validate that a base URL uses HTTPS, with exceptions for local development.\n * Throws an error if the URL is invalid.\n */\nexport function validateBaseUrl(baseUrl: string): void {\n if (!baseUrl || typeof baseUrl !== 'string') {\n throw new Error('Tolinku: baseUrl must be a non-empty string.');\n }\n\n const trimmed = baseUrl.trim();\n\n // Allow local development URLs over HTTP\n const isLocalDev =\n trimmed.startsWith('http://localhost') ||\n trimmed.startsWith('http://127.0.0.1') ||\n trimmed.startsWith('http://10.') ||\n /^http:\\/\\/172\\.(1[6-9]|2\\d|3[01])\\./.test(trimmed) ||\n trimmed.startsWith('http://192.168.');\n\n if (trimmed.startsWith('https://')) {\n return; // Valid HTTPS URL\n }\n\n if (isLocalDev) {\n return; // Valid local development URL\n }\n\n throw new Error(\n 'Tolinku: baseUrl must use HTTPS to protect your API key. Use https:// instead of http://. ' +\n 'Local development URLs (localhost, 127.0.0.1, 10.x, 172.16-31.x, 192.168.x) are exempt from this requirement.'\n );\n}\n\n/** Regex for valid custom event names (after the \"custom.\" prefix) */\nconst EVENT_NAME_REGEX = /^custom\\.[a-z0-9_]+$/;\n\n/**\n * Validate and normalize an event type name.\n * Auto-prefixes with \"custom.\" if missing.\n * Throws a descriptive error if the name is invalid.\n */\nexport function validateEventType(eventType: string): string {\n if (!eventType || typeof eventType !== 'string' || !eventType.trim()) {\n throw new Error('Tolinku: eventType must be a non-empty string.');\n }\n\n let normalized = eventType.trim();\n\n // Auto-prefix with \"custom.\" if not present\n if (!normalized.startsWith('custom.')) {\n normalized = 'custom.' + normalized;\n }\n\n if (!EVENT_NAME_REGEX.test(normalized)) {\n throw new Error(\n `Tolinku: invalid event type \"${normalized}\". ` +\n 'Event names must match the pattern \"custom.[a-z0-9_]+\". ' +\n 'Use only lowercase letters, digits, and underscores after the \"custom.\" prefix.'\n );\n }\n\n return normalized;\n}\n","import { AppState, Platform, type AppStateStatus, type NativeEventSubscription } from 'react-native';\nimport type { HttpClient } from './client';\nimport type { TrackProperties } from './types';\nimport { validateEventType, isSafeUrl } from './validation';\nimport { debugLog, debugWarn } from './debug';\n\n/** Number of events that triggers an automatic flush. */\nconst BATCH_SIZE = 10;\n/** Maximum time (ms) to wait before flushing after the first queued event. */\nconst FLUSH_INTERVAL_MS = 5000;\n/** Maximum number of events to keep in the queue to prevent unbounded growth. */\nconst MAX_QUEUE_SIZE = 1000;\n\ninterface QueuedEvent {\n event_type: string;\n properties: TrackProperties;\n}\n\nexport class Analytics {\n private client: HttpClient;\n private queue: QueuedEvent[] = [];\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private appStateSubscription: NativeEventSubscription | null = null;\n private isFlushing = false;\n\n constructor(client: HttpClient) {\n this.client = client;\n\n // Listen for app going to background to flush events\n this.appStateSubscription = AppState.addEventListener(\n 'change',\n this.handleAppStateChange\n );\n }\n\n /**\n * Track a custom event. The event is added to the internal queue\n * and will be flushed automatically or when flush() is called.\n *\n * Event type must match /^custom\\.[a-z0-9_]+$/.\n * Auto-prefixes with \"custom.\" if missing.\n */\n /**\n * Set once the server says this Appspace does not attribute app opens, so the\n * setting costs one request a launch rather than one per link.\n */\n private appOpensDisabled = false;\n\n /**\n * The last link reported, and when. Cold start and the link stream can both\n * deliver the same tap, depending on the plugin, so an app instrumenting both\n * paths would otherwise report it twice and be billed twice. A genuine second\n * tap of the same link inside this window is implausible; a duplicate delivery\n * of one tap is not.\n */\n private lastOpenUrl: string | null = null;\n private lastOpenAt = 0;\n private static readonly OPEN_DEDUPE_MS = 5000;\n\n\n /**\n * Report that a link opened the app without the browser being involved.\n *\n * A Universal Link or App Link hands the app the URL directly, so Tolinku is\n * never contacted and the tap goes unrecorded. Those taps come from people who\n * already have the app, so leaving them out makes a re-engagement campaign\n * look like a failure exactly when it worked.\n *\n * Only http and https links are reported. A custom scheme means Tolinku's own\n * hand-off page opened the app, and that tap was counted when the page was\n * served, so passing one does nothing rather than counting it twice.\n *\n * Never throws. This runs on the path that routes the user somewhere, and a\n * tap that goes unrecorded is not worth interrupting that.\n */\n async trackLinkOpen(url: string, userId?: string): Promise<void> {\n if (this.appOpensDisabled) return;\n\n const trimmed = typeof url === 'string' ? url.trim() : '';\n if (!trimmed) return;\n\n // The scheme decides, and the server checks it again.\n // Not the platform's URL: React Native's own throws from protocol on most\n // of the versions this package supports, and that throw was uncaught here,\n // so an open reported from a link turned into an unhandled rejection in\n // apps that call this without awaiting it, which is how it is documented.\n if (!isSafeUrl(trimmed)) return;\n\n const now = Date.now();\n if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < Analytics.OPEN_DEDUPE_MS) return;\n this.lastOpenUrl = trimmed;\n this.lastOpenAt = now;\n\n try {\n const result = await this.client.postPublic<{ attribute?: boolean }>(\n '/v1/api/opens',\n {\n url: trimmed,\n // The User-Agent cannot say which platform this is: this SDK\n // identifies itself the same way on both. Without it an app open has\n // no platform and lands in a blank bucket on every breakdown.\n platform: Platform.OS === 'ios' || Platform.OS === 'android' ? Platform.OS : undefined,\n ...(userId ? { user_id: userId } : {}),\n },\n );\n if (result?.attribute === false) this.appOpensDisabled = true;\n } catch {\n // Deliberately silent.\n }\n }\n\n async track(eventType: string, properties?: TrackProperties): Promise<void> {\n const normalizedType = validateEventType(eventType);\n\n const event: QueuedEvent = {\n event_type: normalizedType,\n properties: properties || {},\n };\n\n // Enforce max queue size\n if (this.queue.length >= MAX_QUEUE_SIZE) {\n debugWarn(\n `Analytics queue is full (${MAX_QUEUE_SIZE} events). Dropping oldest event to make room.`\n );\n this.queue.shift();\n }\n\n this.queue.push(event);\n\n if (this.queue.length >= BATCH_SIZE) {\n await this.flush();\n } else if (this.queue.length === 1) {\n // First event in the queue; start the flush timer\n this.startFlushTimer();\n }\n }\n\n /**\n * Immediately flush all queued events to the server.\n * If the queue is empty, this is a no-op.\n * If a flush is already in progress, this is a no-op to prevent race conditions.\n */\n async flush(): Promise<void> {\n if (this.queue.length === 0 || this.isFlushing) return;\n\n this.isFlushing = true;\n\n // Take a snapshot and clear the queue\n const eventsToSend = this.queue.splice(0, this.queue.length);\n this.cancelFlushTimer();\n\n try {\n debugLog(`Flushing ${eventsToSend.length} analytics event(s)`);\n const result = await this.client.post<{ ok: boolean; accepted?: number; errors?: string[] }>('/v1/api/analytics/batch', {\n events: eventsToSend,\n });\n if (result.errors && result.errors.length > 0) {\n debugWarn(`Batch partial failure: ${result.errors.join(', ')}`);\n }\n } catch (err) {\n debugWarn(`Failed to flush analytics events: ${(err as Error).message}`);\n // Re-enqueue events at the front (up to MAX_QUEUE_SIZE)\n const spaceLeft = MAX_QUEUE_SIZE - this.queue.length;\n if (spaceLeft > 0) {\n this.queue.unshift(...eventsToSend.slice(0, spaceLeft));\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n /**\n * Shut down the analytics module: flush remaining events, cancel the timer,\n * and remove the AppState listener.\n */\n async destroy(): Promise<void> {\n this.cancelFlushTimer();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n try {\n await this.flush();\n } catch {\n // Best-effort flush during shutdown\n }\n }\n\n private handleAppStateChange = (state: AppStateStatus): void => {\n if (state === 'background' || state === 'inactive') {\n // Fire-and-forget flush when going to background\n this.flush().catch(() => {});\n }\n };\n\n private startFlushTimer(): void {\n this.cancelFlushTimer();\n this.flushTimer = setTimeout(() => {\n this.flush().catch((err) => {\n debugWarn(`Timer flush failed: ${(err as Error).message}`);\n });\n }, FLUSH_INTERVAL_MS);\n }\n\n private cancelFlushTimer(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n}\n","import { AppState, type AppStateStatus, type NativeEventSubscription } from 'react-native';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport type { HttpClient } from './client';\nimport type {\n EcommerceItem, PurchaseParams, AddToCartParams, RemoveFromCartParams,\n AddToWishlistParams, BeginCheckoutParams, RefundParams, ViewItemParams,\n SearchParams, ShareParams, RateParams, SpendCreditsParams, AddPaymentInfoParams,\n} from './types';\nimport { debugLog, debugWarn } from './debug';\n\nconst BATCH_SIZE = 10;\nconst FLUSH_INTERVAL_MS = 5000;\nconst MAX_QUEUE_SIZE = 500;\nconst CART_ID_STORAGE_KEY = 'tolinku_ecom_cart_id';\n\ninterface QueuedEcomEvent {\n event_type: string;\n transaction_id?: string;\n revenue?: number;\n currency?: string;\n cart_id?: string;\n coupon_code?: string;\n discount?: number;\n shipping?: number;\n tax?: number;\n items?: EcommerceItem[];\n properties?: Record<string, string>;\n user_id?: string;\n campaign?: string;\n source?: string;\n medium?: string;\n platform?: string;\n}\n\nexport class Ecommerce {\n private client: HttpClient;\n private queue: QueuedEcomEvent[] = [];\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private appStateSubscription: NativeEventSubscription | null = null;\n private isFlushing = false;\n private getUserId: () => string | null;\n private memoryCartId: string | null = null;\n\n constructor(client: HttpClient, getUserId: () => string | null) {\n this.client = client;\n this.getUserId = getUserId;\n\n this.appStateSubscription = AppState.addEventListener(\n 'change',\n this.handleAppStateChange,\n );\n }\n\n // ─── Public methods (13 event types) ────────────────────\n\n async viewItem(params: ViewItemParams): Promise<void> {\n await this.enqueue({ event_type: 'view_item', items: params.items });\n }\n\n async addToCart(params: AddToCartParams): Promise<void> {\n const cartId = params.cart_id || await this.getOrCreateCartId();\n await this.enqueue({ event_type: 'add_to_cart', items: params.items, cart_id: cartId });\n }\n\n async removeFromCart(params: RemoveFromCartParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({ event_type: 'remove_from_cart', items: params.items, cart_id: cartId });\n }\n\n async addToWishlist(params: AddToWishlistParams): Promise<void> {\n await this.enqueue({ event_type: 'add_to_wishlist', items: params.items });\n }\n\n async viewCart(): Promise<void> {\n const cartId = await this.getCartId();\n await this.enqueue({ event_type: 'view_cart', cart_id: cartId });\n }\n\n async addPaymentInfo(params?: AddPaymentInfoParams): Promise<void> {\n const cartId = params?.cart_id || await this.getCartId();\n await this.enqueue({ event_type: 'add_payment_info', cart_id: cartId });\n }\n\n async beginCheckout(params: BeginCheckoutParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({\n event_type: 'begin_checkout',\n revenue: params.revenue,\n currency: params.currency,\n cart_id: cartId,\n items: params.items,\n });\n }\n\n async purchase(params: PurchaseParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({\n event_type: 'purchase',\n transaction_id: params.transaction_id,\n revenue: params.revenue,\n currency: params.currency,\n cart_id: cartId,\n coupon_code: params.coupon_code,\n discount: params.discount,\n shipping: params.shipping,\n tax: params.tax,\n items: params.items,\n });\n await this.clearCartId();\n }\n\n async refund(params: RefundParams): Promise<void> {\n await this.enqueue({\n event_type: 'refund',\n transaction_id: params.transaction_id,\n revenue: params.revenue,\n currency: params.currency,\n items: params.items,\n });\n }\n\n async search(params: SearchParams): Promise<void> {\n await this.enqueue({ event_type: 'search', properties: { search_term: params.search_term } });\n }\n\n async share(params: ShareParams): Promise<void> {\n const props: Record<string, string> = {};\n if (params.item_id) props.item_id = params.item_id;\n if (params.url) props.url = params.url;\n if (params.method) props.method = params.method;\n await this.enqueue({ event_type: 'share', properties: props });\n }\n\n async rate(params: RateParams): Promise<void> {\n await this.enqueue({\n event_type: 'rate',\n properties: {\n item_id: params.item_id,\n rating: String(params.rating),\n ...(params.max_rating != null ? { max_rating: String(params.max_rating) } : {}),\n },\n });\n }\n\n async spendCredits(params: SpendCreditsParams): Promise<void> {\n await this.enqueue({ event_type: 'spend_credits', revenue: params.revenue, currency: params.currency });\n }\n\n // ─── Flush ─────────────────────────────────────────────\n\n async flush(): Promise<void> {\n if (this.queue.length === 0 || this.isFlushing) return;\n\n this.isFlushing = true;\n const events = this.queue.splice(0);\n this.cancelFlushTimer();\n\n try {\n debugLog(`Flushing ${events.length} ecommerce event(s)`);\n const result = await this.client.post<{ ok: boolean; accepted?: number; errors?: string[] }>(\n '/v1/api/analytics/ecommerce/batch',\n { events },\n );\n if (result.errors && result.errors.length > 0) {\n debugWarn(`Ecommerce batch partial failure: ${result.errors.join(', ')}`);\n }\n } catch (err) {\n debugWarn(`Failed to flush ecommerce events: ${(err as Error).message}`);\n const spaceLeft = MAX_QUEUE_SIZE - this.queue.length;\n if (spaceLeft > 0) {\n this.queue.unshift(...events.slice(0, spaceLeft));\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n async destroy(): Promise<void> {\n this.cancelFlushTimer();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n try {\n await this.flush();\n } catch {\n // Best-effort flush during shutdown\n }\n }\n\n // ─── Private ───────────────────────────────────────────\n\n private async enqueue(event: QueuedEcomEvent): Promise<void> {\n const userId = this.getUserId();\n if (userId) event.user_id = userId;\n\n if (this.queue.length >= MAX_QUEUE_SIZE) {\n debugWarn(`Ecommerce queue full (${MAX_QUEUE_SIZE}). Dropping oldest event.`);\n this.queue.shift();\n }\n\n this.queue.push(event);\n\n if (this.queue.length >= BATCH_SIZE) {\n await this.flush();\n } else if (this.queue.length === 1) {\n this.startFlushTimer();\n }\n }\n\n private handleAppStateChange = (state: AppStateStatus): void => {\n if (state === 'background' || state === 'inactive') {\n this.flush().catch(() => {});\n }\n };\n\n private startFlushTimer(): void {\n this.cancelFlushTimer();\n this.flushTimer = setTimeout(() => {\n this.flush().catch((err) => {\n debugWarn(`Ecommerce timer flush failed: ${(err as Error).message}`);\n });\n }, FLUSH_INTERVAL_MS);\n }\n\n private cancelFlushTimer(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n // ─── Cart ID lifecycle (AsyncStorage + memory fallback) ─\n\n private async getOrCreateCartId(): Promise<string> {\n const existing = await this.getCartId();\n if (existing) return existing;\n\n const cartId = this.generateId();\n await this.setCartId(cartId);\n return cartId;\n }\n\n private async getCartId(): Promise<string | undefined> {\n try {\n const stored = await AsyncStorage.getItem(CART_ID_STORAGE_KEY);\n if (stored) return stored;\n } catch { /* ignore */ }\n return this.memoryCartId || undefined;\n }\n\n private async setCartId(cartId: string): Promise<void> {\n this.memoryCartId = cartId;\n try {\n await AsyncStorage.setItem(CART_ID_STORAGE_KEY, cartId);\n } catch { /* memory fallback is already set */ }\n }\n\n private async clearCartId(): Promise<void> {\n this.memoryCartId = null;\n try {\n await AsyncStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch { /* ignore */ }\n }\n\n private generateId(): string {\n // Hermes has crypto.randomUUID from React Native 0.74, and older engines\n // and polyfill-free builds have no crypto at all, so this is read off\n // globalThis rather than named as a bare global. React Native's types used\n // to declare `crypto` for us; they no longer do, and naming it directly\n // stopped compiling on React Native 0.88 for that reason.\n const g = globalThis as { crypto?: { randomUUID?: () => string } };\n if (typeof g.crypto?.randomUUID === 'function') {\n return g.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n}\n","import type { HttpClient } from './client';\nimport type {\n CreateReferralOptions,\n CreateReferralResult,\n CompleteReferralOptions,\n CompleteReferralResult,\n MilestoneOptions,\n MilestoneResult,\n ReferralInfo,\n LeaderboardEntry,\n} from './types';\n\nexport class Referrals {\n constructor(private client: HttpClient) {}\n\n /** Create a new referral for a user */\n async create(options: CreateReferralOptions): Promise<CreateReferralResult> {\n if (!options.userId || !options.userId.trim()) {\n throw new Error('Tolinku: userId is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/create', {\n user_id: options.userId,\n metadata: options.metadata,\n user_name: options.userName,\n });\n }\n\n /** Get referral info by code */\n async get(code: string): Promise<ReferralInfo> {\n if (!code || !code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n\n return this.client.get(`/v1/api/referral/${encodeURIComponent(code)}`);\n }\n\n /** Complete a referral (mark as converted) */\n async complete(options: CompleteReferralOptions): Promise<CompleteReferralResult> {\n if (!options.code || !options.code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n if (!options.referredUserId || !options.referredUserId.trim()) {\n throw new Error('Tolinku: referredUserId is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/complete', {\n referral_code: options.code,\n referred_user_id: options.referredUserId,\n milestone: options.milestone,\n referred_user_name: options.referredUserName,\n });\n }\n\n /** Update a referral milestone */\n async milestone(options: MilestoneOptions): Promise<MilestoneResult> {\n if (!options.code || !options.code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n if (!options.milestone || !options.milestone.trim()) {\n throw new Error('Tolinku: milestone is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/milestone', {\n referral_code: options.code,\n milestone: options.milestone,\n });\n }\n\n /** Claim a referral reward */\n async claimReward(code: string): Promise<{ success: boolean; referral_code: string; reward_claimed: boolean }> {\n if (!code || !code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/claim-reward', {\n referral_code: code,\n });\n }\n\n /** Get the referral leaderboard */\n async leaderboard(limit: number = 25): Promise<{ leaderboard: LeaderboardEntry[] }> {\n return this.client.get('/v1/api/referral/leaderboard', {\n limit: String(limit),\n });\n }\n}\n","import { NativeModules, Platform } from 'react-native';\nimport { debugWarn } from './debug';\n\n/**\n * The Play Install Referrer, the deterministic half of deferred linking on\n * Android.\n *\n * A Tolinku link sends an Android visitor to the store with\n * `referrer=tolk_token=<token>` attached. Play keeps that string through the\n * install and returns it on first launch, naming the exact click rather than\n * inferring it from device signals.\n *\n * Reading it needs a Play Services binding, which is native code, and this\n * package ships that itself: the token is Tolinku's own mechanism, minted on the\n * link, so reading it back should not depend on a third party. Nothing extra to\n * install, and autolinking is per-platform so an iOS-only app never builds it.\n *\n * Where the native module is absent, notably in Expo Go, deferred linking still\n * works through signal matching, less precisely.\n */\n\nconst TOKEN_KEY = 'tolk_token';\n\n/**\n * Pull our token out of a Play referrer string.\n *\n * The referrer is shared. A developer's own `utm_source` and anything else they\n * attached sit in the same string, so the token is found among the pairs rather\n * than assumed to be the whole value. A percent-encoded `%3D` is tolerated\n * because Play normally decodes it, and that assumption is not worth a lost\n * install if it is ever wrong.\n */\nexport function parseInstallReferrer(referrer: string | null | undefined): string | null {\n if (!referrer || !referrer.trim()) return null;\n\n let decoded = referrer;\n try {\n decoded = decodeURIComponent(referrer);\n } catch {\n // Malformed encoding: fall back to the raw string.\n }\n\n const pair = decoded\n .split('&')\n .map(p => p.trim())\n .find(p => p.startsWith(`${TOKEN_KEY}=`));\n\n if (!pair) return null;\n const token = pair.slice(TOKEN_KEY.length + 1);\n return token.trim() ? token : null;\n}\n\n/** Anything that can hand back a Play referrer string. */\nexport type ReferrerProvider = () => Promise<string | null> | string | null;\n\n/**\n * Our own native module, when the app was built with it.\n *\n * Accessed lazily rather than at import time. In Expo Go, and anywhere the\n * native side was not built, this is simply absent, and touching NativeModules\n * during module evaluation would turn that ordinary case into a crash on first\n * launch.\n */\nfunction nativeProvider(): ReferrerProvider | null {\n const native = (NativeModules as Record<string, any> | undefined)?.TolinkuInstallReferrer;\n if (!native || typeof native.getInstallReferrer !== 'function') return null;\n return () => native.getInstallReferrer();\n}\n\n/**\n * Best effort at the referrer token for this install.\n *\n * Android only, and null everywhere else: there is no equivalent on iOS, which\n * is why signal matching exists at all. Never throws, because attribution must\n * not be able to fail a first launch.\n */\nexport async function getInstallReferrerToken(\n provider?: ReferrerProvider,\n): Promise<string | null> {\n if (Platform.OS !== 'android') return null;\n\n const source = provider ?? nativeProvider();\n if (!source) return null;\n\n try {\n const referrer = await source();\n return parseInstallReferrer(referrer);\n } catch (err) {\n debugWarn(`Install referrer lookup failed: ${(err as Error).message}`);\n return null;\n }\n}\n","import { Dimensions, PixelRatio, Platform } from 'react-native';\nimport type { HttpClient } from './client';\nimport type { DeferredLink, ClaimBySignalsOptions } from './types';\nimport { debugWarn } from './debug';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { getInstallReferrerToken, type ReferrerProvider } from './install-referrer';\n\n/**\n * Marks that a deferred claim already ran on this install.\n *\n * Claiming is a first-launch action, but nothing stops an app calling it every\n * launch, which is an easy mistake. Each repeat costs a request and records a\n * miss, so a healthy integration would report a match rate near zero.\n * Remembering the attempt belongs here rather than in every integrator's code.\n */\nconst CLAIMED_KEY = 'tolinku_deferred_claimed';\n\nexport class Deferred {\n constructor(private client: HttpClient) {}\n\n /** Claim a deferred deep link by referrer token (from Play Store referrer or clipboard) */\n async claimByToken(token: string, appspaceId?: string): Promise<DeferredLink | null> {\n if (!token || !token.trim()) {\n throw new Error('Tolinku: token is required and must not be blank for claimByToken.');\n }\n\n try {\n // appspaceId narrows what the token may claim, never widens it, and it is\n // what lets a failed claim be attributed: the default host resolves to no\n // Appspace, so without it a miss belongs to nobody and goes uncounted.\n return await this.client.getPublic<DeferredLink>('/v1/api/deferred/claim', {\n token,\n ...(appspaceId ? { appspace_id: appspaceId } : {}),\n });\n } catch (err) {\n debugWarn(`Deferred claimByToken failed: ${(err as Error).message}`);\n return null;\n }\n }\n\n /**\n * Recover the link that led to this install, trying both mechanisms.\n *\n * The Play Install Referrer is asked first on Android: it names the exact\n * click, survives for days, and does not care which network the device was\n * on. Device signals are the fallback, and the only option on iOS, where no\n * equivalent exists.\n *\n * Call once on first launch. Safe to call again, but a claim is consumed the\n * first time it succeeds, so a second call returns null.\n *\n * Reading the referrer needs a native Play Services binding, which this\n * package deliberately does not bundle. Pass `referrerProvider`, or install a\n * supported referrer package and it is used automatically. Without either,\n * Android falls back to signal matching.\n */\n async claimDeferredLink(options: {\n appspaceId: string;\n referrerProvider?: ReferrerProvider;\n /** Claim again even if an attempt was already recorded. For tests. */\n force?: boolean;\n }): Promise<DeferredLink | null> {\n if (!options.appspaceId || !options.appspaceId.trim()) {\n throw new Error('Tolinku: appspaceId is required and must not be blank for claimDeferredLink.');\n }\n\n if (!options.force && (await this.alreadyAttempted())) return null;\n\n const token = await getInstallReferrerToken(options.referrerProvider);\n if (token) {\n // A referrer that cannot be claimed is worth one fallback rather than an\n // error: the install still happened.\n const byToken = await this.claimByToken(token, options.appspaceId).catch(() => null);\n if (byToken) {\n await this.rememberAttempt();\n return byToken;\n }\n }\n\n const { link, settled } = await this.attemptSignals({ appspaceId: options.appspaceId });\n // Only a real answer is remembered. A dropped request leaves this unwritten\n // so the next launch tries again: losing an install's attribution to one\n // bad connection is worse than one extra request.\n if (settled) await this.rememberAttempt();\n return link;\n }\n\n private async alreadyAttempted(): Promise<boolean> {\n try {\n return (await AsyncStorage.getItem(CLAIMED_KEY)) !== null;\n } catch {\n // Storage unavailable: attempt the claim rather than skip it.\n return false;\n }\n }\n\n private async rememberAttempt(): Promise<void> {\n try {\n await AsyncStorage.setItem(CLAIMED_KEY, new Date().toISOString());\n } catch {\n // Not worth failing a claim that already succeeded.\n }\n }\n\n /** Claim a deferred deep link by device signal matching */\n async claimBySignals(options: ClaimBySignalsOptions): Promise<DeferredLink | null> {\n if (!options.appspaceId || !options.appspaceId.trim()) {\n throw new Error('Tolinku: appspaceId is required and must not be blank for claimBySignals.');\n }\n return (await this.attemptSignals(options)).link;\n }\n\n /**\n * The signal claim, with whether the server actually answered.\n *\n * `settled` separates \"nothing is waiting for this device\", which no amount\n * of asking will change, from \"the request never got there\". Both surface as\n * null to callers of claimBySignals, but claimDeferredLink has to tell them\n * apart: recording an attempt that never reached the server would spend an\n * install's one chance at attribution on a dropped connection.\n */\n private async attemptSignals(\n options: ClaimBySignalsOptions,\n ): Promise<{ link: DeferredLink | null; settled: boolean }> {\n try {\n const { width, height } = Dimensions.get('screen');\n const resolvedTimezone = override(options.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone;\n // Matched against the landing page's `navigator.language`, a full BCP-47 tag\n // such as \"ko-KR\". Defaulting to a bare \"en\" meant the language signal\n // almost never scored. Intl reports the device locale with its region on\n // any runtime with Intl support (Hermes has it enabled by default).\n const resolvedLanguage =\n override(options.language) ||\n (typeof Intl !== 'undefined' && typeof Intl.DateTimeFormat === 'function'\n ? Intl.DateTimeFormat().resolvedOptions().locale\n : undefined) ||\n 'en';\n\n const link = await this.client.postPublic<DeferredLink>('/v1/api/deferred/claim-by-signals', {\n appspace_id: options.appspaceId,\n timezone: resolvedTimezone,\n language: resolvedLanguage,\n screen_width: override(options.screenWidth) || width,\n screen_height: override(options.screenHeight) || height,\n // Separates devices reporting identical dp dimensions.\n device_pixel_ratio: override(options.devicePixelRatio) || PixelRatio.get(),\n os_version: override(options.osVersion) || String(Platform.Version),\n });\n return { link, settled: true };\n } catch (err) {\n // A 404 is the ordinary \"nothing waiting for this device\" outcome. Anything\n // else is a configuration problem the integrator has to see: in particular a\n // 403 means appspaceId is wrong, and silently returning null there turns a\n // one-line fix into days of debugging.\n const status = (err as { statusCode?: number; status?: number })?.statusCode\n ?? (err as { status?: number })?.status;\n if (status === 404) {\n // Nothing is waiting for this device. The ordinary outcome, not a fault,\n // and a final one: asking again cannot change it.\n debugWarn('Deferred claimBySignals: no match for this device.');\n return { link: null, settled: true };\n }\n if (status === 403) {\n console.warn(\n '[Tolinku] claimBySignals failed with HTTP 403. Check that appspaceId is your ' +\n 'Appspace ID (copy it from the dashboard under Settings), not your subdomain ' +\n `or slug. ${(err as Error).message}`,\n );\n return { link: null, settled: false };\n }\n debugWarn(`Deferred claimBySignals failed: ${(err as Error).message}`);\n return { link: null, settled: false };\n }\n }\n}\n\n/**\n * An override the caller actually supplied.\n *\n * A blank string and a non-positive number are what an unset configuration value\n * and a failed lookup look like. Taking one literally would replace a good value\n * the device reported with one the matcher cannot use, and a signal that is\n * present and disagrees counts against the match where an absent one is simply\n * skipped. So a blank override is worse than no override, which is the opposite\n * of what the caller intends by passing it.\n */\nfunction override(value: string | undefined): string | undefined;\nfunction override(value: number | undefined): number | undefined;\nfunction override(value: string | number | undefined): string | number | undefined {\n if (typeof value === 'string') {\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n }\n if (typeof value === 'number') {\n return Number.isFinite(value) && value > 0 ? value : undefined;\n }\n return undefined;\n}\n","import type { HttpClient } from './client';\nimport type { ResolvedLink } from './types';\nimport { debugWarn } from './debug';\nimport { parseHttpUrl } from './validation';\n\n/**\n * Working out what a link the operating system handed the app actually means.\n *\n * An app receives the URL that was tapped, exactly as it was written. That is\n * fine while the URL is readable: `/order/4821` says \"order\" and the app can\n * route it. It is not fine for a short link, which is the same route written as\n * a code:\n *\n * https://links.example.com/s7k2p9q/4821\n *\n * Nothing in that URL says \"order\", and nothing about the code can be worked\n * out on the device. An app parsing the path itself sees a first segment it has\n * never heard of and does nothing, so the link opens the app and then appears\n * to fail, which is the quietest way a link can break: no error, no screen, no\n * clue. Short links are what a dashboard offers for sharing and what a QR code\n * carries, so this is not a rare path.\n *\n * `resolve` asks the platform, which answers with the route, the token and the\n * canonical path, and the app can route that the way it routes anything else.\n * A readable URL comes back unchanged, so an app can simply resolve everything\n * rather than guessing which kind it has.\n */\n/**\n * Whether the platform's answer is the path it promises to be.\n *\n * `resolve` sends its question to a host taken from the URL it was given, so an\n * app resolving a link from somewhere it does not control is talking to a\n * stranger. The contract is a path and nothing else: a full URL, or a protocol\n * relative \"//host\" that reads as one, is a redirect waiting to happen in\n * whatever the app does with it next.\n */\nfunction isRoutablePath(path: unknown): path is string {\n return typeof path === 'string'\n && path.startsWith('/')\n && !path.startsWith('//');\n}\n\nexport class Links {\n constructor(private client: HttpClient) {}\n\n /**\n * What this link means, or null if it means nothing here.\n *\n * `url` is a whole link as the app received it. The question goes to the\n * link's own host, because that is how the platform knows which Appspace is\n * being asked about, which also means a link on a domain that is not yours\n * simply answers nothing.\n *\n * Never throws. A link that cannot be resolved, for a bad network or any\n * other reason, is one the app should fall back to its own handling for, and\n * an exception in the middle of a cold start is no way to say so.\n */\n async resolve(url: string): Promise<ResolvedLink | null> {\n if (!url || typeof url !== 'string') return null;\n\n // Parsed here rather than with the platform's URL: React Native's own URL\n // throws from origin and protocol on most of the versions this package\n // supports, and the throw landed inside the catch below, so a perfectly\n // good link came back as \"not a URL\" on device while every test passed.\n //\n // http and https only. A custom scheme link already carries the path the\n // app wants, and anything else is not a link this could answer for.\n const parsed = parseHttpUrl(url);\n if (!parsed) {\n debugWarn(`Links.resolve: not an http(s) URL: ${url}`);\n return null;\n }\n\n try {\n const result = await this.client.postPublicToOrigin<ResolvedLink>(\n parsed.origin,\n '/v1/api/path',\n { path: parsed.pathname },\n );\n if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;\n return result;\n } catch (err) {\n debugWarn(`Links.resolve failed: ${(err as Error).message}`);\n return null;\n }\n }\n}\n","import AsyncStorage from '@react-native-async-storage/async-storage';\n\nconst BASE_KEY = 'tolinku_message_dismissed';\nconst IMPRESSIONS_BASE_KEY = 'tolinku_message_impressions';\nconst LAST_SHOWN_BASE_KEY = 'tolinku_message_last_shown';\n\n/** Current namespace prefix, set when the SDK is initialized. */\nlet keyPrefix = BASE_KEY;\nlet impressionsKeyPrefix = IMPRESSIONS_BASE_KEY;\nlet lastShownKeyPrefix = LAST_SHOWN_BASE_KEY;\n\n/**\n * Set the storage namespace based on the API key.\n * This prevents collisions when the same app uses multiple Appspaces.\n * Uses a simple hash of the API key to keep storage keys short.\n */\nexport function setStorageNamespace(apiKey: string): void {\n const hash = simpleHash(apiKey);\n keyPrefix = `tolinku_${hash}_message_dismissed`;\n impressionsKeyPrefix = `tolinku_${hash}_message_impressions`;\n lastShownKeyPrefix = `tolinku_${hash}_message_last_shown`;\n}\n\n/** Reset to the default (un-namespaced) key. Used during destroy(). */\nexport function resetStorageNamespace(): void {\n keyPrefix = BASE_KEY;\n impressionsKeyPrefix = IMPRESSIONS_BASE_KEY;\n lastShownKeyPrefix = LAST_SHOWN_BASE_KEY;\n}\n\nasync function getStore(key: string): Promise<Record<string, string>> {\n try {\n const raw = await AsyncStorage.getItem(key);\n return raw ? JSON.parse(raw) : {};\n } catch {\n return {};\n }\n}\n\nasync function setStore(key: string, data: Record<string, string>): Promise<void> {\n try {\n await AsyncStorage.setItem(key, JSON.stringify(data));\n } catch {\n // Storage unavailable\n }\n}\n\nexport async function isMessageDismissed(messageId: string, dismissDays: number | null): Promise<boolean> {\n if (!dismissDays || dismissDays <= 0) return false;\n const data = await getStore(keyPrefix);\n const entry = data[messageId];\n if (!entry) return false;\n const dismissedAt = new Date(entry).getTime();\n return (Date.now() - dismissedAt) < (dismissDays * 86400000);\n}\n\nexport async function saveMessageDismissal(messageId: string): Promise<void> {\n const data = await getStore(keyPrefix);\n data[messageId] = new Date().toISOString();\n await setStore(keyPrefix, data);\n}\n\n/**\n * Check if a message should be suppressed based on max_impressions\n * or min_interval_hours. Returns true if the message should NOT be shown.\n */\nexport async function isMessageSuppressed(\n messageId: string,\n maxImpressions: number | null,\n minIntervalHours: number | null,\n): Promise<boolean> {\n // Check max impressions\n if (maxImpressions !== null && maxImpressions > 0) {\n const impressions = await getStore(impressionsKeyPrefix);\n const count = parseInt(impressions[messageId] || '0', 10);\n if (count >= maxImpressions) return true;\n }\n\n // Check min interval\n if (minIntervalHours !== null && minIntervalHours > 0) {\n const lastShown = await getStore(lastShownKeyPrefix);\n const entry = lastShown[messageId];\n if (entry) {\n const lastShownAt = new Date(entry).getTime();\n const intervalMs = minIntervalHours * 3600000;\n if ((Date.now() - lastShownAt) < intervalMs) return true;\n }\n }\n\n return false;\n}\n\n/** Record that a message was shown (increment impression count and update last-shown time). */\nexport async function recordMessageImpression(messageId: string): Promise<void> {\n // Increment impression count\n const impressions = await getStore(impressionsKeyPrefix);\n const count = parseInt(impressions[messageId] || '0', 10);\n impressions[messageId] = String(count + 1);\n await setStore(impressionsKeyPrefix, impressions);\n\n // Update last-shown timestamp\n const lastShown = await getStore(lastShownKeyPrefix);\n lastShown[messageId] = new Date().toISOString();\n await setStore(lastShownKeyPrefix, lastShown);\n}\n\n/**\n * Simple string hash (djb2 algorithm). Returns a short hex string.\n */\nfunction simpleHash(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash + str.charCodeAt(i)) & 0xffffffff;\n }\n return (hash >>> 0).toString(16);\n}\n","import { HttpClient } from './client';\nimport { Analytics } from './analytics';\nimport { Ecommerce } from './ecommerce';\nimport { Referrals } from './referrals';\nimport { Deferred } from './deferred';\nimport { Links } from './links';\nimport { validateBaseUrl } from './validation';\nimport { setDebugEnabled, debugLog, debugWarn } from './debug';\nimport { setStorageNamespace, resetStorageNamespace } from './storage';\nimport { SDK_VERSION } from './types';\nimport type { TolinkuConfig, ResolvedTolinkuConfig, TrackProperties } from './types';\n\n/**\n * Main Tolinku SDK singleton.\n *\n * Initialize once with Tolinku.init(), then use static methods for all operations.\n *\n * Example:\n * Tolinku.init({ apiKey: 'tolk_pub_...' });\n * await Tolinku.track('signup', { source: 'onboarding' });\n */\nexport class Tolinku {\n static readonly VERSION = SDK_VERSION;\n\n private static client: HttpClient | null = null;\n private static analyticsInstance: Analytics | null = null;\n private static ecommerceInstance: Ecommerce | null = null;\n private static referralsInstance: Referrals | null = null;\n private static deferredInstance: Deferred | null = null;\n private static linksInstance: Links | null = null;\n private static _initialized = false;\n private static _userId: string | null = null;\n\n /**\n * Initialize the SDK. Must be called before any other method.\n *\n * If init() is called a second time without calling destroy() first,\n * a warning is logged and the existing instance is returned.\n */\n /**\n * Configure the SDK.\n *\n * The name the Android, iOS and Flutter SDKs use for this. {@link init} does\n * the same thing and still works; it is what this package shipped and\n * breaking it would serve nobody. It is meant for deprecation later, once\n * moving off it is a one-line change rather than a surprise.\n */\n static configure(config: TolinkuConfig): void {\n Tolinku.init(config);\n }\n\n static init(config: TolinkuConfig): void {\n if (!config.apiKey) throw new Error('Tolinku: apiKey is required');\n\n // Double-init guard: warn and return if already configured\n if (Tolinku._initialized) {\n debugWarn(\n 'Tolinku.init() called while already initialized. ' +\n 'Call Tolinku.destroy() first if you need to reconfigure.'\n );\n // Also log to console even without debug mode, since this is a potential bug\n console.warn(\n '[TolinkuSDK] init() called while already initialized. ' +\n 'Call Tolinku.destroy() first if you need to reconfigure.'\n );\n return;\n }\n\n // Resolve defaults\n const baseUrl = config.baseUrl || 'https://api.tolinku.com';\n\n // Validate HTTPS\n validateBaseUrl(baseUrl);\n\n // Enable/disable debug logging\n setDebugEnabled(config.debug === true);\n\n const resolvedConfig: ResolvedTolinkuConfig = {\n apiKey: config.apiKey,\n baseUrl,\n debug: config.debug === true,\n timeout: config.timeout ?? 30000,\n };\n\n // Namespace storage keys by API key\n setStorageNamespace(config.apiKey);\n\n Tolinku.client = new HttpClient(resolvedConfig);\n Tolinku.analyticsInstance = new Analytics(Tolinku.client);\n Tolinku.ecommerceInstance = new Ecommerce(Tolinku.client, () => Tolinku._userId);\n Tolinku.referralsInstance = new Referrals(Tolinku.client);\n Tolinku.deferredInstance = new Deferred(Tolinku.client);\n Tolinku.linksInstance = new Links(Tolinku.client);\n Tolinku._initialized = true;\n\n debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);\n }\n\n /** Check whether the SDK has been initialized. */\n static isConfigured(): boolean {\n return Tolinku._initialized;\n }\n\n /**\n * Set the user ID for segment targeting and analytics attribution.\n * Pass null to clear the user ID.\n */\n static setUserId(userId: string | null): void {\n Tolinku._userId = userId;\n }\n\n /** Get the current user ID, or null if not set. */\n static getUserId(): string | null {\n return Tolinku._userId;\n }\n\n /** Get the underlying HTTP client (used internally by MessageProvider) */\n static getClient(): HttpClient {\n if (!Tolinku.client) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.client;\n }\n\n /**\n * Track a custom event (shorthand for analytics.track).\n * Event type is auto-prefixed with \"custom.\" if not already.\n * Events are batched and flushed automatically.\n */\n static async track(eventType: string, properties?: TrackProperties): Promise<void> {\n if (!Tolinku.analyticsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n const mergedProps = Tolinku._userId\n ? { user_id: Tolinku._userId, ...properties }\n : properties;\n return Tolinku.analyticsInstance.track(eventType, mergedProps);\n }\n\n /**\n * Report that a link opened the app, when it opened without the browser.\n *\n * A Universal Link or App Link hands the app the URL directly, so Tolinku is\n * never contacted and the tap goes unrecorded. Those taps come from people who\n * already have your app, so leaving them out makes a re-engagement campaign\n * look like a failure exactly when it worked.\n *\n * Both ways a link arrives need it. The listener fires only while the app is\n * already running, so a link that launched the app cold arrives separately:\n *\n * ```ts\n * // Launched by a link, app was not running.\n * const initial = await Linking.getInitialURL();\n * if (initial) Tolinku.trackLinkOpen(initial);\n *\n * // Tapped while the app was already open.\n * Linking.addEventListener('url', ({ url }) => {\n * Tolinku.trackLinkOpen(url);\n * // your own routing\n * });\n * ```\n *\n * Wiring both is safe: the same link arriving twice in quick succession is\n * reported once.\n *\n * Only http and https links are reported. A custom scheme means Tolinku's own\n * hand-off page opened the app, and that tap is already counted.\n *\n * Never throws.\n */\n static async trackLinkOpen(url: string): Promise<void> {\n // Unlike track, a missing instance is not worth throwing over: this sits on\n // the path that routes the user somewhere.\n if (!Tolinku.analyticsInstance) return;\n return Tolinku.analyticsInstance.trackLinkOpen(url, Tolinku._userId ?? undefined);\n }\n\n /**\n * Immediately flush all queued analytics and ecommerce events to the server.\n */\n static async flush(): Promise<void> {\n if (!Tolinku.analyticsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n await Promise.all([\n Tolinku.analyticsInstance.flush(),\n Tolinku.ecommerceInstance?.flush(),\n ]);\n }\n\n /** Ecommerce: track purchases, carts, products, revenue */\n static get ecommerce(): Ecommerce {\n if (!Tolinku.ecommerceInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.ecommerceInstance;\n }\n\n /** Referrals: create, complete, milestone, leaderboard, claimReward */\n static get referrals(): Referrals {\n if (!Tolinku.referralsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.referralsInstance;\n }\n\n /** Deferred deep links: claimByToken, claimBySignals */\n static get deferred(): Deferred {\n if (!Tolinku.deferredInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.deferredInstance;\n }\n\n /**\n * Turning a link the app was handed into the route and token it means.\n *\n * Needed for short links, which arrive as an opaque code that nothing on the\n * device can interpret. See {@link Links.resolve}.\n */\n static get links(): Links {\n if (!Tolinku.linksInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.linksInstance;\n }\n\n /**\n * Shut down the SDK and release resources.\n * Flushes remaining analytics events, cancels timers, removes listeners,\n * and aborts in-flight requests. After calling this, you must call init()\n * again before using the SDK.\n */\n static async destroy(): Promise<void> {\n debugLog('Tolinku SDK shutting down');\n\n // Flush and clean up analytics + ecommerce (timers, AppState listeners)\n if (Tolinku.analyticsInstance) {\n await Tolinku.analyticsInstance.destroy();\n }\n if (Tolinku.ecommerceInstance) {\n await Tolinku.ecommerceInstance.destroy();\n }\n\n // Abort all in-flight HTTP requests\n if (Tolinku.client) {\n Tolinku.client.abort();\n }\n\n // Reset storage namespace\n resetStorageNamespace();\n\n // Clear all references\n Tolinku.client = null;\n Tolinku.analyticsInstance = null;\n Tolinku.ecommerceInstance = null;\n Tolinku.referralsInstance = null;\n Tolinku.deferredInstance = null;\n Tolinku.linksInstance = null;\n Tolinku._initialized = false;\n Tolinku._userId = null;\n\n // Reset debug mode\n setDebugEnabled(false);\n }\n}\n","import React from 'react';\nimport {\n Text,\n View,\n Image,\n TouchableOpacity,\n ImageBackground,\n Linking,\n type TextStyle,\n type ViewStyle,\n type ImageStyle,\n} from 'react-native';\nimport type { MessageAppContext, MessageComponent, ShowMessageOptions } from '../types';\nimport { isSafeActionUrl, isSafeUrl } from '../validation';\nimport { debugWarn } from '../debug';\n\n/** The only two shapes React Native lays out: a number, or a percentage. */\ntype Size = number | `${number}%`;\n\n/** What an Image is given when it has neither a height nor a measurable one. */\nconst DEFAULT_IMAGE_HEIGHT: Size = 200;\n\n/**\n * Turn a dimension the message builder wrote into one React Native accepts.\n *\n * The builder's width and height are free text: \"100%\", \"200\", \"200px\" and\n * \"auto\" are all things it invites people to type. React Native takes a number\n * or a percentage string and nothing else, so \"200\" and \"200px\" are not sizes\n * to it, they are mistakes. A view given one lays out at zero, which for an\n * image means it renders and cannot be seen, with the rest of the message\n * looking perfectly fine around the hole.\n *\n * \"auto\" and anything unreadable return undefined, which callers read as \"no\n * opinion\" and size from the content instead.\n */\nexport function dimension(raw: unknown): Size | undefined {\n if (typeof raw === 'number' && isFinite(raw) && raw > 0) return raw;\n if (typeof raw !== 'string') return undefined;\n\n const value = raw.trim();\n if (!value) return undefined;\n if (value.endsWith('%')) {\n return /^\\d+(?:\\.\\d+)?%$/.test(value) ? (value as Size) : undefined;\n }\n\n // Only digits, with an optional px, are a size anyone meant. parseInt would\n // also read \"20rem\" as 20, which is not what was asked for.\n const match = /^(\\d+(?:\\.\\d+)?)(?:px)?$/i.exec(value);\n if (!match) {\n debugWarn(`Dimension \"${raw}\" is not a size React Native understands; ignoring it.`);\n return undefined;\n }\n const parsed = parseFloat(match[1]!);\n return parsed > 0 ? parsed : undefined;\n}\n\n/**\n * A number the author set, which may legitimately be zero.\n *\n * `props.x || fallback` throws away a deliberate 0, and 0 is exactly what an\n * author picks for a square corner or a flush edge. Every stock message\n * template sets borderRadius: 0 on its images, so the old form rounded the\n * corners of every one of them on device only.\n */\nexport function num(raw: unknown, fallback: number): number {\n if (typeof raw === 'number' && isFinite(raw)) return raw;\n if (typeof raw === 'string' && raw.trim()) {\n const parsed = parseFloat(raw);\n if (isFinite(parsed)) return parsed;\n }\n return fallback;\n}\n\n/** One of the alignments the builder offers, never whatever content carried. */\nfunction alignment(raw: unknown): TextStyle['textAlign'] {\n return raw === 'center' || raw === 'right' || raw === 'justify' ? raw : 'left';\n}\n\n/**\n * The colour names React Native knows, which it matches case sensitively.\n *\n * The builder's colour fields are free text in a browser, where names are\n * case insensitive and the set is larger, so this is where the two disagree.\n */\nconst NAMED_COLORS = new Set([\n 'transparent', 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque',\n 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',\n 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan',\n 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen',\n 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',\n 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue',\n 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia',\n 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey',\n 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush',\n 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow',\n 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',\n 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime',\n 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid',\n 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise',\n 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy',\n 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen',\n 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue',\n 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',\n 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey',\n 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet',\n 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen',\n]);\n\n/**\n * A colour React Native can actually parse, or the fallback.\n *\n * The builder's colour fields are free text with no picker, so a browser form\n * anything CSS accepts: `rgb(0 0 0 / 50%)`, `hsl(210 40% 98%)`, `color-mix()`,\n * `var(--brand)`. React Native understands a much smaller set and simply drops\n * what it cannot read, which for a button background means a white button with\n * a white label, an invisible call to action rather than an ugly one.\n */\nexport function color(raw: unknown, fallback: string): string {\n if (typeof raw !== 'string') return fallback;\n const value = raw.trim();\n if (!value) return fallback;\n\n if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) return value;\n // The comma forms only, and no percentage alpha: React Native understands\n // neither the CSS space syntax, rgb(0 0 0 / 50%), nor rgba(0,0,0,50%).\n if (/^(?:rgb|rgba|hsl|hsla)\\(\\s*[\\d.]+\\s*,[^)%]*\\)$/i.test(value)) return value;\n // Named colours, matched against the set React Native actually knows and\n // lowercased first. Its table is case sensitive, so an author who types\n // \"Red\", sees it in the browser preview and passes a case-insensitive check\n // gets nothing on the device: the exact silent failure this guards against.\n if (NAMED_COLORS.has(value.toLowerCase())) return value.toLowerCase();\n\n debugWarn(`Colour \"${raw}\" is not one React Native can read; using ${fallback}.`);\n return fallback;\n}\n\n/**\n * The \"soft\" button variant's tint.\n *\n * Only a hex colour can be tinted by appending an alpha, and a soft button\n * draws its label in the untinted colour. So when the tint cannot be applied,\n * the label and the background are the same colour and the button reads as an\n * empty block. Anything else falls back to filled, which is readable.\n */\nfunction softVariant(hex: string): string | null {\n if (/^#[0-9a-f]{6}$/i.test(hex)) return `${hex}22`;\n // A three digit hex has to be expanded first: \"#abc\" + \"22\" is five digits,\n // which is not a colour in any form, so the tint would be dropped and the\n // button would lose its background entirely.\n if (/^#[0-9a-f]{3}$/i.test(hex)) {\n const [, r, g, b] = hex;\n return `#${r}${r}${g}${g}${b}${b}22`;\n }\n return null;\n}\n\n/**\n * Render the [text](url) links the TextBlock field promises.\n *\n * The field label says \"Markdown links supported\" and the builder preview\n * draws them, so an author has every reason to believe they work. Only the\n * preview did: everywhere else the brackets and the raw URL were shown to the\n * end user as text.\n */\nfunction richText(text: string, onPressUrl: (url: string) => void): React.ReactNode {\n if (!text) return '';\n const regex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const parts: React.ReactNode[] = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n let key = 0;\n\n while ((match = regex.exec(text)) !== null) {\n if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index));\n const [full, label, rawUrl] = match;\n const url = (rawUrl || '').trim();\n if (isSafeActionUrl(url)) {\n parts.push(\n <Text\n key={`link-${key++}`}\n style={{ textDecorationLine: 'underline' }}\n onPress={() => onPressUrl(url)}\n >\n {label}\n </Text>,\n );\n } else {\n parts.push(full);\n }\n lastIndex = regex.lastIndex;\n }\n if (lastIndex < text.length) parts.push(text.slice(lastIndex));\n return parts.length === 1 ? parts[0] : parts;\n}\n\n/**\n * The proportions of a remote image, once the platform can tell us.\n *\n * React Native cannot know them without asking, and asking is asynchronous, so\n * a caller gets null until the answer arrives and lays out from a fallback in\n * the meantime. `enabled` exists because measuring costs a request and is\n * pointless when the size is already known.\n */\nfunction useImageRatio(uri: string, enabled: boolean): number | null {\n const [ratio, setRatio] = React.useState<number | null>(null);\n\n React.useEffect(() => {\n if (!enabled || !uri) return;\n let cancelled = false;\n Image.getSize(\n uri,\n (w, h) => {\n // Guarded so a slow answer cannot set state on an unmounted message,\n // which is a warning in development and a leak in production.\n if (!cancelled && w > 0 && h > 0) setRatio(w / h);\n },\n () => {\n // Unreachable, or something the platform cannot measure. Callers fall\n // back rather than render nothing.\n },\n );\n return () => {\n cancelled = true;\n };\n }, [uri, enabled]);\n\n return ratio;\n}\n\n/**\n * An image sized the way the builder means it.\n *\n * A height left empty means natural proportions, not a fixed box. Picking a\n * number instead is how a 44px icon ends up as a 44 by 200 strip with its\n * middle cropped out, which is what every template icon looked like.\n */\nfunction MessageImage({\n uri,\n width,\n height,\n borderRadius,\n borderWidth,\n borderColor,\n alt,\n}: {\n uri: string;\n width: Size | undefined;\n height: Size | undefined;\n borderRadius: number;\n borderWidth: number;\n borderColor: string;\n alt: string;\n}): React.ReactElement {\n const wantsNaturalHeight = height === undefined;\n const ratio = useImageRatio(uri, wantsNaturalHeight);\n\n const style: ImageStyle = {\n width: width ?? '100%',\n borderRadius,\n alignSelf: 'center',\n marginBottom: 8,\n ...(borderWidth > 0 ? { borderWidth, borderColor } : {}),\n ...(wantsNaturalHeight\n ? ratio\n ? { aspectRatio: ratio }\n : { height: DEFAULT_IMAGE_HEIGHT }\n : { height }),\n };\n\n return (\n <Image\n source={{ uri }}\n style={style}\n // Contain while the proportions are still unknown, so a measurement that\n // never arrives leaves the picture whole rather than cropped.\n resizeMode={wantsNaturalHeight && !ratio ? 'contain' : 'cover'}\n accessibilityLabel={alt}\n />\n );\n}\n\n/**\n * One store badge, at the height the author asked for.\n *\n * A remote image in React Native needs both dimensions, so the width comes\n * from the badge's own proportions rather than a number written here. Apple's\n * and Google's artwork are close but not identical (3.47 against 3.46), and\n * either way a guess shows as a badge slightly shorter than asked for, since\n * \"contain\" shrinks it to fit whatever box it is given.\n */\nfunction StoreBadge({\n uri,\n height,\n label,\n onPress,\n}: {\n uri: string | undefined;\n height: number;\n label: string;\n onPress: () => void;\n}): React.ReactElement {\n const usable = !!uri && isSafeUrl(uri);\n const ratio = useImageRatio(usable ? uri! : '', usable);\n // A badge is artwork, not a layout choice: a height of zero is not a smaller\n // badge, it is no badge, so the authored value is floored rather than obeyed.\n const usableHeight = height > 0 ? height : 44;\n\n return (\n <TouchableOpacity onPress={onPress} activeOpacity={0.7} accessibilityRole=\"button\">\n {usable ? (\n <Image\n source={{ uri: uri! }}\n // Until measured, a badge-shaped box. Both stores' artwork is within\n // a percent of this, so the correction on arrival is imperceptible.\n style={{ height: usableHeight, width: usableHeight * (ratio || 3.47), marginHorizontal: 6 }}\n resizeMode=\"contain\"\n accessibilityLabel={label}\n />\n ) : (\n // A text link rather than a blank space, for the case where the badge\n // artwork itself cannot be loaded.\n <Text style={{ color: '#1B1B1B', fontSize: 15, fontWeight: '600', marginHorizontal: 6 }}>{label}</Text>\n )}\n </TouchableOpacity>\n );\n}\n\n/** The component types this renderer draws. */\nconst SUPPORTED = new Set([\n 'Heading',\n 'TextBlock',\n 'Image',\n 'Button',\n 'DeepLinkButton',\n 'Section',\n 'Spacer',\n 'Divider',\n 'AppIcon',\n 'StoreButtons',\n]);\n\n/**\n * Whether anything in this content would actually draw.\n *\n * A message saved before the builder's palette was narrowed can be made\n * entirely of components this renderer skips, and skipping all of them leaves\n * an empty card with a close button. Asking first lets the message fall back\n * to its title and body instead.\n */\nexport function drawsAnything(\n content: MessageComponent[] | undefined,\n app?: MessageAppContext | null,\n): boolean {\n return (content || []).some(c => {\n if (!c || !SUPPORTED.has(c.type)) return false;\n const props = (c.props || {}) as Record<string, unknown>;\n // A few components draw only when something outside the content exists.\n // Counting them regardless is how an empty card came back.\n if (c.type === 'Image') return isSafeUrl((props.url as string) || '');\n if (c.type === 'DeepLinkButton') return !!app?.deep_link_url;\n if (c.type === 'StoreButtons') {\n const ios = props.showIos !== false && ((props.iosUrlOverride as string) || app?.ios_store_url);\n const android = props.showAndroid !== false && ((props.androidUrlOverride as string) || app?.android_store_url);\n return !!(ios || android);\n }\n return true;\n });\n}\n\n/**\n * How deep a section may nest before the renderer stops following zones.\n *\n * A zone can name a section that contains itself, directly or through another.\n * React's work loop is iterative, so that is not a stack overflow: it is an\n * app that allocates until it is killed, with no error and nothing on screen.\n * Content saved before any of this was validated can be shaped that way, so\n * the renderer refuses to follow it forever rather than trusting what it is\n * handed.\n */\nconst MAX_SECTION_DEPTH = 20;\n\nexport interface RenderOptions extends ShowMessageOptions {\n /** Section children, keyed \"<component id>:content\", as Puck stores them. */\n zones?: Record<string, MessageComponent[]>;\n /** The app the message belongs to, for the components that describe it. */\n app?: MessageAppContext | null;\n /** Dismiss the message. A button action of \"close\" calls this. */\n onRequestClose?: () => void;\n /** How many sections deep this render already is. Internal. */\n depth?: number;\n}\n\ninterface ComponentRendererProps {\n component: MessageComponent;\n messageId: string;\n options: RenderOptions;\n}\n\nexport function PuckComponentRenderer({ component, messageId, options }: ComponentRendererProps): React.ReactElement | null {\n // Content is a network response, not something this package produced, so a\n // malformed entry is skipped rather than allowed to throw mid-render. There\n // is no error boundary in a host app: a throw here is a blank screen.\n if (!component || typeof component !== 'object' || typeof component.type !== 'string') return null;\n const props = component.props && typeof component.props === 'object' ? component.props : {};\n const app = options.app;\n\n /** Open a URL the way the host app asked us to, or the way the OS would. */\n const follow = (url: string) => {\n if (options.onButtonPress) options.onButtonPress(url, messageId);\n else Linking.openURL(url).catch(() => {});\n };\n\n switch (component.type) {\n case 'Heading': {\n const fontSize = num(props.fontSize, 28);\n const style: TextStyle = {\n fontSize,\n fontWeight: '700',\n color: color(props.color, '#1B1B1B'),\n textAlign: alignment(props.alignment),\n lineHeight: fontSize * 1.2,\n marginBottom: 8,\n };\n return <Text style={style}>{(props.text as string) || ''}</Text>;\n }\n\n case 'TextBlock': {\n const fontSize = num(props.fontSize, 15);\n const style: TextStyle = {\n fontSize,\n color: color(props.color, '#555555'),\n textAlign: alignment(props.alignment),\n lineHeight: fontSize * 1.5,\n marginBottom: 8,\n };\n return <Text style={style}>{richText((props.content as string) || '', follow)}</Text>;\n }\n\n case 'Image': {\n const imageUrl = (props.url as string) || '';\n\n if (!imageUrl || !imageUrl.trim()) {\n debugWarn('Image component has empty URL, skipping render.');\n return null;\n }\n if (!isSafeUrl(imageUrl)) {\n debugWarn(`Image URL blocked (unsafe protocol): ${imageUrl}`);\n return null;\n }\n\n return (\n <MessageImage\n uri={imageUrl}\n width={dimension(props.width) ?? '100%'}\n height={dimension(props.height)}\n borderRadius={num(props.borderRadius, 8)}\n borderWidth={num(props.borderWidth, 0)}\n borderColor={color(props.borderColor, '#1B1B1B')}\n alt={(props.alt as string) || ''}\n />\n );\n }\n\n case 'Button':\n case 'DeepLinkButton': {\n const isDeepLink = component.type === 'DeepLinkButton';\n // A deep link button opens the app's own link, which the message content\n // has no way to know; it comes with the app context.\n const action = isDeepLink ? app?.deep_link_url || '' : (props.action as string) || '';\n const label = isDeepLink\n ? (props.label as string) || 'Open in App'\n : (props.label as string) || '';\n\n // A deep link button with nowhere to point is a dead control, so it is\n // left out rather than drawn.\n if (isDeepLink && !action) return null;\n\n const handlePress = () => {\n if (!action) return;\n\n // \"close\" is an action the builder offers and the WebView renderer has\n // always honoured. Here it used to fail the URL check and do nothing,\n // so a dismiss button left the message on screen.\n if (action === 'close') {\n options.onRequestClose?.();\n return;\n }\n\n // Checked before either path, including the caller's own handler. The\n // URL comes from message content, and a handler is ordinary app code\n // that will reasonably pass it to Linking.openURL without looking.\n if (!isSafeActionUrl(action)) {\n debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);\n return;\n }\n\n follow(action);\n };\n\n const variant = (props.style as string) || 'filled';\n const isOutline = variant === 'outline';\n const tint = variant === 'soft' ? softVariant(color(props.bgColor, '#1B1B1B')) : null;\n const isSoft = tint !== null;\n const baseColor = color(props.bgColor, '#1B1B1B');\n const background = isOutline ? 'transparent' : isSoft ? tint! : baseColor;\n const labelColor = isOutline || isSoft ? baseColor : color(props.textColor, '#ffffff');\n\n const containerStyle: ViewStyle = {\n backgroundColor: background,\n borderRadius: num(props.borderRadius, 8),\n paddingVertical: 12,\n paddingHorizontal: 24,\n marginVertical: 8,\n alignItems: 'center',\n ...(isOutline ? { borderWidth: 2, borderColor: baseColor } : {}),\n // A button that is not full width is a compact, centred one. Without\n // alignSelf it stretches to the column anyway, which made the setting\n // do nothing at all.\n ...(props.fullWidth ? { width: '100%' as const } : { alignSelf: 'center' as const }),\n };\n\n const textStyle: TextStyle = {\n color: labelColor,\n fontSize: num(props.fontSize, 16),\n fontWeight: '600',\n };\n\n const emoji = (props.emoji as string) || '';\n\n return (\n <TouchableOpacity onPress={handlePress} style={containerStyle} activeOpacity={0.7}>\n <Text style={textStyle}>{emoji ? `${emoji} ${label}` : label}</Text>\n </TouchableOpacity>\n );\n }\n\n case 'Section': {\n // Puck stores a drop zone's children under \"<component id>:content\" at\n // the top level of the content, never in props.children. Reading\n // props.children rendered every Section as an empty box and lost\n // everything an author put inside it.\n // An id-less section would read the literal key \"undefined:content\" and\n // share its children with every other id-less section in the message.\n const sectionId = typeof props.id === 'string' && props.id ? props.id : null;\n const depth = options.depth || 0;\n const children =\n sectionId && depth < MAX_SECTION_DEPTH ? options.zones?.[`${sectionId}:content`] || [] : [];\n\n const containerStyle: ViewStyle = {\n backgroundColor: typeof props.bgColor === 'string' && props.bgColor\n ? color(props.bgColor, 'transparent')\n : undefined,\n padding: num(props.padding, 16),\n borderRadius: num(props.borderRadius, 0),\n marginVertical: 8,\n };\n\n const content = children.map((child, index) => (\n <PuckComponentRenderer\n key={`${messageId}-section-${index}-${child?.type}`}\n component={child}\n messageId={messageId}\n options={{ ...options, depth: depth + 1 }}\n />\n ));\n\n const bgImage = (props.bgImage as string) || '';\n if (bgImage) {\n if (!isSafeUrl(bgImage)) {\n debugWarn(`Section background image URL blocked (unsafe protocol): ${bgImage}`);\n return <View style={containerStyle}>{content}</View>;\n }\n\n return (\n <ImageBackground\n source={{ uri: bgImage }}\n style={containerStyle}\n resizeMode={(props.bgSize as string) === 'contain' ? 'contain' : 'cover'}\n imageStyle={{ borderRadius: num(props.borderRadius, 0) }}\n >\n {content}\n </ImageBackground>\n );\n }\n\n return <View style={containerStyle}>{content}</View>;\n }\n\n case 'Spacer':\n return <View style={{ height: num(props.height, 24) }} />;\n\n case 'Divider':\n return (\n <View\n style={{\n borderTopWidth: num(props.thickness, 1),\n borderTopColor: color(props.color, '#e5e5e5'),\n marginVertical: 8,\n }}\n />\n );\n\n case 'AppIcon': {\n const size = num(props.size, 80);\n const borderRadius = num(props.borderRadius, 16);\n const iconUrl = app?.icon_url || '';\n\n // A placeholder rather than a hole. The author put an icon here, and an\n // app with no logo set is a setting to fix, not a reason to render a\n // message with a gap in it.\n if (!iconUrl || !isSafeUrl(iconUrl)) {\n return (\n <View\n style={{ width: size, height: size, borderRadius, backgroundColor: '#f0f0f0', alignSelf: 'center', marginBottom: 8 }}\n />\n );\n }\n\n return (\n <Image\n source={{ uri: iconUrl }}\n style={{ width: size, height: size, borderRadius, alignSelf: 'center', marginBottom: 8 }}\n resizeMode=\"cover\"\n accessibilityLabel={app?.name || 'App icon'}\n />\n );\n }\n\n case 'StoreButtons': {\n const iosUrl = (props.iosUrlOverride as string) || app?.ios_store_url || '';\n const androidUrl = (props.androidUrlOverride as string) || app?.android_store_url || '';\n const showIos = props.showIos !== false && !!iosUrl;\n const showAndroid = props.showAndroid !== false && !!androidUrl;\n if (!showIos && !showAndroid) return null;\n\n const height = num(props.height, 44);\n const alignment = props.alignment as string;\n const justifyContent =\n alignment === 'left' ? 'flex-start' : alignment === 'right' ? 'flex-end' : 'center';\n\n // The badges are the official artwork, sent with the app context so the\n // SDK is not guessing an origin or a file name.\n return (\n <View style={{ flexDirection: 'row', justifyContent, alignItems: 'center', flexWrap: 'wrap', marginVertical: 8 }}>\n {showIos ? (\n <StoreBadge\n key=\"ios\"\n uri={app?.ios_badge_url}\n height={height}\n label=\"Download on the App Store\"\n onPress={() => follow(iosUrl)}\n />\n ) : null}\n {showAndroid ? (\n <StoreBadge\n key=\"android\"\n uri={app?.android_badge_url}\n height={height}\n label=\"Get it on Google Play\"\n onPress={() => follow(androidUrl)}\n />\n ) : null}\n </View>\n );\n }\n\n default:\n debugWarn(`Message component \"${component.type}\" is not supported here; skipping it.`);\n return null;\n }\n}\n","import React from 'react';\nimport {\n Modal,\n View,\n TouchableOpacity,\n Pressable,\n ScrollView,\n Text,\n StyleSheet,\n} from 'react-native';\nimport type { Message, MessageAppContext, ShowMessageOptions } from '../types';\nimport { saveMessageDismissal } from '../storage';\nimport { PuckComponentRenderer, color, num, drawsAnything } from './components';\n\ninterface MessageModalProps {\n message: Message | null;\n visible: boolean;\n onClose: () => void;\n options: ShowMessageOptions;\n app?: MessageAppContext | null;\n}\n\n/**\n * The colour a gradient starts with.\n *\n * React Native has no gradient without a native module this package will not\n * pull in, and five of the stock message templates are designed on one. Left\n * alone they arrive as a plain white card. The first stop is a much closer\n * likeness than white, so the message still looks like the thing that was\n * designed.\n */\nfunction gradientStartColor(gradient: unknown): string | null {\n if (typeof gradient !== 'string' || !gradient) return null;\n const match = /#[0-9a-f]{3,8}|rgba?\\([^)]*\\)/i.exec(gradient);\n if (!match) return null;\n // Checked like any other colour: the pattern above will happily match a\n // five digit hex or the space syntax, both of which React Native drops,\n // leaving a card with no background at all.\n const validated = color(match[0], '');\n return validated || null;\n}\n\nexport function MessageModal({ message, visible, onClose, options, app }: MessageModalProps): React.ReactElement {\n if (!message) {\n return <></>;\n }\n\n const handleDismiss = async () => {\n await saveMessageDismissal(message.id);\n options.onDismiss?.(message.id);\n onClose();\n };\n\n const rootProps = (message.content?.root?.props || {}) as Record<string, unknown>;\n\n // Root background: what the author set on the message surface, then the\n // message's own colour field, then white. All of it was ignored before, so a\n // message designed on a gradient arrived as a plain white card.\n // The gradient wins over the colour, which is what CSS does for the same\n // pair and therefore what the preview and the WebView show. It matters\n // because the builder writes bgColor: '#ffffff' into every saved root, so\n // reading the colour first meant a gradient message was always white here.\n const background =\n gradientStartColor(rootProps.bgGradient) ||\n (typeof rootProps.bgColor === 'string' && rootProps.bgColor ? color(rootProps.bgColor, '') : '') ||\n message.background_color ||\n '#ffffff';\n\n const cardStyle = {\n backgroundColor: background,\n padding: Math.max(0, num(rootProps.padding, 20)),\n // Clamped, unlike the other authored numbers. A padding of zero is a\n // choice; a width of zero is the whole message gone, and the field's own\n // minimum is zero. The bounds and the default match the server renderer.\n maxWidth: Math.min(2000, Math.max(100, num(rootProps.contentWidth, 480))),\n };\n\n const content = message.content?.content || [];\n\n // A message may carry only a title and a body, with nothing designed in the\n // builder at all, and one saved before the palette was narrowed may be made\n // entirely of components this renderer skips. Either way the card used to\n // come up empty but for its close button.\n const hasDesignedContent = drawsAnything(content, app);\n\n return (\n <Modal\n visible={visible}\n transparent\n animationType=\"fade\"\n onRequestClose={handleDismiss}\n >\n <Pressable style={styles.overlay} onPress={handleDismiss}>\n <Pressable style={[styles.card, cardStyle]} onPress={() => {}}>\n <TouchableOpacity\n onPress={handleDismiss}\n style={styles.closeButton}\n accessibilityLabel=\"Close message\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeText}>{'\\u00d7'}</Text>\n </TouchableOpacity>\n\n <ScrollView\n style={styles.scrollContent}\n showsVerticalScrollIndicator={false}\n >\n {hasDesignedContent ? (\n content.map((component, index) => (\n <PuckComponentRenderer\n key={`${message.id}-${index}-${component.type}`}\n component={component}\n messageId={message.id}\n options={{\n ...options,\n zones: message.content?.zones,\n app,\n onRequestClose: handleDismiss,\n }}\n />\n ))\n ) : (\n <>\n {message.title ? <Text style={styles.fallbackTitle}>{message.title}</Text> : null}\n {message.body ? <Text style={styles.fallbackBody}>{message.body}</Text> : null}\n </>\n )}\n </ScrollView>\n </Pressable>\n </Pressable>\n </Modal>\n );\n}\n\nconst styles = StyleSheet.create({\n overlay: {\n flex: 1,\n backgroundColor: 'rgba(0,0,0,0.5)',\n alignItems: 'center',\n justifyContent: 'center',\n },\n card: {\n position: 'relative',\n width: '90%',\n maxHeight: '80%',\n borderRadius: 16,\n shadowColor: '#000',\n shadowOffset: { width: 0, height: 20 },\n shadowOpacity: 0.3,\n shadowRadius: 30,\n elevation: 10,\n },\n closeButton: {\n position: 'absolute',\n top: 12,\n right: 12,\n zIndex: 10,\n backgroundColor: 'rgba(0,0,0,0.1)',\n borderRadius: 14,\n width: 28,\n height: 28,\n alignItems: 'center',\n justifyContent: 'center',\n },\n closeText: {\n fontSize: 18,\n lineHeight: 20,\n opacity: 0.6,\n },\n scrollContent: {\n marginTop: 8,\n },\n // Used only when a message has no designed content, so its title and body\n // are all there is to show.\n fallbackTitle: {\n fontSize: 20,\n fontWeight: '700',\n color: '#1B1B1B',\n marginBottom: 8,\n },\n fallbackBody: {\n fontSize: 15,\n lineHeight: 22,\n color: '#555555',\n },\n});\n","import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react';\nimport type { Message, MessageAppContext, ShowMessageOptions } from '../types';\nimport { isMessageDismissed, isMessageSuppressed, recordMessageImpression } from '../storage';\nimport { MessageModal } from './MessageModal';\nimport { Tolinku } from '../Tolinku';\nimport { debugWarn } from '../debug';\n\ninterface TolinkuMessagesProps {\n /** The trigger type to filter messages by (e.g. \"milestone\", \"event\") */\n trigger?: string;\n /** The trigger value to match (e.g. \"installed\", \"first_purchase\") */\n triggerValue?: string;\n /** Called when a message is dismissed */\n onDismiss?: (messageId: string) => void;\n /** Called when a button in the message is pressed */\n onButtonPress?: (action: string, messageId: string) => void;\n}\n\n/**\n * React component that fetches and displays in-app messages as a modal overlay.\n *\n * Place this component anywhere in your component tree. It will automatically\n * fetch messages matching the given trigger and display the highest-priority\n * non-dismissed message.\n *\n * Example:\n * <TolinkuMessages trigger=\"milestone\" triggerValue=\"installed\" />\n */\nexport function TolinkuMessages({\n trigger,\n triggerValue,\n onDismiss,\n onButtonPress,\n}: TolinkuMessagesProps): React.ReactElement {\n const [message, setMessage] = useState<Message | null>(null);\n const [visible, setVisible] = useState(false);\n // Sent alongside the messages: AppIcon, StoreButtons and DeepLinkButton\n // describe the app rather than the message, so the content cannot draw them.\n const [app, setApp] = useState<MessageAppContext | null>(null);\n\n // Stabilize callback refs so they don't trigger re-fetches\n const onDismissRef = useRef(onDismiss);\n onDismissRef.current = onDismiss;\n const onButtonPressRef = useRef(onButtonPress);\n onButtonPressRef.current = onButtonPress;\n\n // Memoize the options object to avoid unnecessary re-renders\n const options: ShowMessageOptions = useMemo(() => ({\n trigger,\n triggerValue,\n onDismiss: (messageId: string) => onDismissRef.current?.(messageId),\n onButtonPress: (action: string, messageId: string) => onButtonPressRef.current?.(action, messageId),\n }), [trigger, triggerValue]);\n\n useEffect(() => {\n let cancelled = false;\n\n async function fetchMessages() {\n try {\n const client = Tolinku.getClient();\n const params: Record<string, string> = {};\n if (trigger) params.trigger = trigger;\n const userId = Tolinku.getUserId();\n if (userId) params.user_id = userId;\n\n const data = await client.get<{ messages: Message[]; app?: MessageAppContext }>('/v1/api/messages', params);\n if (cancelled) return;\n // Kept whether or not a message ends up shown: it belongs to the app,\n // not to any one message.\n if (data.app) setApp(data.app);\n if (!data.messages || data.messages.length === 0) return;\n\n // Filter dismissed/suppressed messages and optionally by triggerValue\n const candidates: Message[] = [];\n for (const m of data.messages) {\n if (triggerValue && m.trigger_value !== triggerValue) continue;\n const dismissed = await isMessageDismissed(m.id, m.dismiss_days);\n if (dismissed) continue;\n const suppressed = await isMessageSuppressed(m.id, m.max_impressions, m.min_interval_hours);\n if (!suppressed) candidates.push(m);\n }\n\n // Sort by priority (highest first)\n candidates.sort((a, b) => b.priority - a.priority);\n\n if (candidates.length > 0 && !cancelled) {\n await recordMessageImpression(candidates[0].id);\n setMessage(candidates[0]);\n setVisible(true);\n }\n } catch (err) {\n debugWarn(`Failed to fetch messages: ${(err as Error).message}`);\n }\n }\n\n fetchMessages();\n\n return () => {\n cancelled = true;\n };\n }, [trigger, triggerValue]);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n setMessage(null);\n }, []);\n\n return (\n <MessageModal\n message={message}\n visible={visible}\n onClose={handleClose}\n options={options}\n app={app}\n />\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/debug.ts","../src/client.ts","../src/validation.ts","../src/analytics.ts","../src/ecommerce.ts","../src/referrals.ts","../src/install-referrer.ts","../src/deferred.ts","../src/links.ts","../src/storage.ts","../src/Tolinku.ts","../src/messages/components.tsx","../src/messages/MessageModal.tsx","../src/messages/MessageProvider.tsx"],"names":["AppState","Platform","BATCH_SIZE","FLUSH_INTERVAL_MS","MAX_QUEUE_SIZE","AsyncStorage","NativeModules","Dimensions","PixelRatio","Linking","jsx","Text","React","Image","TouchableOpacity","View","ImageBackground","alignment","jsxs","Fragment","Modal","Pressable","ScrollView","StyleSheet","useState","useRef","useMemo","useEffect","useCallback"],"mappings":";;;;;;;;;;;;;;;AACO,IAAM,WAAA,GAAc,OAAA;;;ACA3B,IAAI,aAAA,GAAgB,KAAA;AAEb,SAAS,gBAAgB,OAAA,EAAwB;AACtD,EAAA,aAAA,GAAgB,OAAA;AAClB;AAOO,SAAS,SAAS,OAAA,EAAuB;AAC9C,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAE,CAAA;AAAA,EACvC;AACF;AAGO,SAAS,UAAU,OAAA,EAAuB;AAC/C,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAE,CAAA;AAAA,EACxC;AACF;;;AClBA,IAAM,WAAA,GAAc,CAAA;AAEpB,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,aAAA,GAAgB,GAAA;AAetB,SAAS,aAAa,GAAA,EAAuB;AAC3C,EAAA,OACE,OAAO,GAAA,KAAQ,QAAA,IACf,GAAA,KAAQ,IAAA,IACP,IAA2B,IAAA,KAAS,YAAA;AAEzC;AAEO,IAAM,aAAN,MAAiB;AAAA,EAStB,YAAY,MAAA,EAA+B;AAH3C;AAAA,IAAA,IAAA,CAAQ,kBAAA,uBAA+C,GAAA,EAAI;AAC3D,IAAA,IAAA,CAAQ,SAAA,GAAY,KAAA;AAGlB,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAChD,IAAA,IAAA,CAAK,SAAS,MAAA,CAAO,MAAA;AACrB,IAAA,IAAA,CAAK,UAAU,MAAA,CAAO,OAAA;AAAA,EACxB;AAAA,EAEA,MAAM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MACA;AAAA;AAAA,GACF;AAEJ","file":"index.js","sourcesContent":["/** SDK version */\nexport const SDK_VERSION = '0.8.1';\n\n/** Configuration options for the Tolinku SDK */\nexport interface TolinkuConfig {\n /** Your Tolinku publishable API key (starts with tolk_pub_) */\n apiKey: string;\n /** Base URL of your Tolinku domain. Defaults to https://api.tolinku.com */\n baseUrl?: string;\n /** Enable debug logging to the console. Defaults to false. */\n debug?: boolean;\n /** Request timeout in milliseconds. Defaults to 30000 (30 seconds). */\n timeout?: number;\n /**\n * Report incoming links automatically, instead of calling trackLinkOpen by\n * hand. Defaults to false.\n *\n * Off by default because a reported open is billed as a click. Turning this\n * on by upgrading would raise somebody's bill without them asking, so it is\n * a decision the app makes rather than one a release makes for it.\n *\n * Covers both ways a link arrives on React Native, the cold start and the\n * listener, which is the pair that is easy to get half right by hand. It does\n * not cover the open after a deferred install: only your app knows that it\n * just claimed a link, so that one is still reported explicitly.\n */\n autoTrackLinkOpens?: boolean;\n}\n\n/** Resolved configuration with all defaults applied */\nexport interface ResolvedTolinkuConfig {\n apiKey: string;\n baseUrl: string;\n debug: boolean;\n timeout: number;\n}\n\n/** Properties for custom event tracking */\nexport interface TrackProperties {\n campaign?: string;\n source?: string;\n medium?: string;\n platform?: string;\n [key: string]: string | undefined;\n}\n\n/** Options for creating a referral */\nexport interface CreateReferralOptions {\n userId: string;\n metadata?: Record<string, string>;\n userName?: string;\n}\n\n/** Response from creating a referral */\nexport interface CreateReferralResult {\n referral_code: string;\n referral_url: string | null;\n referral_id: string;\n}\n\n/** Options for completing a referral */\nexport interface CompleteReferralOptions {\n code: string;\n referredUserId: string;\n milestone?: string;\n referredUserName?: string;\n}\n\n/** Response from completing a referral */\nexport interface CompleteReferralResult {\n referral: {\n id: string;\n referrer_id: string;\n referred_user_id: string;\n status: string;\n milestone: string;\n completed_at: string;\n reward_type: string | null;\n reward_value: string | null;\n };\n}\n\n/** Options for updating a referral milestone */\nexport interface MilestoneOptions {\n code: string;\n milestone: string;\n}\n\n/** Response from updating a milestone */\nexport interface MilestoneResult {\n referral: {\n id: string;\n referral_code: string;\n milestone: string;\n status: string;\n reward_type: string | null;\n reward_value: string | null;\n };\n}\n\n/** Referral info returned by GET /api/referral/:code */\nexport interface ReferralInfo {\n referrer_id: string;\n status: string;\n milestone: string;\n milestone_history: Array<{ milestone: string; timestamp: string }>;\n reward_type: string | null;\n reward_value: string | null;\n reward_claimed: boolean;\n created_at: string;\n}\n\n/** Leaderboard entry */\nexport interface LeaderboardEntry {\n referrer_id: string;\n referrer_name: string | null;\n total: number;\n completed: number;\n pending: number;\n total_reward_value: string | null;\n}\n\n/** Deferred deep link result */\nexport interface DeferredLink {\n deep_link_path: string;\n appspace_id: string;\n /**\n * The absolute URL for this link, for reporting the open that follows.\n *\n * Reporting an open needs the whole URL, not the path: the host is how the\n * server finds the Appspace and the only thing proving the link belongs to\n * it, and the device has no way to know it. Absent from servers older than\n * this field, so treat it as optional.\n */\n url?: string;\n referrer_id?: string;\n referral_code?: string;\n}\n\n/**\n * What a Tolinku link turned out to mean.\n *\n * The same shape in every SDK, so an app moving between them reads one thing.\n * The Appspace the link belongs to is deliberately not here: the app already\n * knows which Appspace it is, and nothing about routing a link needs it.\n */\nexport interface ResolvedLink {\n /** The route that answers this link. */\n route: {\n prefix: string;\n name: string;\n template: string;\n link_type?: string;\n };\n /** The token the link carried, or '' where it carried none. */\n token: string;\n /** The canonical path, with the token wherever the route's prefix puts it. */\n deep_link_path: string;\n}\n\n/** Options for claiming deferred link by signals */\nexport interface ClaimBySignalsOptions {\n appspaceId: string;\n timezone?: string;\n language?: string;\n screenWidth?: number;\n screenHeight?: number;\n /** Defaults to `PixelRatio.get()`. Override only if you report a custom screen size. */\n devicePixelRatio?: number;\n /** Defaults to `Platform.Version`. Compared on the major component only. */\n osVersion?: string;\n}\n\n/** In-app message from the API */\nexport interface Message {\n id: string;\n name: string;\n title: string;\n body: string | null;\n trigger: string;\n trigger_value: string | null;\n content: MessageContent | null;\n background_color: string;\n priority: number;\n dismiss_days: number | null;\n max_impressions: number | null;\n min_interval_hours: number | null;\n}\n\n/** Puck component content tree */\nexport interface MessageContent {\n root: { props: Record<string, unknown> };\n content: MessageComponent[];\n /**\n * A Section's children, keyed \"<component id>:content\".\n *\n * Puck keeps nested content here rather than on the parent's props, so a\n * renderer that reads props.children finds nothing and draws every Section\n * as an empty box. This was missing from the type entirely, which is part of\n * how that went unnoticed.\n */\n zones?: Record<string, MessageComponent[]>;\n}\n\n/**\n * The app a message belongs to, sent alongside it.\n *\n * AppIcon, StoreButtons and DeepLinkButton describe the app rather than the\n * message, so the content has nothing to draw them from.\n */\nexport interface MessageAppContext {\n name: string;\n icon_url: string | null;\n ios_store_url: string | null;\n android_store_url: string | null;\n deep_link_url: string | null;\n ios_badge_url: string;\n android_badge_url: string;\n}\n\n/** A single Puck component */\nexport interface MessageComponent {\n type: string;\n props: Record<string, unknown>;\n}\n\n/** Options for showing an in-app message */\nexport interface ShowMessageOptions {\n trigger?: string;\n triggerValue?: string;\n onDismiss?: (messageId: string) => void;\n onButtonPress?: (action: string, messageId: string) => void;\n}\n\n// ─── Ecommerce Types ─────────────────────────────────────\n\nexport interface EcommerceItem {\n item_id: string;\n item_name?: string;\n item_category?: string;\n item_brand?: string;\n item_variant?: string;\n item_list_name?: string;\n item_list_id?: string;\n item_image_url?: string;\n price?: number;\n quantity?: number;\n currency?: string;\n coupon_code?: string;\n discount?: number;\n}\n\nexport interface PurchaseParams {\n transaction_id: string;\n revenue: number;\n currency: string;\n items?: EcommerceItem[];\n cart_id?: string;\n coupon_code?: string;\n discount?: number;\n shipping?: number;\n tax?: number;\n}\n\nexport interface AddToCartParams {\n items: EcommerceItem[];\n cart_id?: string;\n}\n\nexport interface RemoveFromCartParams {\n items: EcommerceItem[];\n cart_id?: string;\n}\n\nexport interface AddToWishlistParams {\n items: EcommerceItem[];\n}\n\nexport interface BeginCheckoutParams {\n revenue?: number;\n currency?: string;\n cart_id?: string;\n items?: EcommerceItem[];\n}\n\nexport interface RefundParams {\n transaction_id: string;\n revenue: number;\n currency?: string;\n items?: EcommerceItem[];\n}\n\nexport interface ViewItemParams {\n items: EcommerceItem[];\n}\n\nexport interface SearchParams {\n search_term: string;\n}\n\nexport interface AddPaymentInfoParams {\n cart_id?: string;\n}\n\nexport interface ShareParams {\n item_id?: string;\n url?: string;\n method?: string;\n}\n\nexport interface RateParams {\n item_id: string;\n rating: number;\n max_rating?: number;\n}\n\nexport interface SpendCreditsParams {\n revenue: number;\n currency: string;\n}\n","/** Global debug flag, controlled by Tolinku.init({ debug: true }) */\nlet _debugEnabled = false;\n\nexport function setDebugEnabled(enabled: boolean): void {\n _debugEnabled = enabled;\n}\n\nexport function isDebugEnabled(): boolean {\n return _debugEnabled;\n}\n\n/** Log a message to the console if debug mode is enabled. */\nexport function debugLog(message: string): void {\n if (_debugEnabled) {\n console.log(`[TolinkuSDK] ${message}`);\n }\n}\n\n/** Log a warning to the console if debug mode is enabled. */\nexport function debugWarn(message: string): void {\n if (_debugEnabled) {\n console.warn(`[TolinkuSDK] ${message}`);\n }\n}\n","import type { ResolvedTolinkuConfig } from './types';\nimport { SDK_VERSION } from './types';\nimport { debugLog } from './debug';\n\n/** Maximum number of retry attempts after the initial request. */\nconst MAX_RETRIES = 3;\n/** Base delay in milliseconds before the first retry. */\nconst BASE_DELAY_MS = 500;\n/** Maximum random jitter added to each retry delay, in milliseconds. */\nconst MAX_JITTER_MS = 250;\n\n/**\n * Whether a caught value is an abort, from either the timeout or destroy().\n *\n * Read off the name rather than tested with `instanceof DOMException`. React\n * Native has no DOM, so whether `DOMException` exists as a global at all\n * depends on the engine and on which AbortController implementation is in\n * play: Hermes supplies its own, a polyfill supplies another, and neither is\n * obliged to reject with a real DOMException. The name is the one part every\n * implementation agrees on, including the browser's. The previous check\n * compiled only because React Native's older type definitions pulled DOM\n * globals in behind our backs, and it would have quietly stopped recognising\n * a timeout on any engine without that global.\n */\nfunction isAbortError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n (err as { name?: unknown }).name === 'AbortError'\n );\n}\n\nexport class HttpClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n\n /** Set of AbortControllers for in-flight requests. Used by destroy() to cancel all. */\n private pendingControllers: Set<AbortController> = new Set();\n private destroyed = false;\n\n constructor(config: ResolvedTolinkuConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.timeout = config.timeout;\n }\n\n async get<T>(path: string, params?: Record<string, string>): Promise<T> {\n let url = this.baseUrl + path;\n if (params) {\n const qs = new URLSearchParams(params).toString();\n if (qs) url += '?' + qs;\n }\n\n return this.executeWithRetry<T>(url, {\n method: 'GET',\n headers: this.authenticatedHeaders(),\n });\n }\n\n async post<T>(path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(this.baseUrl + path, {\n method: 'POST',\n headers: {\n ...this.authenticatedHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /** GET without API key auth (for public endpoints like deferred claim) */\n async getPublic<T>(path: string, params?: Record<string, string>): Promise<T> {\n let url = this.baseUrl + path;\n if (params) {\n const qs = new URLSearchParams(params).toString();\n if (qs) url += '?' + qs;\n }\n\n return this.executeWithRetry<T>(url, {\n method: 'GET',\n headers: this.publicHeaders(),\n });\n }\n\n /**\n * POST to a host other than the configured one, without the API key.\n *\n * A few public endpoints work out which Appspace they belong to from the\n * hostname the request arrived on rather than from a key or an id, so a\n * question about a link on a customer's own domain has to be asked on that\n * domain. Everything else about the request is unchanged: same timeout, same\n * retries, same headers.\n */\n async postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(origin.replace(/\\/+$/, '') + path, {\n method: 'POST',\n headers: {\n ...this.publicHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /** POST without API key auth (for public endpoints like deferred claim) */\n async postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T> {\n return this.executeWithRetry<T>(this.baseUrl + path, {\n method: 'POST',\n headers: {\n ...this.publicHeaders(),\n 'Content-Type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n }\n\n /**\n * Abort all in-flight requests and mark the client as destroyed.\n * After calling this, all future requests will throw immediately.\n */\n abort(): void {\n this.destroyed = true;\n for (const controller of this.pendingControllers) {\n controller.abort();\n }\n this.pendingControllers.clear();\n }\n\n private authenticatedHeaders(): Record<string, string> {\n return {\n 'X-API-Key': this.apiKey,\n 'Accept': 'application/json',\n 'User-Agent': `TolinkuReactNativeSDK/${SDK_VERSION}`,\n };\n }\n\n private publicHeaders(): Record<string, string> {\n return {\n 'Accept': 'application/json',\n 'User-Agent': `TolinkuReactNativeSDK/${SDK_VERSION}`,\n };\n }\n\n /**\n * Execute a fetch request with retry logic. Retries on:\n * - Network errors (fetch throws)\n * - HTTP 429 (Too Many Requests), respecting the Retry-After header\n * - HTTP 5xx (server errors)\n *\n * Does NOT retry on 4xx errors (except 429).\n * Uses exponential backoff: BASE_DELAY_MS * 2^attempt + random jitter (0..MAX_JITTER_MS).\n */\n private async executeWithRetry<T>(\n url: string,\n init: RequestInit\n ): Promise<T> {\n if (this.destroyed) {\n throw new TolinkuError('Tolinku: client has been destroyed. Call Tolinku.init() to reinitialize.', 0);\n }\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n this.pendingControllers.add(controller);\n\n // Set up timeout\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const res = await fetch(url, {\n ...init,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n this.pendingControllers.delete(controller);\n\n if (res.ok) {\n return res.json();\n }\n\n // Parse error body\n const errorBody = await res.json().catch(() => ({ error: res.statusText }));\n const errorMessage = errorBody.error || res.statusText;\n const errorCode = errorBody.code;\n\n // Determine if we should retry\n const isRetryable = res.status === 429 || (res.status >= 500 && res.status < 600);\n\n if (!isRetryable || attempt === MAX_RETRIES) {\n throw new TolinkuError(errorMessage, res.status, errorCode);\n }\n\n lastError = new TolinkuError(errorMessage, res.status, errorCode);\n\n // Calculate delay: respect Retry-After for 429, otherwise exponential backoff\n let delayMs: number;\n if (res.status === 429) {\n const retryAfter = res.headers.get('Retry-After');\n const retryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : NaN;\n if (!isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {\n delayMs = retryAfterSeconds * 1000;\n } else {\n delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n }\n } else {\n delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n }\n\n const jitter = Math.random() * MAX_JITTER_MS;\n const totalDelay = delayMs + jitter;\n\n debugLog(`Retry ${attempt + 1}/${MAX_RETRIES} after ${Math.round(totalDelay)}ms (status=${res.status})`);\n\n await sleep(totalDelay);\n } catch (err) {\n clearTimeout(timeoutId);\n this.pendingControllers.delete(controller);\n\n // If the client was destroyed, rethrow immediately\n if (this.destroyed) {\n throw new TolinkuError('Tolinku: request aborted (client destroyed).', 0);\n }\n\n // AbortController timeout\n if (isAbortError(err)) {\n const timeoutErr = new TolinkuError(`Tolinku: request timed out after ${this.timeout}ms`, 0);\n if (attempt === MAX_RETRIES) throw timeoutErr;\n lastError = timeoutErr;\n } else if (err instanceof TolinkuError) {\n // Already a TolinkuError (from the non-retryable branch above); rethrow\n throw err;\n } else {\n // Network error; retry\n if (attempt === MAX_RETRIES) {\n throw new TolinkuError(\n `Tolinku: network error after ${MAX_RETRIES + 1} attempts: ${(err as Error).message}`,\n 0\n );\n }\n lastError = err as Error;\n }\n\n const delayMs = BASE_DELAY_MS * Math.pow(2, attempt);\n const jitter = Math.random() * MAX_JITTER_MS;\n const totalDelay = delayMs + jitter;\n\n debugLog(`Retry ${attempt + 1}/${MAX_RETRIES} after ${Math.round(totalDelay)}ms (${(err as Error).message})`);\n\n await sleep(totalDelay);\n }\n }\n\n // Should not reach here, but just in case\n throw lastError || new TolinkuError('Tolinku: request failed after retries', 0);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class TolinkuError extends Error {\n status: number;\n code: string | undefined;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'TolinkuError';\n this.status = status;\n this.code = code;\n }\n}\n","/**\n * A URL's scheme, lowercased and with its colon, or null when it has none.\n *\n * Deliberately not `new URL(x).protocol`. React Native ships its own URL, and\n * for most of this package's supported range that URL is a stub whose getters\n * throw: `protocol`, `hostname`, `host` and `origin` are all\n * `throw new Error('… is not implemented')` in 0.73, and only gained real\n * implementations much later. Every call here sat inside a try/catch, so the\n * throw was swallowed as \"unparseable\", and everything this guards was refused\n * on device while passing every test, because Jest runs on Node's URL.\n *\n * That is why this parses the scheme itself. Whitespace and control characters\n * are stripped the way a URL parser strips them, from the ends and from inside\n * the scheme, so `java\\tscript:` is recognised as javascript: rather than\n * waved through as something unparseable.\n */\nexport function urlScheme(url: string): string | null {\n if (!url || typeof url !== 'string') return null;\n\n // Tabs and newlines are removed anywhere in a URL; spaces and C0 controls\n // are stripped from the ends.\n const cleaned = url.replace(/[\\t\\n\\r]/g, '').replace(/^[\\u0000-\\u0020]+|[\\u0000-\\u0020]+$/g, '');\n // The underscore is not RFC 3986, and Android registers it in a manifest\n // and iOS in CFBundleURLSchemes, so real apps have schemes carrying one.\n const match = /^([a-zA-Z][a-zA-Z\\d+\\-._]*):/.exec(cleaned);\n return match ? `${match[1]!.toLowerCase()}:` : null;\n}\n\n/**\n * The pieces of an http(s) URL this package needs, or null.\n *\n * Same reason as {@link urlScheme}: React Native's own URL throws from\n * `origin` and `hostname` for most of the versions this package supports, so\n * asking it for them turned a working link into a silent failure on device.\n */\nexport function parseHttpUrl(url: string): { origin: string; pathname: string } | null {\n if (!url || typeof url !== 'string') return null;\n const cleaned = url.replace(/[\\t\\n\\r]/g, '').trim();\n\n const match = /^(https?):\\/\\/([^/?#]+)([^?#]*)/i.exec(cleaned);\n if (!match) return null;\n\n const [, scheme, authority, path] = match;\n if (!authority) return null;\n\n return {\n origin: `${scheme!.toLowerCase()}://${authority.toLowerCase()}`,\n // A URL with no path means the root, which is what a server expects to be\n // asked about.\n pathname: path || '/',\n };\n}\n\n/**\n * Check if a URL is safe to open or render. Only allows http: and https: protocols.\n * Blocks javascript:, data:, file:, and other potentially dangerous protocols.\n */\nexport function isSafeUrl(url: string): boolean {\n const scheme = urlScheme(url);\n return scheme === 'http:' || scheme === 'https:';\n}\n\n/**\n * The schemes that can run code, read local storage, or hide another scheme.\n *\n * Longer than the platform's own list because this package ends up somewhere\n * the platform does not. `Linking.openURL` on Android becomes an Intent, so\n * `content:` reads a ContentProvider, which includes another app's private\n * files wherever a permission has been granted, and `jar:` and `filesystem:`\n * each carry a second URL inside them, so allowing either hands back whatever\n * the rest of this set refuses. None of the three mean anything in a browser,\n * which is why safe-url.ts does not name them.\n */\nconst EXECUTABLE_SCHEMES = new Set([\n 'javascript:',\n 'vbscript:',\n 'data:',\n 'blob:',\n 'file:',\n 'content:',\n 'jar:',\n 'filesystem:',\n]);\n\n/**\n * Check whether a URL is safe to follow when someone taps it.\n *\n * Deliberately not {@link isSafeUrl}. That one allows http and https only,\n * which is right for an image source and wrong for a call to action: this is a\n * deep linking product, so the most natural button in an in-app message is one\n * that opens a screen in the app, `myapp://order/4821`. An allowlist blocked\n * exactly that, silently, before the host app's own handler was even called,\n * while the platform that authored the message has always permitted it.\n *\n * Every customer's scheme is different, so there is no list to allow. The small\n * known set of dangerous schemes is named instead, matching the platform's own\n * rule, and everything else is left to open.\n *\n * Parsing first is what makes this hold: tabs and newlines inside a scheme are\n * ignored by the things that follow URLs, so \"java\\tscript:alert(1)\" would run,\n * and the URL parser strips them the same way before reporting the protocol.\n */\nexport function isSafeActionUrl(url: string): boolean {\n const scheme = urlScheme(url);\n // No scheme means relative or a fragment. There is no base to resolve it\n // against on a device, so it is not something to open.\n if (!scheme) return false;\n return !EXECUTABLE_SCHEMES.has(scheme);\n}\n\n/**\n * Validate that a base URL uses HTTPS, with exceptions for local development.\n * Throws an error if the URL is invalid.\n */\nexport function validateBaseUrl(baseUrl: string): void {\n if (!baseUrl || typeof baseUrl !== 'string') {\n throw new Error('Tolinku: baseUrl must be a non-empty string.');\n }\n\n const trimmed = baseUrl.trim();\n\n // Allow local development URLs over HTTP\n const isLocalDev =\n trimmed.startsWith('http://localhost') ||\n trimmed.startsWith('http://127.0.0.1') ||\n trimmed.startsWith('http://10.') ||\n /^http:\\/\\/172\\.(1[6-9]|2\\d|3[01])\\./.test(trimmed) ||\n trimmed.startsWith('http://192.168.');\n\n if (trimmed.startsWith('https://')) {\n return; // Valid HTTPS URL\n }\n\n if (isLocalDev) {\n return; // Valid local development URL\n }\n\n throw new Error(\n 'Tolinku: baseUrl must use HTTPS to protect your API key. Use https:// instead of http://. ' +\n 'Local development URLs (localhost, 127.0.0.1, 10.x, 172.16-31.x, 192.168.x) are exempt from this requirement.'\n );\n}\n\n/** Regex for valid custom event names (after the \"custom.\" prefix) */\nconst EVENT_NAME_REGEX = /^custom\\.[a-z0-9_]+$/;\n\n/**\n * Validate and normalize an event type name.\n * Auto-prefixes with \"custom.\" if missing.\n * Throws a descriptive error if the name is invalid.\n */\nexport function validateEventType(eventType: string): string {\n if (!eventType || typeof eventType !== 'string' || !eventType.trim()) {\n throw new Error('Tolinku: eventType must be a non-empty string.');\n }\n\n let normalized = eventType.trim();\n\n // Auto-prefix with \"custom.\" if not present\n if (!normalized.startsWith('custom.')) {\n normalized = 'custom.' + normalized;\n }\n\n if (!EVENT_NAME_REGEX.test(normalized)) {\n throw new Error(\n `Tolinku: invalid event type \"${normalized}\". ` +\n 'Event names must match the pattern \"custom.[a-z0-9_]+\". ' +\n 'Use only lowercase letters, digits, and underscores after the \"custom.\" prefix.'\n );\n }\n\n return normalized;\n}\n","import { AppState, Platform, type AppStateStatus, type NativeEventSubscription } from 'react-native';\nimport type { HttpClient } from './client';\nimport type { TrackProperties } from './types';\nimport { validateEventType, isSafeUrl } from './validation';\nimport { debugLog, debugWarn } from './debug';\n\n/** Number of events that triggers an automatic flush. */\nconst BATCH_SIZE = 10;\n/** Maximum time (ms) to wait before flushing after the first queued event. */\nconst FLUSH_INTERVAL_MS = 5000;\n/** Maximum number of events to keep in the queue to prevent unbounded growth. */\nconst MAX_QUEUE_SIZE = 1000;\n\ninterface QueuedEvent {\n event_type: string;\n properties: TrackProperties;\n}\n\nexport class Analytics {\n private client: HttpClient;\n private queue: QueuedEvent[] = [];\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private appStateSubscription: NativeEventSubscription | null = null;\n private isFlushing = false;\n\n constructor(client: HttpClient) {\n this.client = client;\n\n // Listen for app going to background to flush events\n this.appStateSubscription = AppState.addEventListener(\n 'change',\n this.handleAppStateChange\n );\n }\n\n /**\n * Track a custom event. The event is added to the internal queue\n * and will be flushed automatically or when flush() is called.\n *\n * Event type must match /^custom\\.[a-z0-9_]+$/.\n * Auto-prefixes with \"custom.\" if missing.\n */\n /**\n * Set once the server says this Appspace does not attribute app opens, so the\n * setting costs one request a launch rather than one per link.\n */\n private appOpensDisabled = false;\n\n /**\n * The last link reported, and when. Cold start and the link stream can both\n * deliver the same tap, depending on the plugin, so an app instrumenting both\n * paths would otherwise report it twice and be billed twice. A genuine second\n * tap of the same link inside this window is implausible; a duplicate delivery\n * of one tap is not.\n */\n private lastOpenUrl: string | null = null;\n private lastOpenAt = 0;\n /**\n * Part of the key, not carried alongside it. An ordinary open and a deferred\n * one are different events on the server and only the app can tell them\n * apart, so a deferred report just after an ordinary one for the same link is\n * new information rather than a repeat. Keyed on the URL alone, somebody who\n * tapped a link, installed, then tapped it again would have the deferred\n * report swallowed, losing the last stage of the install funnel in the one\n * case it exists to show.\n */\n private lastOpenDeferred = false;\n private static readonly OPEN_DEDUPE_MS = 5000;\n\n\n /**\n * Report that a link opened the app without the browser being involved.\n *\n * A Universal Link or App Link hands the app the URL directly, so Tolinku is\n * never contacted and the tap goes unrecorded. Those taps come from people who\n * already have the app, so leaving them out makes a re-engagement campaign\n * look like a failure exactly when it worked.\n *\n * Only http and https links are reported. A custom scheme means Tolinku's own\n * hand-off page opened the app, and that tap was counted when the page was\n * served, so passing one does nothing rather than counting it twice.\n *\n * Never throws. This runs on the path that routes the user somewhere, and a\n * tap that goes unrecorded is not worth interrupting that.\n */\n async trackLinkOpen(url: string, userId?: string, deferred = false): Promise<void> {\n if (this.appOpensDisabled) return;\n\n const trimmed = typeof url === 'string' ? url.trim() : '';\n if (!trimmed) return;\n\n // The scheme decides, and the server checks it again.\n // Not the platform's URL: React Native's own throws from protocol on most\n // of the versions this package supports, and that throw was uncaught here,\n // so an open reported from a link turned into an unhandled rejection in\n // apps that call this without awaiting it, which is how it is documented.\n if (!isSafeUrl(trimmed)) return;\n\n const now = Date.now();\n if (\n this.lastOpenUrl === trimmed &&\n this.lastOpenDeferred === deferred &&\n now - this.lastOpenAt < Analytics.OPEN_DEDUPE_MS\n ) return;\n this.lastOpenUrl = trimmed;\n this.lastOpenAt = now;\n this.lastOpenDeferred = deferred;\n\n try {\n const result = await this.client.postPublic<{ attribute?: boolean }>(\n '/v1/api/opens',\n {\n url: trimmed,\n // The User-Agent cannot say which platform this is: this SDK\n // identifies itself the same way on both. Without it an app open has\n // no platform and lands in a blank bucket on every breakdown.\n platform: Platform.OS === 'ios' || Platform.OS === 'android' ? Platform.OS : undefined,\n // Whether this open followed a deferred install. Only the app knows.\n // An ordinary open is somebody who already had the app and can never\n // convert to an install; an open after a deferred claim is the last\n // stage of the install funnel. The server records them as different\n // events and must not pool them.\n ...(deferred ? { deferred: true } : {}),\n ...(userId ? { user_id: userId } : {}),\n },\n );\n if (result?.attribute === false) this.appOpensDisabled = true;\n } catch {\n // Deliberately silent.\n }\n }\n\n async track(eventType: string, properties?: TrackProperties): Promise<void> {\n const normalizedType = validateEventType(eventType);\n\n const event: QueuedEvent = {\n event_type: normalizedType,\n properties: properties || {},\n };\n\n // Enforce max queue size\n if (this.queue.length >= MAX_QUEUE_SIZE) {\n debugWarn(\n `Analytics queue is full (${MAX_QUEUE_SIZE} events). Dropping oldest event to make room.`\n );\n this.queue.shift();\n }\n\n this.queue.push(event);\n\n if (this.queue.length >= BATCH_SIZE) {\n await this.flush();\n } else if (this.queue.length === 1) {\n // First event in the queue; start the flush timer\n this.startFlushTimer();\n }\n }\n\n /**\n * Immediately flush all queued events to the server.\n * If the queue is empty, this is a no-op.\n * If a flush is already in progress, this is a no-op to prevent race conditions.\n */\n async flush(): Promise<void> {\n if (this.queue.length === 0 || this.isFlushing) return;\n\n this.isFlushing = true;\n\n // Take a snapshot and clear the queue\n const eventsToSend = this.queue.splice(0, this.queue.length);\n this.cancelFlushTimer();\n\n try {\n debugLog(`Flushing ${eventsToSend.length} analytics event(s)`);\n const result = await this.client.post<{ ok: boolean; accepted?: number; errors?: string[] }>('/v1/api/analytics/batch', {\n events: eventsToSend,\n });\n if (result.errors && result.errors.length > 0) {\n debugWarn(`Batch partial failure: ${result.errors.join(', ')}`);\n }\n } catch (err) {\n debugWarn(`Failed to flush analytics events: ${(err as Error).message}`);\n // Re-enqueue events at the front (up to MAX_QUEUE_SIZE)\n const spaceLeft = MAX_QUEUE_SIZE - this.queue.length;\n if (spaceLeft > 0) {\n this.queue.unshift(...eventsToSend.slice(0, spaceLeft));\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n /**\n * Shut down the analytics module: flush remaining events, cancel the timer,\n * and remove the AppState listener.\n */\n async destroy(): Promise<void> {\n this.cancelFlushTimer();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n try {\n await this.flush();\n } catch {\n // Best-effort flush during shutdown\n }\n }\n\n private handleAppStateChange = (state: AppStateStatus): void => {\n if (state === 'background' || state === 'inactive') {\n // Fire-and-forget flush when going to background\n this.flush().catch(() => {});\n }\n };\n\n private startFlushTimer(): void {\n this.cancelFlushTimer();\n this.flushTimer = setTimeout(() => {\n this.flush().catch((err) => {\n debugWarn(`Timer flush failed: ${(err as Error).message}`);\n });\n }, FLUSH_INTERVAL_MS);\n }\n\n private cancelFlushTimer(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n}\n","import { AppState, type AppStateStatus, type NativeEventSubscription } from 'react-native';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport type { HttpClient } from './client';\nimport type {\n EcommerceItem, PurchaseParams, AddToCartParams, RemoveFromCartParams,\n AddToWishlistParams, BeginCheckoutParams, RefundParams, ViewItemParams,\n SearchParams, ShareParams, RateParams, SpendCreditsParams, AddPaymentInfoParams,\n} from './types';\nimport { debugLog, debugWarn } from './debug';\n\nconst BATCH_SIZE = 10;\nconst FLUSH_INTERVAL_MS = 5000;\nconst MAX_QUEUE_SIZE = 500;\nconst CART_ID_STORAGE_KEY = 'tolinku_ecom_cart_id';\n\ninterface QueuedEcomEvent {\n event_type: string;\n transaction_id?: string;\n revenue?: number;\n currency?: string;\n cart_id?: string;\n coupon_code?: string;\n discount?: number;\n shipping?: number;\n tax?: number;\n items?: EcommerceItem[];\n properties?: Record<string, string>;\n user_id?: string;\n campaign?: string;\n source?: string;\n medium?: string;\n platform?: string;\n}\n\nexport class Ecommerce {\n private client: HttpClient;\n private queue: QueuedEcomEvent[] = [];\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private appStateSubscription: NativeEventSubscription | null = null;\n private isFlushing = false;\n private getUserId: () => string | null;\n private memoryCartId: string | null = null;\n\n constructor(client: HttpClient, getUserId: () => string | null) {\n this.client = client;\n this.getUserId = getUserId;\n\n this.appStateSubscription = AppState.addEventListener(\n 'change',\n this.handleAppStateChange,\n );\n }\n\n // ─── Public methods (13 event types) ────────────────────\n\n async viewItem(params: ViewItemParams): Promise<void> {\n await this.enqueue({ event_type: 'view_item', items: params.items });\n }\n\n async addToCart(params: AddToCartParams): Promise<void> {\n const cartId = params.cart_id || await this.getOrCreateCartId();\n await this.enqueue({ event_type: 'add_to_cart', items: params.items, cart_id: cartId });\n }\n\n async removeFromCart(params: RemoveFromCartParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({ event_type: 'remove_from_cart', items: params.items, cart_id: cartId });\n }\n\n async addToWishlist(params: AddToWishlistParams): Promise<void> {\n await this.enqueue({ event_type: 'add_to_wishlist', items: params.items });\n }\n\n async viewCart(): Promise<void> {\n const cartId = await this.getCartId();\n await this.enqueue({ event_type: 'view_cart', cart_id: cartId });\n }\n\n async addPaymentInfo(params?: AddPaymentInfoParams): Promise<void> {\n const cartId = params?.cart_id || await this.getCartId();\n await this.enqueue({ event_type: 'add_payment_info', cart_id: cartId });\n }\n\n async beginCheckout(params: BeginCheckoutParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({\n event_type: 'begin_checkout',\n revenue: params.revenue,\n currency: params.currency,\n cart_id: cartId,\n items: params.items,\n });\n }\n\n async purchase(params: PurchaseParams): Promise<void> {\n const cartId = params.cart_id || await this.getCartId();\n await this.enqueue({\n event_type: 'purchase',\n transaction_id: params.transaction_id,\n revenue: params.revenue,\n currency: params.currency,\n cart_id: cartId,\n coupon_code: params.coupon_code,\n discount: params.discount,\n shipping: params.shipping,\n tax: params.tax,\n items: params.items,\n });\n await this.clearCartId();\n }\n\n async refund(params: RefundParams): Promise<void> {\n await this.enqueue({\n event_type: 'refund',\n transaction_id: params.transaction_id,\n revenue: params.revenue,\n currency: params.currency,\n items: params.items,\n });\n }\n\n async search(params: SearchParams): Promise<void> {\n await this.enqueue({ event_type: 'search', properties: { search_term: params.search_term } });\n }\n\n async share(params: ShareParams): Promise<void> {\n const props: Record<string, string> = {};\n if (params.item_id) props.item_id = params.item_id;\n if (params.url) props.url = params.url;\n if (params.method) props.method = params.method;\n await this.enqueue({ event_type: 'share', properties: props });\n }\n\n async rate(params: RateParams): Promise<void> {\n await this.enqueue({\n event_type: 'rate',\n properties: {\n item_id: params.item_id,\n rating: String(params.rating),\n ...(params.max_rating != null ? { max_rating: String(params.max_rating) } : {}),\n },\n });\n }\n\n async spendCredits(params: SpendCreditsParams): Promise<void> {\n await this.enqueue({ event_type: 'spend_credits', revenue: params.revenue, currency: params.currency });\n }\n\n // ─── Flush ─────────────────────────────────────────────\n\n async flush(): Promise<void> {\n if (this.queue.length === 0 || this.isFlushing) return;\n\n this.isFlushing = true;\n const events = this.queue.splice(0);\n this.cancelFlushTimer();\n\n try {\n debugLog(`Flushing ${events.length} ecommerce event(s)`);\n const result = await this.client.post<{ ok: boolean; accepted?: number; errors?: string[] }>(\n '/v1/api/analytics/ecommerce/batch',\n { events },\n );\n if (result.errors && result.errors.length > 0) {\n debugWarn(`Ecommerce batch partial failure: ${result.errors.join(', ')}`);\n }\n } catch (err) {\n debugWarn(`Failed to flush ecommerce events: ${(err as Error).message}`);\n const spaceLeft = MAX_QUEUE_SIZE - this.queue.length;\n if (spaceLeft > 0) {\n this.queue.unshift(...events.slice(0, spaceLeft));\n }\n } finally {\n this.isFlushing = false;\n }\n }\n\n async destroy(): Promise<void> {\n this.cancelFlushTimer();\n this.appStateSubscription?.remove();\n this.appStateSubscription = null;\n\n try {\n await this.flush();\n } catch {\n // Best-effort flush during shutdown\n }\n }\n\n // ─── Private ───────────────────────────────────────────\n\n private async enqueue(event: QueuedEcomEvent): Promise<void> {\n const userId = this.getUserId();\n if (userId) event.user_id = userId;\n\n if (this.queue.length >= MAX_QUEUE_SIZE) {\n debugWarn(`Ecommerce queue full (${MAX_QUEUE_SIZE}). Dropping oldest event.`);\n this.queue.shift();\n }\n\n this.queue.push(event);\n\n if (this.queue.length >= BATCH_SIZE) {\n await this.flush();\n } else if (this.queue.length === 1) {\n this.startFlushTimer();\n }\n }\n\n private handleAppStateChange = (state: AppStateStatus): void => {\n if (state === 'background' || state === 'inactive') {\n this.flush().catch(() => {});\n }\n };\n\n private startFlushTimer(): void {\n this.cancelFlushTimer();\n this.flushTimer = setTimeout(() => {\n this.flush().catch((err) => {\n debugWarn(`Ecommerce timer flush failed: ${(err as Error).message}`);\n });\n }, FLUSH_INTERVAL_MS);\n }\n\n private cancelFlushTimer(): void {\n if (this.flushTimer !== null) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n }\n\n // ─── Cart ID lifecycle (AsyncStorage + memory fallback) ─\n\n private async getOrCreateCartId(): Promise<string> {\n const existing = await this.getCartId();\n if (existing) return existing;\n\n const cartId = this.generateId();\n await this.setCartId(cartId);\n return cartId;\n }\n\n private async getCartId(): Promise<string | undefined> {\n try {\n const stored = await AsyncStorage.getItem(CART_ID_STORAGE_KEY);\n if (stored) return stored;\n } catch { /* ignore */ }\n return this.memoryCartId || undefined;\n }\n\n private async setCartId(cartId: string): Promise<void> {\n this.memoryCartId = cartId;\n try {\n await AsyncStorage.setItem(CART_ID_STORAGE_KEY, cartId);\n } catch { /* memory fallback is already set */ }\n }\n\n private async clearCartId(): Promise<void> {\n this.memoryCartId = null;\n try {\n await AsyncStorage.removeItem(CART_ID_STORAGE_KEY);\n } catch { /* ignore */ }\n }\n\n private generateId(): string {\n // Hermes has crypto.randomUUID from React Native 0.74, and older engines\n // and polyfill-free builds have no crypto at all, so this is read off\n // globalThis rather than named as a bare global. React Native's types used\n // to declare `crypto` for us; they no longer do, and naming it directly\n // stopped compiling on React Native 0.88 for that reason.\n const g = globalThis as { crypto?: { randomUUID?: () => string } };\n if (typeof g.crypto?.randomUUID === 'function') {\n return g.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n}\n","import type { HttpClient } from './client';\nimport type {\n CreateReferralOptions,\n CreateReferralResult,\n CompleteReferralOptions,\n CompleteReferralResult,\n MilestoneOptions,\n MilestoneResult,\n ReferralInfo,\n LeaderboardEntry,\n} from './types';\n\nexport class Referrals {\n constructor(private client: HttpClient) {}\n\n /** Create a new referral for a user */\n async create(options: CreateReferralOptions): Promise<CreateReferralResult> {\n if (!options.userId || !options.userId.trim()) {\n throw new Error('Tolinku: userId is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/create', {\n user_id: options.userId,\n metadata: options.metadata,\n user_name: options.userName,\n });\n }\n\n /** Get referral info by code */\n async get(code: string): Promise<ReferralInfo> {\n if (!code || !code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n\n return this.client.get(`/v1/api/referral/${encodeURIComponent(code)}`);\n }\n\n /** Complete a referral (mark as converted) */\n async complete(options: CompleteReferralOptions): Promise<CompleteReferralResult> {\n if (!options.code || !options.code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n if (!options.referredUserId || !options.referredUserId.trim()) {\n throw new Error('Tolinku: referredUserId is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/complete', {\n referral_code: options.code,\n referred_user_id: options.referredUserId,\n milestone: options.milestone,\n referred_user_name: options.referredUserName,\n });\n }\n\n /** Update a referral milestone */\n async milestone(options: MilestoneOptions): Promise<MilestoneResult> {\n if (!options.code || !options.code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n if (!options.milestone || !options.milestone.trim()) {\n throw new Error('Tolinku: milestone is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/milestone', {\n referral_code: options.code,\n milestone: options.milestone,\n });\n }\n\n /** Claim a referral reward */\n async claimReward(code: string): Promise<{ success: boolean; referral_code: string; reward_claimed: boolean }> {\n if (!code || !code.trim()) {\n throw new Error('Tolinku: referral code is required and must not be blank.');\n }\n\n return this.client.post('/v1/api/referral/claim-reward', {\n referral_code: code,\n });\n }\n\n /** Get the referral leaderboard */\n async leaderboard(limit: number = 25): Promise<{ leaderboard: LeaderboardEntry[] }> {\n return this.client.get('/v1/api/referral/leaderboard', {\n limit: String(limit),\n });\n }\n}\n","import { NativeModules, Platform } from 'react-native';\nimport { debugWarn } from './debug';\n\n/**\n * The Play Install Referrer, the deterministic half of deferred linking on\n * Android.\n *\n * A Tolinku link sends an Android visitor to the store with\n * `referrer=tolk_token=<token>` attached. Play keeps that string through the\n * install and returns it on first launch, naming the exact click rather than\n * inferring it from device signals.\n *\n * Reading it needs a Play Services binding, which is native code, and this\n * package ships that itself: the token is Tolinku's own mechanism, minted on the\n * link, so reading it back should not depend on a third party. Nothing extra to\n * install, and autolinking is per-platform so an iOS-only app never builds it.\n *\n * Where the native module is absent, notably in Expo Go, deferred linking still\n * works through signal matching, less precisely.\n */\n\nconst TOKEN_KEY = 'tolk_token';\n\n/**\n * Pull our token out of a Play referrer string.\n *\n * The referrer is shared. A developer's own `utm_source` and anything else they\n * attached sit in the same string, so the token is found among the pairs rather\n * than assumed to be the whole value. A percent-encoded `%3D` is tolerated\n * because Play normally decodes it, and that assumption is not worth a lost\n * install if it is ever wrong.\n */\nexport function parseInstallReferrer(referrer: string | null | undefined): string | null {\n if (!referrer || !referrer.trim()) return null;\n\n let decoded = referrer;\n try {\n decoded = decodeURIComponent(referrer);\n } catch {\n // Malformed encoding: fall back to the raw string.\n }\n\n const pair = decoded\n .split('&')\n .map(p => p.trim())\n .find(p => p.startsWith(`${TOKEN_KEY}=`));\n\n if (!pair) return null;\n const token = pair.slice(TOKEN_KEY.length + 1);\n return token.trim() ? token : null;\n}\n\n/** Anything that can hand back a Play referrer string. */\nexport type ReferrerProvider = () => Promise<string | null> | string | null;\n\n/**\n * Our own native module, when the app was built with it.\n *\n * Accessed lazily rather than at import time. In Expo Go, and anywhere the\n * native side was not built, this is simply absent, and touching NativeModules\n * during module evaluation would turn that ordinary case into a crash on first\n * launch.\n */\nfunction nativeProvider(): ReferrerProvider | null {\n const native = (NativeModules as Record<string, any> | undefined)?.TolinkuInstallReferrer;\n if (!native || typeof native.getInstallReferrer !== 'function') return null;\n return () => native.getInstallReferrer();\n}\n\n/**\n * Best effort at the referrer token for this install.\n *\n * Android only, and null everywhere else: there is no equivalent on iOS, which\n * is why signal matching exists at all. Never throws, because attribution must\n * not be able to fail a first launch.\n */\nexport async function getInstallReferrerToken(\n provider?: ReferrerProvider,\n): Promise<string | null> {\n if (Platform.OS !== 'android') return null;\n\n const source = provider ?? nativeProvider();\n if (!source) return null;\n\n try {\n const referrer = await source();\n return parseInstallReferrer(referrer);\n } catch (err) {\n debugWarn(`Install referrer lookup failed: ${(err as Error).message}`);\n return null;\n }\n}\n","import { Dimensions, PixelRatio, Platform } from 'react-native';\nimport type { HttpClient } from './client';\nimport type { DeferredLink, ClaimBySignalsOptions } from './types';\nimport { debugWarn } from './debug';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { getInstallReferrerToken, type ReferrerProvider } from './install-referrer';\n\n/**\n * Marks that a deferred claim already ran on this install.\n *\n * Claiming is a first-launch action, but nothing stops an app calling it every\n * launch, which is an easy mistake. Each repeat costs a request and records a\n * miss, so a healthy integration would report a match rate near zero.\n * Remembering the attempt belongs here rather than in every integrator's code.\n */\nconst CLAIMED_KEY = 'tolinku_deferred_claimed';\n\nexport class Deferred {\n constructor(private client: HttpClient) {}\n\n /** Claim a deferred deep link by referrer token (from Play Store referrer or clipboard) */\n async claimByToken(token: string, appspaceId?: string): Promise<DeferredLink | null> {\n if (!token || !token.trim()) {\n throw new Error('Tolinku: token is required and must not be blank for claimByToken.');\n }\n\n try {\n // appspaceId narrows what the token may claim, never widens it, and it is\n // what lets a failed claim be attributed: the default host resolves to no\n // Appspace, so without it a miss belongs to nobody and goes uncounted.\n return await this.client.getPublic<DeferredLink>('/v1/api/deferred/claim', {\n token,\n ...(appspaceId ? { appspace_id: appspaceId } : {}),\n });\n } catch (err) {\n debugWarn(`Deferred claimByToken failed: ${(err as Error).message}`);\n return null;\n }\n }\n\n /**\n * Recover the link that led to this install, trying both mechanisms.\n *\n * The Play Install Referrer is asked first on Android: it names the exact\n * click, survives for days, and does not care which network the device was\n * on. Device signals are the fallback, and the only option on iOS, where no\n * equivalent exists.\n *\n * Call once on first launch. Safe to call again, but a claim is consumed the\n * first time it succeeds, so a second call returns null.\n *\n * Reading the referrer needs a native Play Services binding, which this\n * package deliberately does not bundle. Pass `referrerProvider`, or install a\n * supported referrer package and it is used automatically. Without either,\n * Android falls back to signal matching.\n */\n async claimDeferredLink(options: {\n appspaceId: string;\n referrerProvider?: ReferrerProvider;\n /** Claim again even if an attempt was already recorded. For tests. */\n force?: boolean;\n }): Promise<DeferredLink | null> {\n if (!options.appspaceId || !options.appspaceId.trim()) {\n throw new Error('Tolinku: appspaceId is required and must not be blank for claimDeferredLink.');\n }\n\n if (!options.force && (await this.alreadyAttempted())) return null;\n\n const token = await getInstallReferrerToken(options.referrerProvider);\n if (token) {\n // A referrer that cannot be claimed is worth one fallback rather than an\n // error: the install still happened.\n const byToken = await this.claimByToken(token, options.appspaceId).catch(() => null);\n if (byToken) {\n await this.rememberAttempt();\n return byToken;\n }\n }\n\n const { link, settled } = await this.attemptSignals({ appspaceId: options.appspaceId });\n // Only a real answer is remembered. A dropped request leaves this unwritten\n // so the next launch tries again: losing an install's attribution to one\n // bad connection is worse than one extra request.\n if (settled) await this.rememberAttempt();\n return link;\n }\n\n private async alreadyAttempted(): Promise<boolean> {\n try {\n return (await AsyncStorage.getItem(CLAIMED_KEY)) !== null;\n } catch {\n // Storage unavailable: attempt the claim rather than skip it.\n return false;\n }\n }\n\n private async rememberAttempt(): Promise<void> {\n try {\n await AsyncStorage.setItem(CLAIMED_KEY, new Date().toISOString());\n } catch {\n // Not worth failing a claim that already succeeded.\n }\n }\n\n /** Claim a deferred deep link by device signal matching */\n async claimBySignals(options: ClaimBySignalsOptions): Promise<DeferredLink | null> {\n if (!options.appspaceId || !options.appspaceId.trim()) {\n throw new Error('Tolinku: appspaceId is required and must not be blank for claimBySignals.');\n }\n return (await this.attemptSignals(options)).link;\n }\n\n /**\n * The signal claim, with whether the server actually answered.\n *\n * `settled` separates \"nothing is waiting for this device\", which no amount\n * of asking will change, from \"the request never got there\". Both surface as\n * null to callers of claimBySignals, but claimDeferredLink has to tell them\n * apart: recording an attempt that never reached the server would spend an\n * install's one chance at attribution on a dropped connection.\n */\n private async attemptSignals(\n options: ClaimBySignalsOptions,\n ): Promise<{ link: DeferredLink | null; settled: boolean }> {\n try {\n const { width, height } = Dimensions.get('screen');\n const resolvedTimezone = override(options.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone;\n // Matched against the landing page's `navigator.language`, a full BCP-47 tag\n // such as \"ko-KR\". Defaulting to a bare \"en\" meant the language signal\n // almost never scored. Intl reports the device locale with its region on\n // any runtime with Intl support (Hermes has it enabled by default).\n const resolvedLanguage =\n override(options.language) ||\n (typeof Intl !== 'undefined' && typeof Intl.DateTimeFormat === 'function'\n ? Intl.DateTimeFormat().resolvedOptions().locale\n : undefined) ||\n 'en';\n\n const link = await this.client.postPublic<DeferredLink>('/v1/api/deferred/claim-by-signals', {\n appspace_id: options.appspaceId,\n timezone: resolvedTimezone,\n language: resolvedLanguage,\n screen_width: override(options.screenWidth) || width,\n screen_height: override(options.screenHeight) || height,\n // Separates devices reporting identical dp dimensions.\n device_pixel_ratio: override(options.devicePixelRatio) || PixelRatio.get(),\n os_version: override(options.osVersion) || String(Platform.Version),\n });\n return { link, settled: true };\n } catch (err) {\n // A 404 is the ordinary \"nothing waiting for this device\" outcome. Anything\n // else is a configuration problem the integrator has to see: in particular a\n // 403 means appspaceId is wrong, and silently returning null there turns a\n // one-line fix into days of debugging.\n const status = (err as { statusCode?: number; status?: number })?.statusCode\n ?? (err as { status?: number })?.status;\n if (status === 404) {\n // Nothing is waiting for this device. The ordinary outcome, not a fault,\n // and a final one: asking again cannot change it.\n debugWarn('Deferred claimBySignals: no match for this device.');\n return { link: null, settled: true };\n }\n if (status === 403) {\n console.warn(\n '[Tolinku] claimBySignals failed with HTTP 403. Check that appspaceId is your ' +\n 'Appspace ID (copy it from the dashboard under Settings), not your subdomain ' +\n `or slug. ${(err as Error).message}`,\n );\n return { link: null, settled: false };\n }\n debugWarn(`Deferred claimBySignals failed: ${(err as Error).message}`);\n return { link: null, settled: false };\n }\n }\n}\n\n/**\n * An override the caller actually supplied.\n *\n * A blank string and a non-positive number are what an unset configuration value\n * and a failed lookup look like. Taking one literally would replace a good value\n * the device reported with one the matcher cannot use, and a signal that is\n * present and disagrees counts against the match where an absent one is simply\n * skipped. So a blank override is worse than no override, which is the opposite\n * of what the caller intends by passing it.\n */\nfunction override(value: string | undefined): string | undefined;\nfunction override(value: number | undefined): number | undefined;\nfunction override(value: string | number | undefined): string | number | undefined {\n if (typeof value === 'string') {\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n }\n if (typeof value === 'number') {\n return Number.isFinite(value) && value > 0 ? value : undefined;\n }\n return undefined;\n}\n","import type { HttpClient } from './client';\nimport type { ResolvedLink } from './types';\nimport { debugWarn } from './debug';\nimport { parseHttpUrl } from './validation';\n\n/**\n * Working out what a link the operating system handed the app actually means.\n *\n * An app receives the URL that was tapped, exactly as it was written. That is\n * fine while the URL is readable: `/order/4821` says \"order\" and the app can\n * route it. It is not fine for a short link, which is the same route written as\n * a code:\n *\n * https://links.example.com/s7k2p9q/4821\n *\n * Nothing in that URL says \"order\", and nothing about the code can be worked\n * out on the device. An app parsing the path itself sees a first segment it has\n * never heard of and does nothing, so the link opens the app and then appears\n * to fail, which is the quietest way a link can break: no error, no screen, no\n * clue. Short links are what a dashboard offers for sharing and what a QR code\n * carries, so this is not a rare path.\n *\n * `resolve` asks the platform, which answers with the route, the token and the\n * canonical path, and the app can route that the way it routes anything else.\n * A readable URL comes back unchanged, so an app can simply resolve everything\n * rather than guessing which kind it has.\n */\n/**\n * Whether the platform's answer is the path it promises to be.\n *\n * `resolve` sends its question to a host taken from the URL it was given, so an\n * app resolving a link from somewhere it does not control is talking to a\n * stranger. The contract is a path and nothing else: a full URL, or a protocol\n * relative \"//host\" that reads as one, is a redirect waiting to happen in\n * whatever the app does with it next.\n */\nfunction isRoutablePath(path: unknown): path is string {\n return typeof path === 'string'\n && path.startsWith('/')\n && !path.startsWith('//');\n}\n\nexport class Links {\n constructor(private client: HttpClient) {}\n\n /**\n * What this link means, or null if it means nothing here.\n *\n * `url` is a whole link as the app received it. The question goes to the\n * link's own host, because that is how the platform knows which Appspace is\n * being asked about, which also means a link on a domain that is not yours\n * simply answers nothing.\n *\n * Never throws. A link that cannot be resolved, for a bad network or any\n * other reason, is one the app should fall back to its own handling for, and\n * an exception in the middle of a cold start is no way to say so.\n */\n async resolve(url: string): Promise<ResolvedLink | null> {\n if (!url || typeof url !== 'string') return null;\n\n // Parsed here rather than with the platform's URL: React Native's own URL\n // throws from origin and protocol on most of the versions this package\n // supports, and the throw landed inside the catch below, so a perfectly\n // good link came back as \"not a URL\" on device while every test passed.\n //\n // http and https only. A custom scheme link already carries the path the\n // app wants, and anything else is not a link this could answer for.\n const parsed = parseHttpUrl(url);\n if (!parsed) {\n debugWarn(`Links.resolve: not an http(s) URL: ${url}`);\n return null;\n }\n\n try {\n const result = await this.client.postPublicToOrigin<ResolvedLink>(\n parsed.origin,\n '/v1/api/path',\n { path: parsed.pathname },\n );\n if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;\n return result;\n } catch (err) {\n debugWarn(`Links.resolve failed: ${(err as Error).message}`);\n return null;\n }\n }\n}\n","import AsyncStorage from '@react-native-async-storage/async-storage';\n\nconst BASE_KEY = 'tolinku_message_dismissed';\nconst IMPRESSIONS_BASE_KEY = 'tolinku_message_impressions';\nconst LAST_SHOWN_BASE_KEY = 'tolinku_message_last_shown';\n\n/** Current namespace prefix, set when the SDK is initialized. */\nlet keyPrefix = BASE_KEY;\nlet impressionsKeyPrefix = IMPRESSIONS_BASE_KEY;\nlet lastShownKeyPrefix = LAST_SHOWN_BASE_KEY;\n\n/**\n * Set the storage namespace based on the API key.\n * This prevents collisions when the same app uses multiple Appspaces.\n * Uses a simple hash of the API key to keep storage keys short.\n */\nexport function setStorageNamespace(apiKey: string): void {\n const hash = simpleHash(apiKey);\n keyPrefix = `tolinku_${hash}_message_dismissed`;\n impressionsKeyPrefix = `tolinku_${hash}_message_impressions`;\n lastShownKeyPrefix = `tolinku_${hash}_message_last_shown`;\n}\n\n/** Reset to the default (un-namespaced) key. Used during destroy(). */\nexport function resetStorageNamespace(): void {\n keyPrefix = BASE_KEY;\n impressionsKeyPrefix = IMPRESSIONS_BASE_KEY;\n lastShownKeyPrefix = LAST_SHOWN_BASE_KEY;\n}\n\nasync function getStore(key: string): Promise<Record<string, string>> {\n try {\n const raw = await AsyncStorage.getItem(key);\n return raw ? JSON.parse(raw) : {};\n } catch {\n return {};\n }\n}\n\nasync function setStore(key: string, data: Record<string, string>): Promise<void> {\n try {\n await AsyncStorage.setItem(key, JSON.stringify(data));\n } catch {\n // Storage unavailable\n }\n}\n\nexport async function isMessageDismissed(messageId: string, dismissDays: number | null): Promise<boolean> {\n if (!dismissDays || dismissDays <= 0) return false;\n const data = await getStore(keyPrefix);\n const entry = data[messageId];\n if (!entry) return false;\n const dismissedAt = new Date(entry).getTime();\n return (Date.now() - dismissedAt) < (dismissDays * 86400000);\n}\n\nexport async function saveMessageDismissal(messageId: string): Promise<void> {\n const data = await getStore(keyPrefix);\n data[messageId] = new Date().toISOString();\n await setStore(keyPrefix, data);\n}\n\n/**\n * Check if a message should be suppressed based on max_impressions\n * or min_interval_hours. Returns true if the message should NOT be shown.\n */\nexport async function isMessageSuppressed(\n messageId: string,\n maxImpressions: number | null,\n minIntervalHours: number | null,\n): Promise<boolean> {\n // Check max impressions\n if (maxImpressions !== null && maxImpressions > 0) {\n const impressions = await getStore(impressionsKeyPrefix);\n const count = parseInt(impressions[messageId] || '0', 10);\n if (count >= maxImpressions) return true;\n }\n\n // Check min interval\n if (minIntervalHours !== null && minIntervalHours > 0) {\n const lastShown = await getStore(lastShownKeyPrefix);\n const entry = lastShown[messageId];\n if (entry) {\n const lastShownAt = new Date(entry).getTime();\n const intervalMs = minIntervalHours * 3600000;\n if ((Date.now() - lastShownAt) < intervalMs) return true;\n }\n }\n\n return false;\n}\n\n/** Record that a message was shown (increment impression count and update last-shown time). */\nexport async function recordMessageImpression(messageId: string): Promise<void> {\n // Increment impression count\n const impressions = await getStore(impressionsKeyPrefix);\n const count = parseInt(impressions[messageId] || '0', 10);\n impressions[messageId] = String(count + 1);\n await setStore(impressionsKeyPrefix, impressions);\n\n // Update last-shown timestamp\n const lastShown = await getStore(lastShownKeyPrefix);\n lastShown[messageId] = new Date().toISOString();\n await setStore(lastShownKeyPrefix, lastShown);\n}\n\n/**\n * Simple string hash (djb2 algorithm). Returns a short hex string.\n */\nfunction simpleHash(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash + str.charCodeAt(i)) & 0xffffffff;\n }\n return (hash >>> 0).toString(16);\n}\n","import { Linking, type EmitterSubscription } from 'react-native';\nimport { HttpClient } from './client';\nimport { Analytics } from './analytics';\nimport { Ecommerce } from './ecommerce';\nimport { Referrals } from './referrals';\nimport { Deferred } from './deferred';\nimport { Links } from './links';\nimport { validateBaseUrl } from './validation';\nimport { setDebugEnabled, debugLog, debugWarn } from './debug';\nimport { setStorageNamespace, resetStorageNamespace } from './storage';\nimport { SDK_VERSION } from './types';\nimport type { TolinkuConfig, ResolvedTolinkuConfig, TrackProperties } from './types';\n\n/**\n * Main Tolinku SDK singleton.\n *\n * Initialize once with Tolinku.init(), then use static methods for all operations.\n *\n * Example:\n * Tolinku.init({ apiKey: 'tolk_pub_...' });\n * await Tolinku.track('signup', { source: 'onboarding' });\n */\nexport class Tolinku {\n static readonly VERSION = SDK_VERSION;\n\n private static client: HttpClient | null = null;\n private static analyticsInstance: Analytics | null = null;\n private static ecommerceInstance: Ecommerce | null = null;\n private static referralsInstance: Referrals | null = null;\n private static deferredInstance: Deferred | null = null;\n private static linksInstance: Links | null = null;\n private static _initialized = false;\n private static _userId: string | null = null;\n\n /**\n * Initialize the SDK. Must be called before any other method.\n *\n * If init() is called a second time without calling destroy() first,\n * a warning is logged and the existing instance is returned.\n */\n /**\n * Configure the SDK.\n *\n * The name the Android, iOS and Flutter SDKs use for this. {@link init} does\n * the same thing and still works; it is what this package shipped and\n * breaking it would serve nobody. It is meant for deprecation later, once\n * moving off it is a one-line change rather than a surprise.\n */\n static configure(config: TolinkuConfig): void {\n Tolinku.init(config);\n }\n\n /**\n * Removes the automatic link listener, when one was installed.\n *\n * Held here rather than inside Analytics because it is a property of this\n * configuration: destroy() has to take it back down or a reconfigured SDK\n * reports every link twice.\n */\n private static linkSubscription: EmitterSubscription | null = null;\n\n static init(config: TolinkuConfig): void {\n if (!config.apiKey) throw new Error('Tolinku: apiKey is required');\n\n // Double-init guard: warn and return if already configured\n if (Tolinku._initialized) {\n debugWarn(\n 'Tolinku.init() called while already initialized. ' +\n 'Call Tolinku.destroy() first if you need to reconfigure.'\n );\n // Also log to console even without debug mode, since this is a potential bug\n console.warn(\n '[TolinkuSDK] init() called while already initialized. ' +\n 'Call Tolinku.destroy() first if you need to reconfigure.'\n );\n return;\n }\n\n // Resolve defaults\n const baseUrl = config.baseUrl || 'https://api.tolinku.com';\n\n // Validate HTTPS\n validateBaseUrl(baseUrl);\n\n // Enable/disable debug logging\n setDebugEnabled(config.debug === true);\n\n const resolvedConfig: ResolvedTolinkuConfig = {\n apiKey: config.apiKey,\n baseUrl,\n debug: config.debug === true,\n timeout: config.timeout ?? 30000,\n };\n\n // Namespace storage keys by API key\n setStorageNamespace(config.apiKey);\n\n Tolinku.client = new HttpClient(resolvedConfig);\n Tolinku.analyticsInstance = new Analytics(Tolinku.client);\n Tolinku.ecommerceInstance = new Ecommerce(Tolinku.client, () => Tolinku._userId);\n Tolinku.referralsInstance = new Referrals(Tolinku.client);\n Tolinku.deferredInstance = new Deferred(Tolinku.client);\n Tolinku.linksInstance = new Links(Tolinku.client);\n Tolinku._initialized = true;\n\n if (config.autoTrackLinkOpens === true) Tolinku.startAutoLinkTracking();\n\n debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);\n }\n\n /**\n * Report incoming links without the app wiring anything.\n *\n * A link arrives in two places and both need reporting: one that launches the\n * app cold arrives at getInitialURL, one tapped while it is already running\n * arrives at the listener. Instrumenting only the second is the common\n * mistake, because it works in every test done by hand with the app open.\n *\n * Both are wired, and the same link arriving at both inside a few seconds is\n * reported once: trackLinkOpen drops a repeat of the same URL, which is why\n * covering both here is safe rather than double counting.\n */\n private static startAutoLinkTracking(): void {\n Linking.getInitialURL()\n .then((url) => { if (url) void Tolinku.trackLinkOpen(url); })\n .catch(() => { /* a link that cannot be read is not worth a crash at launch */ });\n\n Tolinku.linkSubscription = Linking.addEventListener('url', ({ url }) => {\n if (url) void Tolinku.trackLinkOpen(url);\n });\n }\n\n /** Check whether the SDK has been initialized. */\n static isConfigured(): boolean {\n return Tolinku._initialized;\n }\n\n /**\n * Set the user ID for segment targeting and analytics attribution.\n * Pass null to clear the user ID.\n */\n static setUserId(userId: string | null): void {\n Tolinku._userId = userId;\n }\n\n /** Get the current user ID, or null if not set. */\n static getUserId(): string | null {\n return Tolinku._userId;\n }\n\n /** Get the underlying HTTP client (used internally by MessageProvider) */\n static getClient(): HttpClient {\n if (!Tolinku.client) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.client;\n }\n\n /**\n * Track a custom event (shorthand for analytics.track).\n * Event type is auto-prefixed with \"custom.\" if not already.\n * Events are batched and flushed automatically.\n */\n static async track(eventType: string, properties?: TrackProperties): Promise<void> {\n if (!Tolinku.analyticsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n const mergedProps = Tolinku._userId\n ? { user_id: Tolinku._userId, ...properties }\n : properties;\n return Tolinku.analyticsInstance.track(eventType, mergedProps);\n }\n\n /**\n * Report that a link opened the app, when it opened without the browser.\n *\n * A Universal Link or App Link hands the app the URL directly, so Tolinku is\n * never contacted and the tap goes unrecorded. Those taps come from people who\n * already have your app, so leaving them out makes a re-engagement campaign\n * look like a failure exactly when it worked.\n *\n * Both ways a link arrives need it. The listener fires only while the app is\n * already running, so a link that launched the app cold arrives separately:\n *\n * ```ts\n * // Launched by a link, app was not running.\n * const initial = await Linking.getInitialURL();\n * if (initial) Tolinku.trackLinkOpen(initial);\n *\n * // Tapped while the app was already open.\n * Linking.addEventListener('url', ({ url }) => {\n * Tolinku.trackLinkOpen(url);\n * // your own routing\n * });\n * ```\n *\n * Wiring both is safe: the same link arriving twice in quick succession is\n * reported once.\n *\n * Only http and https links are reported. A custom scheme means Tolinku's own\n * hand-off page opened the app, and that tap is already counted.\n *\n * Never throws.\n */\n static async trackLinkOpen(url: string, deferred = false): Promise<void> {\n // Unlike track, a missing instance is not worth throwing over: this sits on\n // the path that routes the user somewhere.\n if (!Tolinku.analyticsInstance) return;\n return Tolinku.analyticsInstance.trackLinkOpen(url, Tolinku._userId ?? undefined, deferred);\n }\n\n /**\n * Immediately flush all queued analytics and ecommerce events to the server.\n */\n static async flush(): Promise<void> {\n if (!Tolinku.analyticsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n await Promise.all([\n Tolinku.analyticsInstance.flush(),\n Tolinku.ecommerceInstance?.flush(),\n ]);\n }\n\n /** Ecommerce: track purchases, carts, products, revenue */\n static get ecommerce(): Ecommerce {\n if (!Tolinku.ecommerceInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.ecommerceInstance;\n }\n\n /** Referrals: create, complete, milestone, leaderboard, claimReward */\n static get referrals(): Referrals {\n if (!Tolinku.referralsInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.referralsInstance;\n }\n\n /** Deferred deep links: claimByToken, claimBySignals */\n static get deferred(): Deferred {\n if (!Tolinku.deferredInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.deferredInstance;\n }\n\n /**\n * Turning a link the app was handed into the route and token it means.\n *\n * Needed for short links, which arrive as an opaque code that nothing on the\n * device can interpret. See {@link Links.resolve}.\n */\n static get links(): Links {\n if (!Tolinku.linksInstance) {\n throw new Error('Tolinku: SDK not initialized. Call Tolinku.init() first.');\n }\n return Tolinku.linksInstance;\n }\n\n /**\n * Shut down the SDK and release resources.\n * Flushes remaining analytics events, cancels timers, removes listeners,\n * and aborts in-flight requests. After calling this, you must call init()\n * again before using the SDK.\n */\n static async destroy(): Promise<void> {\n debugLog('Tolinku SDK shutting down');\n\n // Flush and clean up analytics + ecommerce (timers, AppState listeners)\n if (Tolinku.analyticsInstance) {\n await Tolinku.analyticsInstance.destroy();\n }\n if (Tolinku.ecommerceInstance) {\n await Tolinku.ecommerceInstance.destroy();\n }\n\n // Abort all in-flight HTTP requests\n if (Tolinku.client) {\n Tolinku.client.abort();\n }\n\n // Reset storage namespace\n resetStorageNamespace();\n\n if (Tolinku.linkSubscription) {\n Tolinku.linkSubscription.remove();\n Tolinku.linkSubscription = null;\n }\n\n // Clear all references\n Tolinku.client = null;\n Tolinku.analyticsInstance = null;\n Tolinku.ecommerceInstance = null;\n Tolinku.referralsInstance = null;\n Tolinku.deferredInstance = null;\n Tolinku.linksInstance = null;\n Tolinku._initialized = false;\n Tolinku._userId = null;\n\n // Reset debug mode\n setDebugEnabled(false);\n }\n}\n","import React from 'react';\nimport {\n Text,\n View,\n Image,\n TouchableOpacity,\n ImageBackground,\n Linking,\n type TextStyle,\n type ViewStyle,\n type ImageStyle,\n} from 'react-native';\nimport type { MessageAppContext, MessageComponent, ShowMessageOptions } from '../types';\nimport { isSafeActionUrl, isSafeUrl } from '../validation';\nimport { debugWarn } from '../debug';\n\n/** The only two shapes React Native lays out: a number, or a percentage. */\ntype Size = number | `${number}%`;\n\n/** What an Image is given when it has neither a height nor a measurable one. */\nconst DEFAULT_IMAGE_HEIGHT: Size = 200;\n\n/**\n * Turn a dimension the message builder wrote into one React Native accepts.\n *\n * The builder's width and height are free text: \"100%\", \"200\", \"200px\" and\n * \"auto\" are all things it invites people to type. React Native takes a number\n * or a percentage string and nothing else, so \"200\" and \"200px\" are not sizes\n * to it, they are mistakes. A view given one lays out at zero, which for an\n * image means it renders and cannot be seen, with the rest of the message\n * looking perfectly fine around the hole.\n *\n * \"auto\" and anything unreadable return undefined, which callers read as \"no\n * opinion\" and size from the content instead.\n */\nexport function dimension(raw: unknown): Size | undefined {\n if (typeof raw === 'number' && isFinite(raw) && raw > 0) return raw;\n if (typeof raw !== 'string') return undefined;\n\n const value = raw.trim();\n if (!value) return undefined;\n if (value.endsWith('%')) {\n return /^\\d+(?:\\.\\d+)?%$/.test(value) ? (value as Size) : undefined;\n }\n\n // Only digits, with an optional px, are a size anyone meant. parseInt would\n // also read \"20rem\" as 20, which is not what was asked for.\n const match = /^(\\d+(?:\\.\\d+)?)(?:px)?$/i.exec(value);\n if (!match) {\n debugWarn(`Dimension \"${raw}\" is not a size React Native understands; ignoring it.`);\n return undefined;\n }\n const parsed = parseFloat(match[1]!);\n return parsed > 0 ? parsed : undefined;\n}\n\n/**\n * A number the author set, which may legitimately be zero.\n *\n * `props.x || fallback` throws away a deliberate 0, and 0 is exactly what an\n * author picks for a square corner or a flush edge. Every stock message\n * template sets borderRadius: 0 on its images, so the old form rounded the\n * corners of every one of them on device only.\n */\nexport function num(raw: unknown, fallback: number): number {\n if (typeof raw === 'number' && isFinite(raw)) return raw;\n if (typeof raw === 'string' && raw.trim()) {\n const parsed = parseFloat(raw);\n if (isFinite(parsed)) return parsed;\n }\n return fallback;\n}\n\n/** One of the alignments the builder offers, never whatever content carried. */\nfunction alignment(raw: unknown): TextStyle['textAlign'] {\n return raw === 'center' || raw === 'right' || raw === 'justify' ? raw : 'left';\n}\n\n/**\n * The colour names React Native knows, which it matches case sensitively.\n *\n * The builder's colour fields are free text in a browser, where names are\n * case insensitive and the set is larger, so this is where the two disagree.\n */\nconst NAMED_COLORS = new Set([\n 'transparent', 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque',\n 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',\n 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan',\n 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen',\n 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',\n 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue',\n 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia',\n 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey',\n 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush',\n 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow',\n 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',\n 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime',\n 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid',\n 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise',\n 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy',\n 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen',\n 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue',\n 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',\n 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey',\n 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet',\n 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen',\n]);\n\n/**\n * A colour React Native can actually parse, or the fallback.\n *\n * The builder's colour fields are free text with no picker, so a browser form\n * anything CSS accepts: `rgb(0 0 0 / 50%)`, `hsl(210 40% 98%)`, `color-mix()`,\n * `var(--brand)`. React Native understands a much smaller set and simply drops\n * what it cannot read, which for a button background means a white button with\n * a white label, an invisible call to action rather than an ugly one.\n */\nexport function color(raw: unknown, fallback: string): string {\n if (typeof raw !== 'string') return fallback;\n const value = raw.trim();\n if (!value) return fallback;\n\n if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) return value;\n // The comma forms only, and no percentage alpha: React Native understands\n // neither the CSS space syntax, rgb(0 0 0 / 50%), nor rgba(0,0,0,50%).\n if (/^(?:rgb|rgba|hsl|hsla)\\(\\s*[\\d.]+\\s*,[^)%]*\\)$/i.test(value)) return value;\n // Named colours, matched against the set React Native actually knows and\n // lowercased first. Its table is case sensitive, so an author who types\n // \"Red\", sees it in the browser preview and passes a case-insensitive check\n // gets nothing on the device: the exact silent failure this guards against.\n if (NAMED_COLORS.has(value.toLowerCase())) return value.toLowerCase();\n\n debugWarn(`Colour \"${raw}\" is not one React Native can read; using ${fallback}.`);\n return fallback;\n}\n\n/**\n * The \"soft\" button variant's tint.\n *\n * Only a hex colour can be tinted by appending an alpha, and a soft button\n * draws its label in the untinted colour. So when the tint cannot be applied,\n * the label and the background are the same colour and the button reads as an\n * empty block. Anything else falls back to filled, which is readable.\n */\nfunction softVariant(hex: string): string | null {\n if (/^#[0-9a-f]{6}$/i.test(hex)) return `${hex}22`;\n // A three digit hex has to be expanded first: \"#abc\" + \"22\" is five digits,\n // which is not a colour in any form, so the tint would be dropped and the\n // button would lose its background entirely.\n if (/^#[0-9a-f]{3}$/i.test(hex)) {\n const [, r, g, b] = hex;\n return `#${r}${r}${g}${g}${b}${b}22`;\n }\n return null;\n}\n\n/**\n * Render the [text](url) links the TextBlock field promises.\n *\n * The field label says \"Markdown links supported\" and the builder preview\n * draws them, so an author has every reason to believe they work. Only the\n * preview did: everywhere else the brackets and the raw URL were shown to the\n * end user as text.\n */\nfunction richText(text: string, onPressUrl: (url: string) => void): React.ReactNode {\n if (!text) return '';\n const regex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const parts: React.ReactNode[] = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n let key = 0;\n\n while ((match = regex.exec(text)) !== null) {\n if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index));\n const [full, label, rawUrl] = match;\n const url = (rawUrl || '').trim();\n if (isSafeActionUrl(url)) {\n parts.push(\n <Text\n key={`link-${key++}`}\n style={{ textDecorationLine: 'underline' }}\n onPress={() => onPressUrl(url)}\n >\n {label}\n </Text>,\n );\n } else {\n parts.push(full);\n }\n lastIndex = regex.lastIndex;\n }\n if (lastIndex < text.length) parts.push(text.slice(lastIndex));\n return parts.length === 1 ? parts[0] : parts;\n}\n\n/**\n * The proportions of a remote image, once the platform can tell us.\n *\n * React Native cannot know them without asking, and asking is asynchronous, so\n * a caller gets null until the answer arrives and lays out from a fallback in\n * the meantime. `enabled` exists because measuring costs a request and is\n * pointless when the size is already known.\n */\nfunction useImageRatio(uri: string, enabled: boolean): number | null {\n const [ratio, setRatio] = React.useState<number | null>(null);\n\n React.useEffect(() => {\n if (!enabled || !uri) return;\n let cancelled = false;\n Image.getSize(\n uri,\n (w, h) => {\n // Guarded so a slow answer cannot set state on an unmounted message,\n // which is a warning in development and a leak in production.\n if (!cancelled && w > 0 && h > 0) setRatio(w / h);\n },\n () => {\n // Unreachable, or something the platform cannot measure. Callers fall\n // back rather than render nothing.\n },\n );\n return () => {\n cancelled = true;\n };\n }, [uri, enabled]);\n\n return ratio;\n}\n\n/**\n * An image sized the way the builder means it.\n *\n * A height left empty means natural proportions, not a fixed box. Picking a\n * number instead is how a 44px icon ends up as a 44 by 200 strip with its\n * middle cropped out, which is what every template icon looked like.\n */\nfunction MessageImage({\n uri,\n width,\n height,\n borderRadius,\n borderWidth,\n borderColor,\n alt,\n}: {\n uri: string;\n width: Size | undefined;\n height: Size | undefined;\n borderRadius: number;\n borderWidth: number;\n borderColor: string;\n alt: string;\n}): React.ReactElement {\n const wantsNaturalHeight = height === undefined;\n const ratio = useImageRatio(uri, wantsNaturalHeight);\n\n const style: ImageStyle = {\n width: width ?? '100%',\n borderRadius,\n alignSelf: 'center',\n marginBottom: 8,\n ...(borderWidth > 0 ? { borderWidth, borderColor } : {}),\n ...(wantsNaturalHeight\n ? ratio\n ? { aspectRatio: ratio }\n : { height: DEFAULT_IMAGE_HEIGHT }\n : { height }),\n };\n\n return (\n <Image\n source={{ uri }}\n style={style}\n // Contain while the proportions are still unknown, so a measurement that\n // never arrives leaves the picture whole rather than cropped.\n resizeMode={wantsNaturalHeight && !ratio ? 'contain' : 'cover'}\n accessibilityLabel={alt}\n />\n );\n}\n\n/**\n * One store badge, at the height the author asked for.\n *\n * A remote image in React Native needs both dimensions, so the width comes\n * from the badge's own proportions rather than a number written here. Apple's\n * and Google's artwork are close but not identical (3.47 against 3.46), and\n * either way a guess shows as a badge slightly shorter than asked for, since\n * \"contain\" shrinks it to fit whatever box it is given.\n */\nfunction StoreBadge({\n uri,\n height,\n label,\n onPress,\n}: {\n uri: string | undefined;\n height: number;\n label: string;\n onPress: () => void;\n}): React.ReactElement {\n const usable = !!uri && isSafeUrl(uri);\n const ratio = useImageRatio(usable ? uri! : '', usable);\n // A badge is artwork, not a layout choice: a height of zero is not a smaller\n // badge, it is no badge, so the authored value is floored rather than obeyed.\n const usableHeight = height > 0 ? height : 44;\n\n return (\n <TouchableOpacity onPress={onPress} activeOpacity={0.7} accessibilityRole=\"button\">\n {usable ? (\n <Image\n source={{ uri: uri! }}\n // Until measured, a badge-shaped box. Both stores' artwork is within\n // a percent of this, so the correction on arrival is imperceptible.\n style={{ height: usableHeight, width: usableHeight * (ratio || 3.47), marginHorizontal: 6 }}\n resizeMode=\"contain\"\n accessibilityLabel={label}\n />\n ) : (\n // A text link rather than a blank space, for the case where the badge\n // artwork itself cannot be loaded.\n <Text style={{ color: '#1B1B1B', fontSize: 15, fontWeight: '600', marginHorizontal: 6 }}>{label}</Text>\n )}\n </TouchableOpacity>\n );\n}\n\n/** The component types this renderer draws. */\nconst SUPPORTED = new Set([\n 'Heading',\n 'TextBlock',\n 'Image',\n 'Button',\n 'DeepLinkButton',\n 'Section',\n 'Spacer',\n 'Divider',\n 'AppIcon',\n 'StoreButtons',\n]);\n\n/**\n * Whether anything in this content would actually draw.\n *\n * A message saved before the builder's palette was narrowed can be made\n * entirely of components this renderer skips, and skipping all of them leaves\n * an empty card with a close button. Asking first lets the message fall back\n * to its title and body instead.\n */\nexport function drawsAnything(\n content: MessageComponent[] | undefined,\n app?: MessageAppContext | null,\n): boolean {\n return (content || []).some(c => {\n if (!c || !SUPPORTED.has(c.type)) return false;\n const props = (c.props || {}) as Record<string, unknown>;\n // A few components draw only when something outside the content exists.\n // Counting them regardless is how an empty card came back.\n if (c.type === 'Image') return isSafeUrl((props.url as string) || '');\n if (c.type === 'DeepLinkButton') return !!app?.deep_link_url;\n if (c.type === 'StoreButtons') {\n const ios = props.showIos !== false && ((props.iosUrlOverride as string) || app?.ios_store_url);\n const android = props.showAndroid !== false && ((props.androidUrlOverride as string) || app?.android_store_url);\n return !!(ios || android);\n }\n return true;\n });\n}\n\n/**\n * How deep a section may nest before the renderer stops following zones.\n *\n * A zone can name a section that contains itself, directly or through another.\n * React's work loop is iterative, so that is not a stack overflow: it is an\n * app that allocates until it is killed, with no error and nothing on screen.\n * Content saved before any of this was validated can be shaped that way, so\n * the renderer refuses to follow it forever rather than trusting what it is\n * handed.\n */\nconst MAX_SECTION_DEPTH = 20;\n\nexport interface RenderOptions extends ShowMessageOptions {\n /** Section children, keyed \"<component id>:content\", as Puck stores them. */\n zones?: Record<string, MessageComponent[]>;\n /** The app the message belongs to, for the components that describe it. */\n app?: MessageAppContext | null;\n /** Dismiss the message. A button action of \"close\" calls this. */\n onRequestClose?: () => void;\n /** How many sections deep this render already is. Internal. */\n depth?: number;\n}\n\ninterface ComponentRendererProps {\n component: MessageComponent;\n messageId: string;\n options: RenderOptions;\n}\n\nexport function PuckComponentRenderer({ component, messageId, options }: ComponentRendererProps): React.ReactElement | null {\n // Content is a network response, not something this package produced, so a\n // malformed entry is skipped rather than allowed to throw mid-render. There\n // is no error boundary in a host app: a throw here is a blank screen.\n if (!component || typeof component !== 'object' || typeof component.type !== 'string') return null;\n const props = component.props && typeof component.props === 'object' ? component.props : {};\n const app = options.app;\n\n /** Open a URL the way the host app asked us to, or the way the OS would. */\n const follow = (url: string) => {\n if (options.onButtonPress) options.onButtonPress(url, messageId);\n else Linking.openURL(url).catch(() => {});\n };\n\n switch (component.type) {\n case 'Heading': {\n const fontSize = num(props.fontSize, 28);\n const style: TextStyle = {\n fontSize,\n fontWeight: '700',\n color: color(props.color, '#1B1B1B'),\n textAlign: alignment(props.alignment),\n lineHeight: fontSize * 1.2,\n marginBottom: 8,\n };\n return <Text style={style}>{(props.text as string) || ''}</Text>;\n }\n\n case 'TextBlock': {\n const fontSize = num(props.fontSize, 15);\n const style: TextStyle = {\n fontSize,\n color: color(props.color, '#555555'),\n textAlign: alignment(props.alignment),\n lineHeight: fontSize * 1.5,\n marginBottom: 8,\n };\n return <Text style={style}>{richText((props.content as string) || '', follow)}</Text>;\n }\n\n case 'Image': {\n const imageUrl = (props.url as string) || '';\n\n if (!imageUrl || !imageUrl.trim()) {\n debugWarn('Image component has empty URL, skipping render.');\n return null;\n }\n if (!isSafeUrl(imageUrl)) {\n debugWarn(`Image URL blocked (unsafe protocol): ${imageUrl}`);\n return null;\n }\n\n return (\n <MessageImage\n uri={imageUrl}\n width={dimension(props.width) ?? '100%'}\n height={dimension(props.height)}\n borderRadius={num(props.borderRadius, 8)}\n borderWidth={num(props.borderWidth, 0)}\n borderColor={color(props.borderColor, '#1B1B1B')}\n alt={(props.alt as string) || ''}\n />\n );\n }\n\n case 'Button':\n case 'DeepLinkButton': {\n const isDeepLink = component.type === 'DeepLinkButton';\n // A deep link button opens the app's own link, which the message content\n // has no way to know; it comes with the app context.\n const action = isDeepLink ? app?.deep_link_url || '' : (props.action as string) || '';\n const label = isDeepLink\n ? (props.label as string) || 'Open in App'\n : (props.label as string) || '';\n\n // A deep link button with nowhere to point is a dead control, so it is\n // left out rather than drawn.\n if (isDeepLink && !action) return null;\n\n const handlePress = () => {\n if (!action) return;\n\n // \"close\" is an action the builder offers and the WebView renderer has\n // always honoured. Here it used to fail the URL check and do nothing,\n // so a dismiss button left the message on screen.\n if (action === 'close') {\n options.onRequestClose?.();\n return;\n }\n\n // Checked before either path, including the caller's own handler. The\n // URL comes from message content, and a handler is ordinary app code\n // that will reasonably pass it to Linking.openURL without looking.\n if (!isSafeActionUrl(action)) {\n debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);\n return;\n }\n\n follow(action);\n };\n\n const variant = (props.style as string) || 'filled';\n const isOutline = variant === 'outline';\n const tint = variant === 'soft' ? softVariant(color(props.bgColor, '#1B1B1B')) : null;\n const isSoft = tint !== null;\n const baseColor = color(props.bgColor, '#1B1B1B');\n const background = isOutline ? 'transparent' : isSoft ? tint! : baseColor;\n const labelColor = isOutline || isSoft ? baseColor : color(props.textColor, '#ffffff');\n\n const containerStyle: ViewStyle = {\n backgroundColor: background,\n borderRadius: num(props.borderRadius, 8),\n paddingVertical: 12,\n paddingHorizontal: 24,\n marginVertical: 8,\n alignItems: 'center',\n ...(isOutline ? { borderWidth: 2, borderColor: baseColor } : {}),\n // A button that is not full width is a compact, centred one. Without\n // alignSelf it stretches to the column anyway, which made the setting\n // do nothing at all.\n ...(props.fullWidth ? { width: '100%' as const } : { alignSelf: 'center' as const }),\n };\n\n const textStyle: TextStyle = {\n color: labelColor,\n fontSize: num(props.fontSize, 16),\n fontWeight: '600',\n };\n\n const emoji = (props.emoji as string) || '';\n\n return (\n <TouchableOpacity onPress={handlePress} style={containerStyle} activeOpacity={0.7}>\n <Text style={textStyle}>{emoji ? `${emoji} ${label}` : label}</Text>\n </TouchableOpacity>\n );\n }\n\n case 'Section': {\n // Puck stores a drop zone's children under \"<component id>:content\" at\n // the top level of the content, never in props.children. Reading\n // props.children rendered every Section as an empty box and lost\n // everything an author put inside it.\n // An id-less section would read the literal key \"undefined:content\" and\n // share its children with every other id-less section in the message.\n const sectionId = typeof props.id === 'string' && props.id ? props.id : null;\n const depth = options.depth || 0;\n const children =\n sectionId && depth < MAX_SECTION_DEPTH ? options.zones?.[`${sectionId}:content`] || [] : [];\n\n const containerStyle: ViewStyle = {\n backgroundColor: typeof props.bgColor === 'string' && props.bgColor\n ? color(props.bgColor, 'transparent')\n : undefined,\n padding: num(props.padding, 16),\n borderRadius: num(props.borderRadius, 0),\n marginVertical: 8,\n };\n\n const content = children.map((child, index) => (\n <PuckComponentRenderer\n key={`${messageId}-section-${index}-${child?.type}`}\n component={child}\n messageId={messageId}\n options={{ ...options, depth: depth + 1 }}\n />\n ));\n\n const bgImage = (props.bgImage as string) || '';\n if (bgImage) {\n if (!isSafeUrl(bgImage)) {\n debugWarn(`Section background image URL blocked (unsafe protocol): ${bgImage}`);\n return <View style={containerStyle}>{content}</View>;\n }\n\n return (\n <ImageBackground\n source={{ uri: bgImage }}\n style={containerStyle}\n resizeMode={(props.bgSize as string) === 'contain' ? 'contain' : 'cover'}\n imageStyle={{ borderRadius: num(props.borderRadius, 0) }}\n >\n {content}\n </ImageBackground>\n );\n }\n\n return <View style={containerStyle}>{content}</View>;\n }\n\n case 'Spacer':\n return <View style={{ height: num(props.height, 24) }} />;\n\n case 'Divider':\n return (\n <View\n style={{\n borderTopWidth: num(props.thickness, 1),\n borderTopColor: color(props.color, '#e5e5e5'),\n marginVertical: 8,\n }}\n />\n );\n\n case 'AppIcon': {\n const size = num(props.size, 80);\n const borderRadius = num(props.borderRadius, 16);\n const iconUrl = app?.icon_url || '';\n\n // A placeholder rather than a hole. The author put an icon here, and an\n // app with no logo set is a setting to fix, not a reason to render a\n // message with a gap in it.\n if (!iconUrl || !isSafeUrl(iconUrl)) {\n return (\n <View\n style={{ width: size, height: size, borderRadius, backgroundColor: '#f0f0f0', alignSelf: 'center', marginBottom: 8 }}\n />\n );\n }\n\n return (\n <Image\n source={{ uri: iconUrl }}\n style={{ width: size, height: size, borderRadius, alignSelf: 'center', marginBottom: 8 }}\n resizeMode=\"cover\"\n accessibilityLabel={app?.name || 'App icon'}\n />\n );\n }\n\n case 'StoreButtons': {\n const iosUrl = (props.iosUrlOverride as string) || app?.ios_store_url || '';\n const androidUrl = (props.androidUrlOverride as string) || app?.android_store_url || '';\n const showIos = props.showIos !== false && !!iosUrl;\n const showAndroid = props.showAndroid !== false && !!androidUrl;\n if (!showIos && !showAndroid) return null;\n\n const height = num(props.height, 44);\n const alignment = props.alignment as string;\n const justifyContent =\n alignment === 'left' ? 'flex-start' : alignment === 'right' ? 'flex-end' : 'center';\n\n // The badges are the official artwork, sent with the app context so the\n // SDK is not guessing an origin or a file name.\n return (\n <View style={{ flexDirection: 'row', justifyContent, alignItems: 'center', flexWrap: 'wrap', marginVertical: 8 }}>\n {showIos ? (\n <StoreBadge\n key=\"ios\"\n uri={app?.ios_badge_url}\n height={height}\n label=\"Download on the App Store\"\n onPress={() => follow(iosUrl)}\n />\n ) : null}\n {showAndroid ? (\n <StoreBadge\n key=\"android\"\n uri={app?.android_badge_url}\n height={height}\n label=\"Get it on Google Play\"\n onPress={() => follow(androidUrl)}\n />\n ) : null}\n </View>\n );\n }\n\n default:\n debugWarn(`Message component \"${component.type}\" is not supported here; skipping it.`);\n return null;\n }\n}\n","import React from 'react';\nimport {\n Modal,\n View,\n TouchableOpacity,\n Pressable,\n ScrollView,\n Text,\n StyleSheet,\n} from 'react-native';\nimport type { Message, MessageAppContext, ShowMessageOptions } from '../types';\nimport { saveMessageDismissal } from '../storage';\nimport { PuckComponentRenderer, color, num, drawsAnything } from './components';\n\ninterface MessageModalProps {\n message: Message | null;\n visible: boolean;\n onClose: () => void;\n options: ShowMessageOptions;\n app?: MessageAppContext | null;\n}\n\n/**\n * The colour a gradient starts with.\n *\n * React Native has no gradient without a native module this package will not\n * pull in, and five of the stock message templates are designed on one. Left\n * alone they arrive as a plain white card. The first stop is a much closer\n * likeness than white, so the message still looks like the thing that was\n * designed.\n */\nfunction gradientStartColor(gradient: unknown): string | null {\n if (typeof gradient !== 'string' || !gradient) return null;\n const match = /#[0-9a-f]{3,8}|rgba?\\([^)]*\\)/i.exec(gradient);\n if (!match) return null;\n // Checked like any other colour: the pattern above will happily match a\n // five digit hex or the space syntax, both of which React Native drops,\n // leaving a card with no background at all.\n const validated = color(match[0], '');\n return validated || null;\n}\n\nexport function MessageModal({ message, visible, onClose, options, app }: MessageModalProps): React.ReactElement {\n if (!message) {\n return <></>;\n }\n\n const handleDismiss = async () => {\n await saveMessageDismissal(message.id);\n options.onDismiss?.(message.id);\n onClose();\n };\n\n const rootProps = (message.content?.root?.props || {}) as Record<string, unknown>;\n\n // Root background: what the author set on the message surface, then the\n // message's own colour field, then white. All of it was ignored before, so a\n // message designed on a gradient arrived as a plain white card.\n // The gradient wins over the colour, which is what CSS does for the same\n // pair and therefore what the preview and the WebView show. It matters\n // because the builder writes bgColor: '#ffffff' into every saved root, so\n // reading the colour first meant a gradient message was always white here.\n const background =\n gradientStartColor(rootProps.bgGradient) ||\n (typeof rootProps.bgColor === 'string' && rootProps.bgColor ? color(rootProps.bgColor, '') : '') ||\n message.background_color ||\n '#ffffff';\n\n const cardStyle = {\n backgroundColor: background,\n padding: Math.max(0, num(rootProps.padding, 20)),\n // Clamped, unlike the other authored numbers. A padding of zero is a\n // choice; a width of zero is the whole message gone, and the field's own\n // minimum is zero. The bounds and the default match the server renderer.\n maxWidth: Math.min(2000, Math.max(100, num(rootProps.contentWidth, 480))),\n };\n\n const content = message.content?.content || [];\n\n // A message may carry only a title and a body, with nothing designed in the\n // builder at all, and one saved before the palette was narrowed may be made\n // entirely of components this renderer skips. Either way the card used to\n // come up empty but for its close button.\n const hasDesignedContent = drawsAnything(content, app);\n\n return (\n <Modal\n visible={visible}\n transparent\n animationType=\"fade\"\n onRequestClose={handleDismiss}\n >\n <Pressable style={styles.overlay} onPress={handleDismiss}>\n <Pressable style={[styles.card, cardStyle]} onPress={() => {}}>\n <TouchableOpacity\n onPress={handleDismiss}\n style={styles.closeButton}\n accessibilityLabel=\"Close message\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeText}>{'\\u00d7'}</Text>\n </TouchableOpacity>\n\n <ScrollView\n style={styles.scrollContent}\n showsVerticalScrollIndicator={false}\n >\n {hasDesignedContent ? (\n content.map((component, index) => (\n <PuckComponentRenderer\n key={`${message.id}-${index}-${component.type}`}\n component={component}\n messageId={message.id}\n options={{\n ...options,\n zones: message.content?.zones,\n app,\n onRequestClose: handleDismiss,\n }}\n />\n ))\n ) : (\n <>\n {message.title ? <Text style={styles.fallbackTitle}>{message.title}</Text> : null}\n {message.body ? <Text style={styles.fallbackBody}>{message.body}</Text> : null}\n </>\n )}\n </ScrollView>\n </Pressable>\n </Pressable>\n </Modal>\n );\n}\n\nconst styles = StyleSheet.create({\n overlay: {\n flex: 1,\n backgroundColor: 'rgba(0,0,0,0.5)',\n alignItems: 'center',\n justifyContent: 'center',\n },\n card: {\n position: 'relative',\n width: '90%',\n maxHeight: '80%',\n borderRadius: 16,\n shadowColor: '#000',\n shadowOffset: { width: 0, height: 20 },\n shadowOpacity: 0.3,\n shadowRadius: 30,\n elevation: 10,\n },\n closeButton: {\n position: 'absolute',\n top: 12,\n right: 12,\n zIndex: 10,\n backgroundColor: 'rgba(0,0,0,0.1)',\n borderRadius: 14,\n width: 28,\n height: 28,\n alignItems: 'center',\n justifyContent: 'center',\n },\n closeText: {\n fontSize: 18,\n lineHeight: 20,\n opacity: 0.6,\n },\n scrollContent: {\n marginTop: 8,\n },\n // Used only when a message has no designed content, so its title and body\n // are all there is to show.\n fallbackTitle: {\n fontSize: 20,\n fontWeight: '700',\n color: '#1B1B1B',\n marginBottom: 8,\n },\n fallbackBody: {\n fontSize: 15,\n lineHeight: 22,\n color: '#555555',\n },\n});\n","import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react';\nimport type { Message, MessageAppContext, ShowMessageOptions } from '../types';\nimport { isMessageDismissed, isMessageSuppressed, recordMessageImpression } from '../storage';\nimport { MessageModal } from './MessageModal';\nimport { Tolinku } from '../Tolinku';\nimport { debugWarn } from '../debug';\n\ninterface TolinkuMessagesProps {\n /** The trigger type to filter messages by (e.g. \"milestone\", \"event\") */\n trigger?: string;\n /** The trigger value to match (e.g. \"installed\", \"first_purchase\") */\n triggerValue?: string;\n /** Called when a message is dismissed */\n onDismiss?: (messageId: string) => void;\n /** Called when a button in the message is pressed */\n onButtonPress?: (action: string, messageId: string) => void;\n}\n\n/**\n * React component that fetches and displays in-app messages as a modal overlay.\n *\n * Place this component anywhere in your component tree. It will automatically\n * fetch messages matching the given trigger and display the highest-priority\n * non-dismissed message.\n *\n * Example:\n * <TolinkuMessages trigger=\"milestone\" triggerValue=\"installed\" />\n */\nexport function TolinkuMessages({\n trigger,\n triggerValue,\n onDismiss,\n onButtonPress,\n}: TolinkuMessagesProps): React.ReactElement {\n const [message, setMessage] = useState<Message | null>(null);\n const [visible, setVisible] = useState(false);\n // Sent alongside the messages: AppIcon, StoreButtons and DeepLinkButton\n // describe the app rather than the message, so the content cannot draw them.\n const [app, setApp] = useState<MessageAppContext | null>(null);\n\n // Stabilize callback refs so they don't trigger re-fetches\n const onDismissRef = useRef(onDismiss);\n onDismissRef.current = onDismiss;\n const onButtonPressRef = useRef(onButtonPress);\n onButtonPressRef.current = onButtonPress;\n\n // Memoize the options object to avoid unnecessary re-renders\n const options: ShowMessageOptions = useMemo(() => ({\n trigger,\n triggerValue,\n onDismiss: (messageId: string) => onDismissRef.current?.(messageId),\n onButtonPress: (action: string, messageId: string) => onButtonPressRef.current?.(action, messageId),\n }), [trigger, triggerValue]);\n\n useEffect(() => {\n let cancelled = false;\n\n async function fetchMessages() {\n try {\n const client = Tolinku.getClient();\n const params: Record<string, string> = {};\n if (trigger) params.trigger = trigger;\n const userId = Tolinku.getUserId();\n if (userId) params.user_id = userId;\n\n const data = await client.get<{ messages: Message[]; app?: MessageAppContext }>('/v1/api/messages', params);\n if (cancelled) return;\n // Kept whether or not a message ends up shown: it belongs to the app,\n // not to any one message.\n if (data.app) setApp(data.app);\n if (!data.messages || data.messages.length === 0) return;\n\n // Filter dismissed/suppressed messages and optionally by triggerValue\n const candidates: Message[] = [];\n for (const m of data.messages) {\n if (triggerValue && m.trigger_value !== triggerValue) continue;\n const dismissed = await isMessageDismissed(m.id, m.dismiss_days);\n if (dismissed) continue;\n const suppressed = await isMessageSuppressed(m.id, m.max_impressions, m.min_interval_hours);\n if (!suppressed) candidates.push(m);\n }\n\n // Sort by priority (highest first)\n candidates.sort((a, b) => b.priority - a.priority);\n\n if (candidates.length > 0 && !cancelled) {\n await recordMessageImpression(candidates[0].id);\n setMessage(candidates[0]);\n setVisible(true);\n }\n } catch (err) {\n debugWarn(`Failed to fetch messages: ${(err as Error).message}`);\n }\n }\n\n fetchMessages();\n\n return () => {\n cancelled = true;\n };\n }, [trigger, triggerValue]);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n setMessage(null);\n }, []);\n\n return (\n <MessageModal\n message={message}\n visible={visible}\n onClose={handleClose}\n options={options}\n app={app}\n />\n );\n}\n"]}