UNPKG

web-collect-events-narayana

Version:

An sdk for collecting events from web pages

203 lines (202 loc) 8.07 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const browserProfile_1 = __importDefault(require("./helpers/browserProfile")); const scrollState_1 = __importDefault(require("./helpers/scrollState")); const dateTimeIndex_1 = __importDefault(require("./helpers/dateTimeIndex")); const userId_1 = __importDefault(require("./helpers/userId")); const domNodeProfile_1 = __importDefault(require("./helpers/domNodeProfile")); const validNode_1 = require("./helpers/validNode"); const api_1 = require("./helpers/api"); class GTETWebSDK { constructor() { this.isPushNotificationScope = false; this.isCustomEventScope = false; this._data = []; this.checkScope(); this.initStorage(); console.log("GTETWebSDK started"); } initStorage() { this._data = []; } ; setData(value) { this._data.push(value); } getData() { return this._data; } ; removeData() { this._data = []; } ; checkScope() { this.isPushNotificationScope = typeof window !== "undefined" && typeof navigator !== "undefined"; this.isCustomEventScope = typeof window !== "undefined"; } handleDocumentClick(e) { const targetNode = e.target; console.log(targetNode); if ((0, validNode_1.isNodeValid)(targetNode)) { const data = { eventType: "click", browserProfile: (0, browserProfile_1.default)(), scrollState: (0, scrollState_1.default)(), dateTimeIndex: (0, dateTimeIndex_1.default)(), userId: (0, userId_1.default)(), domNodeProfile: (0, domNodeProfile_1.default)(e), }; this.setData(data); } } sendData() { const data = this.getData(); const url = `${process.env.BASE_URL}/api/v1/stream`; if (data.length > 0) { if (!url) { console.log("POST_URL environment variable is not defined."); return; } (0, api_1.postData)(url, data) .then((response) => { if (response.ok) { console.log("Data sent successfully:", data); this.removeData(); } else { console.log("Failed to perform the POST request."); } }) .catch((error) => { console.log(error); }); } } selfAnalyze(url) { if (this.isCustomEventScope) { document.addEventListener("click", this.handleDocumentClick.bind(this)); // Bind the event handler document.addEventListener("visibilitychange", () => { const formdata = new FormData(); formdata.append("data", JSON.stringify(this.getData())); navigator.sendBeacon(`${url}/api/v1/stream`, formdata); }); // Bind the event handler setInterval(this.sendData.bind(this, url), 60000); // Bind the method console.log("Self analyze started"); } else { console.log("This code is not running in a browser environment for selfAnalyze."); } } customEvent(eventName, data) { if (this.isCustomEventScope) { const dataObject = { eventType: eventName, data: data, }; this.setData(dataObject); this.sendData(); } else { console.log("This code is not running in a browser environment for customEvent."); } } pushNotification(publicVapidKey, api, swfile) { if (this.isPushNotificationScope) { if ("serviceWorker" in navigator && "PushManager" in window) { if (swfile) { this.registerServiceWorkerWithFile(swfile) .then(() => this.sendSubscriptionToServer(publicVapidKey, api)) .catch((error) => console.error("Error:", error)); } else { this.registerServiceWorkerWithoutFile() .then(() => this.sendSubscriptionToServer(publicVapidKey, api)) .catch((error) => console.error("Error:", error)); } } else { console.log("Service Worker or PushManager is not supported in this browser."); } } else { console.log("This code is not running in a browser environment for pushNotification."); } } registerServiceWorkerWithFile(swfile) { return __awaiter(this, void 0, void 0, function* () { try { const register = yield navigator.serviceWorker.register(`/${swfile}.js`, { scope: "/", }); console.log("Service Worker registered:", register); } catch (error) { console.error("Failed to register Service Worker:", error); throw error; } }); } registerServiceWorkerWithoutFile() { return __awaiter(this, void 0, void 0, function* () { try { const register = yield navigator.serviceWorker.register('https://push-notifications-narayana.s3.ap-south-1.amazonaws.com/service-worker.js', { scope: "/", }); console.log("Service Worker registered:", register); } catch (error) { console.error("Failed to register Service Worker:", error); throw error; } }); } sendSubscriptionToServer(publicVapidKey, api) { return __awaiter(this, void 0, void 0, function* () { try { const registration = yield navigator.serviceWorker.ready; const subscription = yield registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.urlBase64ToUint8Array(publicVapidKey), }); +(yield fetch(api, { method: "POST", body: JSON.stringify(subscription), headers: { "content-type": "application/json", }, })); console.log("Push Sent...", JSON.stringify(subscription)); } catch (error) { console.error("Failed to send subscription to the server:", error); throw error; } }); } urlBase64ToUint8Array(base64String) { const padding = "=".repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/\-/g, "+") .replace(/_/g, "/"); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } } exports.default = GTETWebSDK;