npm package: @fynd-design-engineering/web-utils
Description: Utility functions for web development including navigation and validation helpers
Author: Your Name
Latest version: 1.0.1

# 🔧 Web Utils

A comprehensive collection of utility functions for web development, built with TypeScript for better development experience and type safety.

## 📦 Installation

```bash
npm install @fynd-design-engineering/web-utils
```

## 🚀 Quick Start

```typescript
// Import specific functions
import { getPathSegments, checkForLocalhostUrls } from "@your-org/web-utils";

// Import by namespace
import { navigation, validations } from "@your-org/web-utils";

// Import everything
import * as WebUtils from "@your-org/web-utils";
```

## 📚 API Reference

### Navigation Utils

#### `getPathSegments()`

Extracts and returns path segments from the current URL, excluding empty segments.

**Returns:** `string[]` - Array of path segments

**Example:**

```typescript
import { getPathSegments } from "@your-org/web-utils";

// Current URL: https://example.com/user/profile/settings
const segments = getPathSegments();
console.log(segments); // ['user', 'profile', 'settings']

// Root URL: https://example.com/
const rootSegments = getPathSegments();
console.log(rootSegments); // []
```

**Namespace Usage:**

```typescript
import { navigation } from "@your-org/web-utils";
const segments = navigation.getPathSegments();
```

---

### Validation Utils

#### `checkForLocalhostUrls(options?)`

Scans the entire HTML document for localhost URLs and displays detailed warnings in the console. Perfect for catching development URLs that accidentally make it to production.

**Parameters:**

- `options` (optional): Configuration object
  - `checkLinks` (boolean, default: `true`) - Check href attributes in `<a>` and `<link>` tags
  - `checkImages` (boolean, default: `true`) - Check src attributes in `<img>` tags
  - `checkScripts` (boolean, default: `true`) - Check src attributes in `<script>` tags
  - `checkTextContent` (boolean, default: `true`) - Check text content throughout the document

**Returns:** `void`

**What it detects:**

- `localhost` (any port)
- `127.0.0.1` (any port)
- `0.0.0.0` (any port)
- HTTP and HTTPS variants
- With or without ports and paths

**Example:**

```typescript
import { checkForLocalhostUrls } from "@your-org/web-utils";

// Check everything (default)
checkForLocalhostUrls();

// Check only specific types
checkForLocalhostUrls({
  checkLinks: true,
  checkImages: false,
  checkScripts: true,
  checkTextContent: false,
});

// Namespace usage
import { validations } from "@your-org/web-utils";
validations.checkForLocalhostUrls();
```

**Console Output Example:**

```
🚨 LOCALHOST URLs DETECTED - PRODUCTION WARNING
⚠️  CRITICAL: Localhost URLs found in production environment!
📊 Total issues found: 3
🔗 Unique URLs: 2

1. Found localhost URL in a href: http://localhost:3000/api
2. Found localhost URL in img src: http://127.0.0.1:8080/image.jpg
3. Found localhost URL in text content: localhost:5173

🔧 Please replace all localhost URLs with production URLs before deployment.
📚 This can cause broken links, missing resources, and poor user experience.
```

#### `enableAutomaticLocalhostCheck()`

Automatically runs localhost URL checking when the DOM is fully loaded. Call this once to enable automatic detection.

**Returns:** `void`

**Example:**

```typescript
import { enableAutomaticLocalhostCheck } from "@your-org/web-utils";

// Enable automatic checking
enableAutomaticLocalhostCheck();

// This will automatically run checkForLocalhostUrls() when DOM is ready
```

---

## 🎯 Usage Patterns

### Basic Usage

```typescript
import { getPathSegments, checkForLocalhostUrls } from "@your-org/web-utils";

// Get current page segments
const currentPath = getPathSegments();
console.log("Current path:", currentPath);

// Check for localhost URLs
checkForLocalhostUrls();
```

### Namespace Usage

```typescript
import { navigation, validations } from "@your-org/web-utils";

// Navigation utilities
const segments = navigation.getPathSegments();

// Validation utilities
validations.checkForLocalhostUrls();
validations.enableAutomaticLocalhostCheck();
```

### Framework Integration

#### React

```tsx
import React, { useEffect, useState } from "react";
import {
  getPathSegments,
  enableAutomaticLocalhostCheck,
} from "@your-org/web-utils";

function MyComponent() {
  const [pathSegments, setPathSegments] = useState<string[]>([]);

  useEffect(() => {
    // Get path segments
    setPathSegments(getPathSegments());

    // Enable localhost checking in development
    if (process.env.NODE_ENV === "development") {
      enableAutomaticLocalhostCheck();
    }
  }, []);

  return (
    <div>
      <h1>Current Path: /{pathSegments.join("/")}</h1>
    </div>
  );
}
```

#### Vue.js

```vue
<template>
  <div>
    <h1>Current Path: /{{ pathSegments.join("/") }}</h1>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  getPathSegments,
  enableAutomaticLocalhostCheck,
} from "@your-org/web-utils";

const pathSegments = ref<string[]>([]);

onMounted(() => {
  pathSegments.value = getPathSegments();

  if (process.env.NODE_ENV === "development") {
    enableAutomaticLocalhostCheck();
  }
});
</script>
```

#### Vanilla JavaScript

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Web Utils Example</title>
  </head>
  <body>
    <div id="path-display"></div>

    <script type="module">
      import {
        getPathSegments,
        checkForLocalhostUrls,
      } from "@your-org/web-utils";

      // Display current path
      const segments = getPathSegments();
      document.getElementById(
        "path-display"
      ).textContent = `Current path: /${segments.join("/")}`;

      // Check for localhost URLs
      checkForLocalhostUrls();
    </script>
  </body>
</html>
```

---

## 🛡️ Production Safety

The validation utilities are designed with production safety in mind:

- **Console Warnings**: All localhost detection results are logged to console for debugging
- **Non-breaking**: Functions won't crash your application
- **Environment Aware**: Can be configured to throw errors in production builds
- **Performance**: Efficient DOM scanning with minimal performance impact

---

## 🔧 Development

### Building

```bash
npm run build
```

### Development Mode

```bash
npm run dev  # Watch mode for development
```

---

## 📋 Requirements

- **Browser Environment**: These utilities require `window` and `document` objects
- **TypeScript**: Full TypeScript support with type definitions included
- **Modern Browsers**: ES2020+ support recommended

---

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## 📄 License

MIT License - see LICENSE file for details

---

## 🏷️ Keywords

`web` `utils` `typescript` `navigation` `validation` `localhost` `url` `path` `browser` `development`

---

## 📞 Support

If you encounter any issues or have questions:

1. Check the [Issues](https://github.com/your-org/web-utils/issues) page
2. Create a new issue with detailed description
3. Include browser version and environment details

---

_Built with ❤️ and TypeScript_