# `@repobit/dex-utils`

# BD Web Utilities

BD Web Utilities is an npm package that provides a comprehensive suite of tools for modern web applications. It simplifies common tasks such as cookie management, page context extraction, user management, and user agent detection, while also offering utility functions for dynamic script loading and performance optimization through throttling and debouncing.

---

## Overview

This package is designed to help developers manage essential aspects of web applications with ease. It includes:

- **Cookie Management:** A simple wrapper around js-cookie to handle browser cookies.
- **Page Context Extraction:** A class to manage and extract page information such as locale, country, language, and query parameters.
- **User Management:** An abstract class for handling user login, fingerprinting, geolocation, and locale determination.
- **User Agent Detection:** An abstract class for parsing the browser’s user agent string to identify operating system and browser details.
- **Utility Functions:** Standalone functions for dynamically loading scripts and optimizing function execution using throttling and debouncing.

---

## Key Features

- **Modular Design:** Import only the components you need.
- **Intuitive API:** Simple classes with clear public methods, properties, and getters.
- **Performance Optimization:** Throttling and debouncing functions improve responsiveness.
- **Cross-Platform Support:** Robust user agent detection for adapting to different devices and browsers.
- **User-Centric:** Manage user context with automated locale and geolocation detection.

---

## Installation

Install via npm or yarn:

```bash
npm install @repobit/dex-utils
```

---

# Classes

## Cookies

### Description:
A wrapper around the js-cookie library (https://www.npmjs.com/package/js-cookie) for managing browser cookies. Alongside the already existing methods, we have also added the has function.

### Public Methods & Properties:

- ## set(name: string, value: string, options: {expires: number, path: string, ...}): void
    Use Case: Set a cookie with the corresponding name, value and options. For expires you pass the number of days.

- ## get(name: string, options: { domain: string, ...}): string
    Use Case: Get the cookie value if it exists.

- ## has(name: string): boolean
    Use Case: Checks if a cookie with the specified name exists. This is useful before attempting to access or modify cookie data.

### Usage

```typescript
Cookies.set('key', 'value', { expires: 1 });

if (Cookies.has('key')) {
    console.log(Cookies.get('key'));
}
```

---

## Page

### Description:
Manages page-related context such as locale, country, language, page name, and URL query parameters.

### Public Properties:

- ## locale: string
    Locale in the format `${string}-${string}` (e.g., "en-us"). It is passed as a parameter to the constructor so it is up to the developer to set it correctly.

- ## country: string
    Derived from the locale (e.g., for "en-us", country is "us").

- ## language: string
    Derived from the locale (e.g., for "en-us", language is "en").

- ## name: string
    Identifier for the page. It's the last part of the link in most cases (e.g, for "https://www.example.com/page", the name should be "page"). It is passed as a parameter to the constructor so it is up to the developer how they wish to set it.

- ## queryParams: URLSearchParams
    URL query parameters extracted from the current page link.

- ## environment: 'dev' | 'stage' | 'prod'
    Current deployment environment. It is passed as a parameter to the constructor so it is up to the developer to set it correctly depending on the project.

### Public Methods:

- ## getParamValue(key: string): string | null
    Use Case: Retrieves the value of a specific query parameter from the URL.

### Usage

```typescript
const page = new Page('en-us', 'homepage', 'prod');
console.log(page.country); // Outputs: "us"
console.log(page.getParamValue('ref')); // Retrieves the value of 'ref' from the URL query parameters
```

---

## User

### Description:
A class that manages user-related operations such as login, fingerprint generation, and geolocation-based locale determination.

### Public properties:

- ## info: Promise<UserInfoResult | null>
    Logged-in user's information (if available) received from Connect.

- ## fingerprint: Promise<string | null>
    A unique ID for the user.

- ## country: Promise<string>
    The user's country based on geolocation.

- ## locale: Promise<string>
    The user's locale (e.g., "en-us") fetched using his country.

### Public Methods:

- ## login(): Promise<void>
    Use Case: Initiates the user login process. If the user is not logged in, this method redirects to the login endpoint.

### Usage

```typescript
const user = new User();
user.info.then(info => {
  if (!info) {
    User.login();
  } else {
    console.log('User Info:', info);
  }
});
```

---

## UserAgent

### Description:
An abstract class that parses the user agent string to identify operating system and browser details. This is built upon the already existing cssua (https://cssuseragent.org/).

### Public Getters (Operating System):

- ## windows, macos, ios, android, linux
    Use Case: Identify the user's operating system.

### Public Getters (Browser):

- ## edge, chrome, firefox, safari, opera, ie, vivaldi
    Use Case: Determine the user's browser.

### Public Boolean Getters:

- ## isWindows, isMacos, isLinux, isUnix, isAndroid, isIos, isDesktop, isMobile
- ## isEdge, isChrome, isFirefox, isSafari, isOpera, isVivaldi, isIe
    Use Case: Quickly check the device type and browser for conditional logic in the application.

### Computed Getters:

- ## os
    Use Case: Returns a string representing the detected operating system.

- ## browser
    Use Case: Returns a string representing the detected browser.

### Usage

```typescript
if (UserAgent.isMobile) {
  console.log('Operating System:', UserAgent.os);
} else {
  console.log('Browser:', UserAgent.browser);
}
```

---

# Public Standalone Functions

## loadScript

### Description
Dynamically loads an external JavaScript file by appending a script element to the document head, ensuring the same script is not loaded multiple times. The return type of this call is a promise, making it ideal for checks where you need to make sure that the script was loaded successfully or unsuccessfully.

### Parameters:

- #### src: string – URL of the script.
- #### attrs: ScriptParameters – Optional attributes to add to the script element.

### Usage

```typescript
loadScript('https://example.com/some-library.js', { async: 'true' })
  .then(() => console.log('Script loaded successfully'))
  .catch(error => console.error('Error loading script:', error));
```

---

## throttle

### Description
Creates a throttled version of a function, ensuring it is executed at most once every specified delay period.

### Parameters:

- #### callback: Function – The function to throttle.
- #### delay: number – Delay in milliseconds (default is 250ms).

### Usage

```typescript
const throttledFunction = throttle(() => {
  console.log('Throttled function executed');
}, 500);

window.addEventListener('resize', throttledFunction);
```

---

## debounce

### Description
Creates a debounced version of a function that delays its execution until a specified time has elapsed since the last invocation. Especially usefull when you know that there will be a lot of clicks on a button for example.

### Parameters:

- #### callback: Function – The function to throttle.
- #### delay: number – Delay in milliseconds (default is 250ms).
- #### immediate: boolean – If true, triggers the function on the leading edge instead of the trailing edge.

### Usage

```typescript
const debouncedFunction = debounce(() => {
  console.log('Debounced function executed');
}, 300);

document.querySelector('input')?.addEventListener('input', debouncedFunction);
```

---

## getUserVisitorId

### Description
Fetches the current user's visitor ID from the `/bduuid` endpoint and returns the `bd_visitor_id` value from the response payload.

### Parameters:

This function does not accept any parameters.

### Returns:

- #### Promise<string> - Resolves to the user's visitor ID.

### Usage

```typescript
const visitorId = await getUserVisitorId();
console.log(visitorId);
```
