import { Leanbase } from './leanbase' import type { LeanbaseConfig } from './types' import { isArray } from '@posthog/core' type QueuedCall = { fn: keyof typeof api; args: any[] } const api = { _instance: null as Leanbase | null, _queue: [] as QueuedCall[], init(apiKey: string, options?: LeanbaseConfig) { this._instance = new Leanbase(apiKey, options) const q = this._queue this._queue = [] for (const { fn, args } of q) { // @ts-expect-error dynamic dispatch to API methods this[fn](...args) } }, capture(...args: Parameters['capture']>) { if (this._instance) { return this._instance.capture(...args) } this._queue.push({ fn: 'capture', args }) }, captureException(...args: Parameters['captureException']>) { if (this._instance) { return this._instance.captureException(...args) } this._queue.push({ fn: 'captureException', args }) }, identify(...args: Parameters['identify']>) { if (this._instance) { return this._instance.identify(...args) } this._queue.push({ fn: 'identify', args }) }, group(...args: Parameters['group']>) { if (this._instance) { return this._instance.group(...args) } this._queue.push({ fn: 'group', args }) }, alias(...args: Parameters['alias']>) { if (this._instance) { return this._instance.alias(...args) } this._queue.push({ fn: 'alias', args }) }, reset() { this._instance?.reset() this._instance = null }, getInstance(): Leanbase | null { return this._instance }, } // Attach to globalThis for browsers (SSR-safe guards inside Leanbase) ;(function attachToGlobal(g: Window & typeof globalThis & { leanbase?: typeof api; Leanbase?: typeof api }) { // Prefer not to overwrite if a stub already exists (e.g., user queued calls before script loaded) const existing = g.leanbase if (existing && typeof existing === 'object') { // If there is a pre-existing queue-compatible stub, try to drain it into our API if (isArray(existing._queue)) { api._queue = existing._queue as any } } g.leanbase = api // Also expose PascalCase alias for familiarity g.Leanbase = g.leanbase })(globalThis as Window & typeof globalThis) export default api