Linters, dependencies clean up, jquery out

This commit is contained in:
2025-03-12 23:06:39 +05:30
parent f7da9f2b4c
commit a65e285551
11 changed files with 700 additions and 909 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,3 @@
export const ARMCO_SERVER = "https://telemetry.armco.tech/events/";
export const ADD = "add";
export const ARMCO_SERVER = "https://telemetry.armco.tech/events/"
export const ADD = "add"
export const TAG = "tag"

View File

@@ -1,16 +1,16 @@
import { sendBulkData } from "./analytics";
import { Event, SubmissionStrategy } from "./index.interface";
import { sendBulkData } from "./analytics"
import { Event, SubmissionStrategy } from "./index.interface"
const MAX_EVENTS = 100; // Maximum number of events to collect before flushing
const FLUSH_INTERVAL = 15000; // 60 seconds (in milliseconds)
const MAX_EVENTS = 100 // Maximum number of events to collect before flushing
const FLUSH_INTERVAL = 15000 // 60 seconds (in milliseconds)
let events: Event[] = [];
let events: Event[] = []
// Function to add an event to the collection
export function queueEvent(event: Event) {
events.push(event);
events.push(event)
if (events.length >= MAX_EVENTS) {
flushEvents();
flushEvents()
}
}
@@ -19,37 +19,38 @@ function flushEvents() {
// Implement the logic to send the events to your analytics server here
sendBulkData(events, () => {
// Clear the events array after flushing
events = [];
events = []
})
}
// Function to flush events before navigating away
function handleBeforeUnload() {
if (events.length > 0) {
flushEvents()
}
}
// Function to flush events when changing tabs
function handleVisibilityChange() {
if (document.visibilityState === "hidden" && events.length > 0) {
flushEvents()
}
}
// Attach event listeners (if running in a browser environment)
export function hookFlushHandlers(submissionStrategy: SubmissionStrategy = "ONEVENT") {
if (typeof window !== 'undefined' && submissionStrategy === "DEFER") {
// Function to flush events before navigating away
function handleBeforeUnload() {
if (events.length > 0) {
flushEvents();
}
}
// Function to flush events when changing tabs
function handleVisibilityChange() {
if (document.visibilityState === 'hidden' && events.length > 0) {
flushEvents();
}
}
export function hookFlushHandlers(
submissionStrategy: SubmissionStrategy = "ONEVENT",
) {
if (typeof window !== "undefined" && submissionStrategy === "DEFER") {
// Attach event listeners
window.addEventListener('beforeunload', handleBeforeUnload);
document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener("beforeunload", handleBeforeUnload)
document.addEventListener("visibilitychange", handleVisibilityChange)
// Flush events on a regular interval
setInterval(() => {
if (events.length > 0) {
flushEvents();
flushEvents()
}
}, FLUSH_INTERVAL);
}, FLUSH_INTERVAL)
}
}
}

8
global-modules.d.ts vendored
View File

@@ -1,14 +1,14 @@
import analytics from './index';
import analytics from "./index"
declare global {
namespace NodeJS {
interface Global {
analytics: analytics;
analytics: analytics
}
}
interface Window {
analytics: analytics;
analytics: analytics
}
}
export {};
export {}

View File

@@ -1,3 +1,3 @@
export function isArClient(name: string | null): boolean {
return !!(name && name.startsWith("@armco"));
}
return !!(name && name.startsWith("@armco"))
}

View File

@@ -1,32 +1,30 @@
export interface User {
email: string;
// Other user properties...
email: string
// Other user properties...
}
export interface Event {
eventType: string;
timestamp?: Date;
region?: string,
address?: string,
coordinates?: {
latitude: number
longitude: number
}
[key: string]: any; // Index signature to accept any other properties with their associated types
eventType: string
timestamp?: Date
region?: string
address?: string
coordinates?: {
latitude: number
longitude: number
}
[key: string]: any // Index signature to accept any other properties with their associated types
}
export interface ConfigType {
apiKey?: string;
analyticsLogEndpoint?: string;
analyticsTagEndpoint?: string;
hostProjectName?: string;
trackEvents?: Array<string>;
submissionStrategy?: SubmissionStrategy
showPopUp?: boolean
apiKey?: string
analyticsLogEndpoint?: string
analyticsTagEndpoint?: string
hostProjectName?: string
trackEvents?: Array<string>
submissionStrategy?: SubmissionStrategy
showPopUp?: boolean
}
export type SubmissionStrategy = "ONEVENT" | "DEFER"
export type objType = { [key: string]: any }
export type EVENT_TYPES = "CLICK" | "SUBMIT" | "SCROLL" | string

