import { SDKOptions, Events } from "../types"; import { getToken, storeToken } from "../utils/session"; import { ERRORS } from "../utils/constant"; class Base { private apiKey: string; private host: string; private identifier?: string; private worker?: Worker; constructor(options: SDKOptions) { this.apiKey = options.apiKey; this.host = options.host; this.identifier = options.identifier; if (typeof window !== "undefined" && typeof Worker !== "undefined") { this.worker = new Worker(new URL("./core/worker.js", import.meta.url)); } else { console.warn("Web Workers are not available in this environment"); } } private async ensureIsAuth() { const token = getToken(); if (!token) { await this.authenticate(); } return token; } private async authenticate(): Promise { return new Promise((resolve, reject) => { if (!this.worker) { reject("Web Worker not initialized"); return; } this.worker.onmessage = event => { if (event.data.type === Events.AUTH_SUCCESS) { storeToken(event.data.token); resolve(event.data.token); } else if (event.data.type === Events.AUTH_FAILED) { reject(Events.AUTH_FAILED); } }; this.worker.postMessage({ type: Events.INITIATE_AUTHENTICATION, host: this.host, payload: { phoneNumber: this.identifier }, headers: { "x-api-key": this.apiKey }, }); }); } async sendEvent(eventType: string, data: Record) { const token = await this.ensureIsAuth(); if (this.worker) { this.worker.postMessage({ type: eventType, host: this.host, payload: { ...data }, headers: { "Member-Authorization": `Bearer ${token}`, "x-api-key": this.apiKey, }, }); } } } export default Base;