/** * Fiskon Relay Terminal SDK for JavaScript * Works in: browsers, Node 18+, Electron (main process), React Native, Deno, Bun. Zero dependencies. * * import { Relay } from "./fiskon-relay.js"; * const relay = new Relay("YOUR_SECRET_KEY"); // server / Electron main process ONLY * const client = new Relay({ publicKey: "pk_..." }); // safe inside web pages and apps (device registration only) */ const DEFAULT_BASE = "https://relay.naweriindustries.com/api/v1"; export class RelayError extends Error { constructor({ message, code, status, data }) { super(message || "Request failed"); this.name = "RelayError"; this.code = code; // stable machine code, e.g. "insufficient_tokens" this.status = status; // HTTP status this.data = data; } } export class Relay { constructor(opts = {}) { if (typeof opts === "string") opts = { apiKey: opts }; this.apiKey = opts.apiKey; this.publicKey = opts.publicKey; this.baseUrl = (opts.baseUrl || DEFAULT_BASE).replace(/\/+$/, ""); this.timeoutMs = opts.timeoutMs || 30000; this._fetch = opts.fetch || globalThis.fetch.bind(globalThis); if (!this.apiKey && !this.publicKey) throw new Error("Relay: provide an apiKey or a publicKey"); } async _request(method, path, body, { idempotencyKey, client } = {}) { const headers = { Accept: "application/json" }; if (client && this.publicKey && !this.apiKey) headers["X-Public-Key"] = this.publicKey; else if (this.apiKey) headers["Authorization"] = `Bearer ${this.apiKey}`; else throw new Error("This call needs the secret apiKey"); if (body !== undefined) headers["Content-Type"] = "application/json"; if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey; const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), this.timeoutMs); let res; try { res = await this._fetch(this.baseUrl + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: ctl.signal }); } finally { clearTimeout(timer); } let json; try { json = await res.json(); } catch { json = { error: 1, code: "bad_response", message: `HTTP ${res.status}` }; } if (!res.ok || json.error) throw new RelayError({ message: json.message, code: json.code, status: res.status, data: json.data }); return json; } sendEmail(p, o) { return this._request("POST", "/email", p, o); } sendSms(p, o) { return this._request("POST", "/sms", p, o); } sendWhatsapp(p, o) { return this._request("POST", "/whatsapp", p, o); } sendPush(p, o) { return this._request("POST", "/push", p, o); } registerDevice(p) { return this._request("POST", "/push/devices", p, { client: true }); } removeDevice(p) { return this._request("DELETE", "/push/devices", p, { client: true }); } sendTransactional(p, o) { return this._request("POST", "/transactional/email", p, o); } templates() { return this._request("GET", "/templates"); } sendOtp(p) { return this._request("POST", "/otp", p); } verifyOtp(p) { return this._request("POST", "/otp/verify", p); } balance() { return this._request("GET", "/balance"); } status(channel, id) { return this._request("GET", `/messages/${channel}/${id}`); } } /** * Web push helper (browser only). Needs your Firebase web config + VAPID key, and a * /firebase-messaging-sw.js file on YOUR site (see the Developers page). Uses the PUBLISHABLE key. */ export async function registerWebPush({ publicKey, firebaseConfig, vapidKey, externalId, tags = [], serviceWorkerUrl = "/firebase-messaging-sw.js", baseUrl }) { if (!("serviceWorker" in navigator) || !("Notification" in window)) throw new Error("Push is not supported in this browser"); if ((await Notification.requestPermission()) !== "granted") throw new Error("Notification permission was not granted"); const { initializeApp } = await import("https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js"); const { getMessaging, getToken } = await import("https://www.gstatic.com/firebasejs/10.12.2/firebase-messaging.js"); const reg = await navigator.serviceWorker.register(serviceWorkerUrl + "?cfg=" + encodeURIComponent(JSON.stringify(firebaseConfig))); const token = await getToken(getMessaging(initializeApp(firebaseConfig)), { vapidKey, serviceWorkerRegistration: reg }); const relay = new Relay({ publicKey, baseUrl }); await relay.registerDevice({ token, platform: "web", external_id: externalId, tags }); return token; } export default Relay;