View File

@@ -11,18 +11,22 @@ import {
sendHostProjectName,
getSessionId,
startSession,
} from "./analytics";
} from "./analytics"
document.addEventListener("DOMContentLoaded", function (event) {
const environment = getEnvironment();
const environment = getEnvironment()
console.info("[ANALYTICS] Idenfitied environment: ", environment)
if (!environment || environment === "development") {
console.info("[ANALYTICS] Attempting to auto-load analytics configurations from environment...")
init();
console.info(
"[ANALYTICS] Attempting to auto-load analytics configurations from environment...",
)
init()
} else {
console.info("[ANALYTICS] Identified non-dev environment, analytics auto load wouldn't be attempted.")
console.info(
"[ANALYTICS] Identified non-dev environment, analytics auto load wouldn't be attempted.",
)
}
});
})
export {
init,
@@ -37,4 +41,4 @@ export {
sendHostProjectName,
getSessionId,
startSession,
};
}

View File

@@ -1,48 +1,54 @@
import jstz from "jstz";
import jstz from "jstz"
export function ipLookup() {
fetch('https://extreme-ip-lookup.com/json/')
.then(res => res.json())
.then(response => {
fallbackProcess(response)
})
.catch(() => {
console.log('We could not find your location');
})
fetch("https://extreme-ip-lookup.com/json/")
.then((res) => res.json())
.then((response) => {
fallbackProcess(response)
})
.catch(() => {
console.log("We could not find your location")
})
}
export function success(position: any, callback: Function) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
reverseGeocodingWithGoogle(latitude, longitude, callback)
const latitude = position.coords.latitude
const longitude = position.coords.longitude
reverseGeocodingWithGoogle(latitude, longitude, callback)
}
export function error() {
console.log("Unable to retrieve your location");
console.log("Unable to retrieve your location")
}
function reverseGeocodingWithGoogle(latitude: string, longitude: string, callback: Function) {
fetch(`https://maps.googleapis.com/maps/api/geocode/json?
function reverseGeocodingWithGoogle(
latitude: string,
longitude: string,
callback: Function,
) {
fetch(`https://maps.googleapis.com/maps/api/geocode/json?
latlng=${latitude},${longitude}&key={GOOGLE_MAP_KEY}`)
.then(res => res.json())
.then(response => {
callback ? callback(response) : processUserData(response)
})
.catch(status => {
ipLookup()
})
.then((res) => res.json())
.then((response) => {
callback ? callback(response) : processUserData(response)
})
.catch((status) => {
ipLookup()
})
}
function processUserData(response: any) {
console.log(response.results[0].formatted_address);
console.log(response.results[0].formatted_address)
}
function fallbackProcess(response: any) {
const address: any = document.querySelector('.address')
address.innerText = `${response.city}, ${response.country}`
const address: any = document.querySelector(".address")
address.innerText = `${response.city}, ${response.country}`
}
const localTimeRegion = jstz.determine().name();
const localTime = new Date().toLocaleString("en-US", { timeZone: localTimeRegion });
const localTimeRegion = jstz.determine().name()
const localTime = new Date().toLocaleString("en-US", {
timeZone: localTimeRegion,
})
export { localTimeRegion, localTime };
export { localTimeRegion, localTime }

309
package-lock.json generated
View File

@@ -1,309 +0,0 @@
{
"name": "@armco/analytics",
"version": "0.1.6",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@armco/analytics",
"version": "0.1.6",
"license": "ISC",
"dependencies": {
"jet-logger": "^1.3.1",
"jquery": "^3.7.0",
"js-cookie": "^3.0.5",
"jstz": "^2.1.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.1",
"@types/jquery": "^3.5.16",
"@types/js-cookie": "^3.0.3",
"@types/node": "^20.4.2",
"@types/uuid": "^9.0.2",
"fs-extra": "^11.1.1",
"typescript": "^5.1.6"
},
"peerDependencies": {
"jquery": "^3.7.0"
}
},
"node_modules/@types/fs-extra": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.1.tgz",
"integrity": "sha512-MxObHvNl4A69ofaTRU8DFqvgzzv8s9yRtaPPm5gud9HDNvpB3GPQFvNuTWAI59B9huVGV5jXYJwbCsmBsOGYWA==",
"dev": true,
"dependencies": {
"@types/jsonfile": "*",
"@types/node": "*"
}
},
"node_modules/@types/jquery": {
"version": "3.5.16",
"resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.16.tgz",
"integrity": "sha512-bsI7y4ZgeMkmpG9OM710RRzDFp+w4P1RGiIt30C1mSBT+ExCleeh4HObwgArnDFELmRrOpXgSYN9VF1hj+f1lw==",
"dev": true,
"dependencies": {
"@types/sizzle": "*"
}
},
"node_modules/@types/js-cookie": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.3.tgz",
"integrity": "sha512-Xe7IImK09HP1sv2M/aI+48a20VX+TdRJucfq4vfRVy6nWN8PYPOEnlMRSgxJAgYQIXJVL8dZ4/ilAM7dWNaOww==",
"dev": true
},
"node_modules/@types/jsonfile": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@types/jsonfile/-/jsonfile-6.1.1.tgz",
"integrity": "sha512-GSgiRCVeapDN+3pqA35IkQwasaCh/0YFH5dEF6S88iDvEn901DjOeH3/QPY+XYP1DFzDZPvIvfeEgk+7br5png==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "20.4.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz",
"integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw==",
"dev": true
},
"node_modules/@types/sizzle": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.3.tgz",
"integrity": "sha512-JYM8x9EGF163bEyhdJBpR2QX1R5naCJHC8ucJylJ3w9/CVBaskdQ8WqBf8MmQrd1kRvp/a4TS8HJ+bxzR7ZJYQ==",
"dev": true
},
"node_modules/@types/uuid": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.2.tgz",
"integrity": "sha512-kNnC1GFBLuhImSnV7w4njQkUiJi0ZXUycu1rUaouPqiKlXkh77JKgdRnTAp1x5eBwcIwbtI+3otwzuIDEuDoxQ==",
"dev": true
},
"node_modules/colors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/colors/-/colors-1.3.0.tgz",
"integrity": "sha512-EDpX3a7wHMWFA7PUHWPHNWqOxIIRSJetuwl0AS5Oi/5FMV8kWm69RTlgm00GKjBO1xFHMtBbL49yRtMMdticBw==",
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/fs-extra": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz",
"integrity": "sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==",
"dev": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=14.14"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true
},
"node_modules/jet-logger": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/jet-logger/-/jet-logger-1.3.1.tgz",
"integrity": "sha512-BSsTm88Y7a+XtXKpZM71qm0ulH+bNI13rR+BzeQStfjpE/6n3fX3FZpKF/WZh52h1e6gEAOjuFlkmdzGBQnwPg==",
"dependencies": {
"colors": "1.3.0"
}
},
"node_modules/jquery": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.0.tgz",
"integrity": "sha512-umpJ0/k8X0MvD1ds0P9SfowREz2LenHsQaxSohMZ5OMNEU2r0tf8pdeEFTHMFxWVxKNyU9rTtK3CWzUCTKJUeQ=="
},
"node_modules/js-cookie": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
"engines": {
"node": ">=14"
}
},
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dev": true,
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/jstz": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/jstz/-/jstz-2.1.1.tgz",
"integrity": "sha512-8hfl5RD6P7rEeIbzStBz3h4f+BQHfq/ABtoU6gXKQv5OcZhnmrIpG7e1pYaZ8hS9e0mp+bxUj08fnDUbKctYyA==",
"engines": {
"node": ">=0.10"
}
},
"node_modules/typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/universalify": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
"integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"dev": true,
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/uuid": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz",
"integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==",
"bin": {
"uuid": "dist/bin/uuid"
}
}
},
"dependencies": {
"@types/fs-extra": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.1.tgz",
"integrity": "sha512-MxObHvNl4A69ofaTRU8DFqvgzzv8s9yRtaPPm5gud9HDNvpB3GPQFvNuTWAI59B9huVGV5jXYJwbCsmBsOGYWA==",
"dev": true,
"requires": {
"@types/jsonfile": "*",
"@types/node": "*"
}
},
"@types/jquery": {
"version": "3.5.16",
"resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.16.tgz",
"integrity": "sha512-bsI7y4ZgeMkmpG9OM710RRzDFp+w4P1RGiIt30C1mSBT+ExCleeh4HObwgArnDFELmRrOpXgSYN9VF1hj+f1lw==",
"dev": true,
"requires": {
"@types/sizzle": "*"
}
},
"@types/js-cookie": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.3.tgz",
"integrity": "sha512-Xe7IImK09HP1sv2M/aI+48a20VX+TdRJucfq4vfRVy6nWN8PYPOEnlMRSgxJAgYQIXJVL8dZ4/ilAM7dWNaOww==",
"dev": true
},
"@types/jsonfile": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@types/jsonfile/-/jsonfile-6.1.1.tgz",
"integrity": "sha512-GSgiRCVeapDN+3pqA35IkQwasaCh/0YFH5dEF6S88iDvEn901DjOeH3/QPY+XYP1DFzDZPvIvfeEgk+7br5png==",
"dev": true,
"requires": {
"@types/node": "*"
}
},
"@types/node": {
"version": "20.4.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.2.tgz",
"integrity": "sha512-Dd0BYtWgnWJKwO1jkmTrzofjK2QXXcai0dmtzvIBhcA+RsG5h8R3xlyta0kGOZRNfL9GuRtb1knmPEhQrePCEw==",
"dev": true
},
"@types/sizzle": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.3.tgz",
"integrity": "sha512-JYM8x9EGF163bEyhdJBpR2QX1R5naCJHC8ucJylJ3w9/CVBaskdQ8WqBf8MmQrd1kRvp/a4TS8HJ+bxzR7ZJYQ==",
"dev": true
},
"@types/uuid": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.2.tgz",
"integrity": "sha512-kNnC1GFBLuhImSnV7w4njQkUiJi0ZXUycu1rUaouPqiKlXkh77JKgdRnTAp1x5eBwcIwbtI+3otwzuIDEuDoxQ==",
"dev": true
},
"colors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/colors/-/colors-1.3.0.tgz",
"integrity": "sha512-EDpX3a7wHMWFA7PUHWPHNWqOxIIRSJetuwl0AS5Oi/5FMV8kWm69RTlgm00GKjBO1xFHMtBbL49yRtMMdticBw=="
},
"fs-extra": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz",
"integrity": "sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==",
"dev": true,
"requires": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
}
},
"graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true
},
"jet-logger": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/jet-logger/-/jet-logger-1.3.1.tgz",
"integrity": "sha512-BSsTm88Y7a+XtXKpZM71qm0ulH+bNI13rR+BzeQStfjpE/6n3fX3FZpKF/WZh52h1e6gEAOjuFlkmdzGBQnwPg==",
"requires": {
"colors": "1.3.0"
}
},
"jquery": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.0.tgz",
"integrity": "sha512-umpJ0/k8X0MvD1ds0P9SfowREz2LenHsQaxSohMZ5OMNEU2r0tf8pdeEFTHMFxWVxKNyU9rTtK3CWzUCTKJUeQ=="
},
"js-cookie": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw=="
},
"jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dev": true,
"requires": {
"graceful-fs": "^4.1.6",
"universalify": "^2.0.0"
}
},
"jstz": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/jstz/-/jstz-2.1.1.tgz",
"integrity": "sha512-8hfl5RD6P7rEeIbzStBz3h4f+BQHfq/ABtoU6gXKQv5OcZhnmrIpG7e1pYaZ8hS9e0mp+bxUj08fnDUbKctYyA=="
},
"typescript": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"dev": true
},
"universalify": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
"integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"dev": true
},
"uuid": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz",
"integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg=="
}
}
}

View File

@@ -38,7 +38,6 @@
],
"devDependencies": {
"@types/fs-extra": "^11.0.1",
"@types/jquery": "^3.5.16",
"@types/js-cookie": "^3.0.3",
"@types/node": "^20.4.2",
"@types/uuid": "^9.0.2",
@@ -46,13 +45,8 @@
"typescript": "^5.1.6"
},
"dependencies": {
"jet-logger": "^1.3.1",
"jquery": "^3.7.0",
"js-cookie": "^3.0.5",
"jstz": "^2.1.1",
"uuid": "^9.0.0"
},
"peerDependencies": {
"jquery": "^3.7.0"
}
}

View File

@@ -1,121 +1,126 @@
import Cookies from 'js-cookie';
import {v4 as uuidv4} from "uuid";
import Cookies from "js-cookie"
import { v4 as uuidv4 } from "uuid"
const SESSION_COOKIE_NAME = 'ar-session-id';
const SESSION_EXPIRATION_TIME = 30; // In minutes
let localStorageTimeout: NodeJS.Timeout;
const SESSION_COOKIE_NAME = "ar-session-id"
const SESSION_EXPIRATION_TIME = 30 // In minutes
let localStorageTimeout: NodeJS.Timeout
// Function to generate a new session ID
function generateSessionId() {
return uuidv4();
return uuidv4()
}
// Function to start a new session and generate a session ID
export function startSession() {
const sessionId = generateSessionId();
const expirationDate = new Date();
const sessionId = generateSessionId()
const expirationDate = new Date()
// Generate a unique identifier for this tab if it doesn't already have one
let tabId = sessionStorage.getItem('tabId');
let tabId = sessionStorage.getItem("tabId")
if (!tabId) {
const timestamp = expirationDate.getTime();
tabId = `${uuidv4()}-${timestamp}`;
sessionStorage.setItem('tabId', tabId);
const timestamp = expirationDate.getTime()
tabId = `${uuidv4()}-${timestamp}`
sessionStorage.setItem("tabId", tabId)
}
// Combine the tab ID and session ID to create a unique cookie name for this tab
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`;
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`
refreshSessionId(sessionId, cookieName);
refreshSessionId(sessionId, cookieName)
return sessionId;
return sessionId
}
// Function to refresh the session ID expiration time
function refreshSessionId(sessionId: string, cookieName: string) {
const expirationDate = new Date();
expirationDate.setMinutes(expirationDate.getMinutes() + SESSION_EXPIRATION_TIME);
const expirationDate = new Date()
expirationDate.setMinutes(
expirationDate.getMinutes() + SESSION_EXPIRATION_TIME,
)
// Refresh the session ID expiration time in cookies or localStorage
try {
Cookies.set(cookieName, sessionId, { expires: expirationDate });
Cookies.set(cookieName, sessionId, { expires: expirationDate })
} catch (error) {
clearTimeout(localStorageTimeout);
localStorageTimeout = setTimeout(() => localStorage.removeItem(cookieName), SESSION_EXPIRATION_TIME * 1000);
clearTimeout(localStorageTimeout)
localStorageTimeout = setTimeout(
() => localStorage.removeItem(cookieName),
SESSION_EXPIRATION_TIME * 1000,
)
}
}
// Function to get the current session ID (if it exists) and refresh the cookie expiration time
export function getSessionId() {
let sessionId: string | null | undefined;
let sessionId: string | null | undefined
// Get the tab ID from sessionStorage
const tabId = sessionStorage.getItem('tabId');
const tabId = sessionStorage.getItem("tabId")
if (!tabId) {
// If there's no tab ID, start a new session
return startSession();
return startSession()
}
// Combine the tab ID and session ID to create the cookie name
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`;
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`
sessionId = Cookies.get(cookieName);
sessionId = Cookies.get(cookieName)
// If the session ID is not found in cookies, check localStorage
if (!sessionId) {
sessionId = localStorage.getItem(cookieName);
sessionId = localStorage.getItem(cookieName)
}
if (!sessionId) {
return startSession();
return startSession()
}
refreshSessionId(sessionId, cookieName);
refreshSessionId(sessionId, cookieName)
return sessionId;
return sessionId
}
export function extendSession() {
// Get the tab ID from sessionStorage
const tabId = sessionStorage.getItem('tabId');
const tabId = sessionStorage.getItem("tabId")
if (!tabId) {
// If there's no tab ID, there's no session to extend
return;
return
}
// Combine the tab ID and session ID to create the cookie name
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`;
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`
let sessionId: string | null | undefined = Cookies.get(cookieName);
let sessionId: string | null | undefined = Cookies.get(cookieName)
// If the session ID is not found in cookies, check localStorage
if (!sessionId) {
sessionId = localStorage.getItem(cookieName);
sessionId = localStorage.getItem(cookieName)
}
if (sessionId) {
refreshSessionId(sessionId, cookieName);
refreshSessionId(sessionId, cookieName)
}
}
// Helper function to remove the session cookie
export function terminateSession(): void {
// Get the tab ID from sessionStorage
const tabId = sessionStorage.getItem('tabId');
const tabId = sessionStorage.getItem("tabId")
if (!tabId) {
// If there's no tab ID, there's nothing to remove
return;
return
}
// Combine the tab ID and session ID to create the cookie name
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`;
const cookieName = `${SESSION_COOKIE_NAME}-${tabId}`
// Use Cookies if available
if (typeof window !== 'undefined' && window.Cookies) {
Cookies.remove(cookieName);
if (typeof window !== "undefined" && window.Cookies) {
Cookies.remove(cookieName)
} else {
// Fallback to localStorage (blocked Cookies)
localStorage.removeItem(cookieName);
localStorage.removeItem(cookieName)
}
}