UNPKG

view-analytics-js

Version:

A lightweight JavaScript/TypeScript library to track viewing analytics for web pages, with Supabase backend integration.

75 lines (73 loc) 2.6 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { initializeAnalytics: () => initializeAnalytics, trackPageView: () => trackPageView }); module.exports = __toCommonJS(index_exports); var import_ua_parser_js = require("ua-parser-js"); var DEFAULT_BASE_URL = "https://hynflywzhfcaomlvvnwg.supabase.co/functions/v1"; var config = null; function initializeAnalytics(websiteId, baseUrl = DEFAULT_BASE_URL) { if (!websiteId) { throw new Error("Website ID is required."); } config = { baseUrl, websiteId }; } function trackPageView() { if (!config) { throw new Error("Library is not initialized. Call initializeAnalytics() first."); } const parser = new import_ua_parser_js.UAParser(); const deviceInfo = parser.getResult(); console.log("Device", deviceInfo); const payload = { website_id: config.websiteId, timestamp: (/* @__PURE__ */ new Date()).toISOString(), browser: deviceInfo.browser.name || "unknown", deviceType: deviceInfo.device.type || "desktop", os: `${deviceInfo.os.name}`, referrer: document.referrer || "direct", url: window.location.href }; console.log("Sending analytics payload:", payload); fetch(`${config.baseUrl}/insert_page_view`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }).then((response) => { if (!response.ok) { throw new Error(`API call failed with status ${response.status}`); } return response.json(); }).then((data) => { console.log("Analytics recorded successfully:", data); }).catch((error) => { console.error("Error recording analytics:", error); }); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { initializeAnalytics, trackPageView });