{"_id":"@cookiefirst/fastdetect","_rev":"7-7451ad4b3782aa213ce7d50462e8187f","name":"@cookiefirst/fastdetect","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.3":{"name":"@cookiefirst/fastdetect","version":"1.0.3","keywords":["user-agent","device-detection","browser-detection","mobile-detection","os-detection","high-performance","api","parser","useragent","device"],"author":{"name":"Kees van den Bos"},"license":"AGPL-3.0","_id":"@cookiefirst/fastdetect@1.0.3","maintainers":[{"name":"keesvdb","email":"info@cookiefirst.com"},{"name":"jedlikk","email":"jedlikowskib@gmail.com"},{"name":"rafal-cf","email":"rafal@cookiefirst.com"}],"homepage":"https://github.com/cookiefirst-dds/fastdetect#readme","bugs":{"url":"https://github.com/cookiefirst-dds/fastdetect/issues"},"dist":{"shasum":"151c47b8a510653f088f94b18f0a02a2f588dd4e","tarball":"https://registry.npmjs.org/@cookiefirst/fastdetect/-/fastdetect-1.0.3.tgz","fileCount":4,"integrity":"sha512-jh4GBmX66CAeK0yAKPuU1HiwHVKVzYAtzR7FyJjahCbvpWgWtypHXMxWYtWpuuPePmrhaGhJ6Sf/I+XTp1d+vg==","signatures":[{"sig":"MEQCIHmAeDkJIHmT8VdEKP7GaGF5VCHs2OqsZCbC7/1K/qQ2AiAIdQfk7CaxwzHUaYdgBEj3P/pg7DBOXg5rViz/M7zF4A==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":63690},"main":"index.js","types":"index.d.ts","module":"esm/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./index.d.ts","import":"./esm/index.mjs","require":"./index.js"},"./parsers/os":{"types":"./parsers/os.d.ts","import":"./esm/parsers/os.mjs","require":"./parsers/os.js"},"./parsers/bot":{"types":"./parsers/bot.d.ts","import":"./esm/parsers/bot.mjs","require":"./parsers/bot.js"},"./parsers/device":{"types":"./parsers/device.d.ts","import":"./esm/parsers/device.mjs","require":"./parsers/device.js"},"./parsers/browser":{"types":"./parsers/browser.d.ts","import":"./esm/parsers/browser.mjs","require":"./parsers/browser.js"}},"gitHead":"3e1adbd86f995bbd74aa15fdd72e0983451b2226","_npmUser":{"name":"keesvdb","email":"info@cookiefirst.com"},"repository":{"url":"git+https://github.com/cookiefirst-dds/fastdetect.git","type":"git"},"_npmVersion":"10.8.2","description":"High-performance device detection library optimized for API usage with comprehensive device, browser, and OS detection","directories":{},"_nodeVersion":"20.19.4","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/fastdetect_1.0.3_1754640826925_0.12624975162470808","host":"s3://npm-registry-packages-npm-production"}},"1.0.5":{"name":"@cookiefirst/fastdetect","version":"1.0.5","keywords":["user-agent","device-detection","browser-detection","mobile-detection","os-detection","high-performance","api","parser","useragent","device"],"author":{"name":"Kees van den Bos"},"license":"AGPL-3.0","_id":"@cookiefirst/fastdetect@1.0.5","maintainers":[{"name":"keesvdb","email":"info@cookiefirst.com"},{"name":"jedlikk","email":"jedlikowskib@gmail.com"},{"name":"rafal-cf","email":"rafal@cookiefirst.com"}],"homepage":"https://github.com/cookiefirst-dds/fastdetect#readme","bugs":{"url":"https://github.com/cookiefirst-dds/fastdetect/issues"},"dist":{"shasum":"e0679ef635ff6c43ecb464c2e2f40c8285335425","tarball":"https://registry.npmjs.org/@cookiefirst/fastdetect/-/fastdetect-1.0.5.tgz","fileCount":63,"integrity":"sha512-Js6fN1HA3EW2dky6VmdEsAwOCHJzSMFqF3iykT7BaDw8+WuypZUhBdt6E8w7WCq59jcwbWlkO/CqaZUTkrYdlg==","signatures":[{"sig":"MEQCIEBiUjbvJ1p5gS/YWkfCRCw7gQsS75aAt6B/52PUx8UsAiBtWKLSo/0MNdiUHX+Y8K+jNuDlG48LWpF1oqm0K0q59w==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":634725},"main":"dist/index.js","types":"dist/index.d.ts","module":"dist/index.esm.js","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.esm.js","require":"./dist/index.js"},"./parsers/os":{"types":"./dist/parsers/os.d.ts","import":"./dist/parsers/os.esm.js","require":"./dist/parsers/os.js"},"./parsers/device":{"types":"./dist/parsers/device.d.ts","import":"./dist/parsers/device.esm.js","require":"./dist/parsers/device.js"},"./parsers/browser":{"types":"./dist/parsers/browser.d.ts","import":"./dist/parsers/browser.esm.js","require":"./dist/parsers/browser.js"}},"gitHead":"ef53fa38e8d2a45b27bf8b25bcca0a656179b9d2","scripts":{"lint":"eslint src/**/*.ts","test":"jest","build":"npm run build:cjs && npm run build:esm && npm run build:types","prebuild":"npm run bots:update","benchmark":"node benchmarks/performance.js","build:cjs":"tsc -p tsconfig.cjs.json","build:esm":"tsc -p tsconfig.esm.json","build:prod":"node scripts/build.js","test:watch":"jest --watch","bots:update":"node scripts/sync-bots.js","build:types":"tsc -p tsconfig.types.json","test:coverage":"jest --coverage","prepublishOnly":"npm run build && npm test"},"_npmUser":{"name":"keesvdb","email":"info@cookiefirst.com"},"repository":{"url":"git+https://github.com/cookiefirst-dds/fastdetect.git","type":"git"},"_npmVersion":"10.8.2","description":"High-performance device detection library optimized for API usage with comprehensive device, browser, and OS detection","directories":{},"_nodeVersion":"20.19.4","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^8.49.0","ts-jest":"^29.1.1","jest-junit":"^16.0.0","typescript":"^5.2.2","@types/jest":"^29.5.5","@types/node":"^20.6.0","crawler-user-agents":"^1.15.0","eslint-plugin-import":"^2.32.0","@typescript-eslint/parser":"^6.7.0","@typescript-eslint/eslint-plugin":"^6.7.0"},"_npmOperationalInternal":{"tmp":"tmp/fastdetect_1.0.5_1754908255996_0.11733059895508435","host":"s3://npm-registry-packages-npm-production"}},"1.1.0":{"name":"@cookiefirst/fastdetect","version":"1.1.0","description":"High-performance device detection library optimized for API usage with comprehensive device, browser, and OS detection","main":"dist/index.js","module":"dist/esm/index.mjs","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/esm/index.mjs","require":"./dist/index.js"},"./parsers/browser":{"types":"./dist/parsers/browser.d.ts","import":"./dist/esm/parsers/browser.mjs","require":"./dist/parsers/browser.js"},"./parsers/device":{"types":"./dist/parsers/device.d.ts","import":"./dist/esm/parsers/device.mjs","require":"./dist/parsers/device.js"},"./parsers/os":{"types":"./dist/parsers/os.d.ts","import":"./dist/esm/parsers/os.mjs","require":"./dist/parsers/os.js"},"./parsers/bot":{"types":"./dist/parsers/bot.d.ts","import":"./dist/esm/parsers/bot.mjs","require":"./dist/parsers/bot.js"}},"scripts":{"prebuild":"npm run bots:update","bots:update":"node scripts/sync-bots.js","build":"npm run build:cjs && npm run build:esm && npm run build:types","build:cjs":"tsc -p tsconfig.cjs.json","build:esm":"tsc -p tsconfig.esm.json","build:types":"tsc -p tsconfig.types.json","build:prod":"node scripts/build.js","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","benchmark":"node benchmarks/performance.js","lint":"eslint src/","prepublishOnly":"npm run build && npm test"},"keywords":["user-agent","device-detection","browser-detection","mobile-detection","os-detection","high-performance","api","parser","useragent","device"],"author":{"name":"Kees van den Bos"},"license":"AGPL-3.0","repository":{"type":"git","url":"git+https://github.com/cookiefirst-dds/fastdetect.git"},"bugs":{"url":"https://github.com/cookiefirst-dds/fastdetect/issues"},"homepage":"https://github.com/cookiefirst-dds/fastdetect#readme","publishConfig":{"access":"public"},"engines":{"node":">=18.0.0"},"devDependencies":{"@eslint/js":"^10.0.1","@types/jest":"^30.0.0","@types/node":"^25.5.0","crawler-user-agents":"1.15.0","eslint":"^10.1.0","eslint-plugin-import-x":"^4.16.2","jest":"^30.3.0","jest-junit":"^16.0.0","ts-jest":"^29.4.6","typescript":"^5.9.3","typescript-eslint":"^8.57.1"},"_id":"@cookiefirst/fastdetect@1.1.0","gitHead":"205db266a7c25ec3a32703809635d63829ba70f7","_nodeVersion":"20.20.1","_npmVersion":"10.8.2","dist":{"integrity":"sha512-LzsEUdsGDGAVYDsBTck9ac3O6zX667t41LL/865rkSzgrUj+GZcko8IdBIMcaEmaAUQgIltob6rWGaNn6a20DA==","shasum":"7fc6af9308d286ddc1c70197213a70d1ce3ceda9","tarball":"https://registry.npmjs.org/@cookiefirst/fastdetect/-/fastdetect-1.1.0.tgz","fileCount":63,"unpackedSize":662406,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIBJUBqOjJVg1GOK+nbt72Vv/outFc+VY7Qjjw/JN156LAiBUSsydoYDHtj8XfhzPx0JSo4W3uM74CyXarGVBLLSeFg=="}]},"_npmUser":{"name":"keesvdb","email":"info@cookiefirst.com"},"directories":{},"maintainers":[{"name":"keesvdb","email":"info@cookiefirst.com"},{"name":"jedlikk","email":"jedlikowskib@gmail.com"},{"name":"rafal-cf","email":"rafal@cookiefirst.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/fastdetect_1.1.0_1774275781155_0.19306099799896015"},"_hasShrinkwrap":false}},"time":{"created":"2025-08-08T08:13:46.801Z","modified":"2026-03-23T14:23:01.472Z","1.0.0":"2025-08-08T05:11:17.245Z","1.0.2":"2025-08-08T05:45:39.186Z","1.0.3":"2025-08-08T08:13:47.161Z","1.0.5":"2025-08-11T10:30:56.167Z","1.1.0":"2026-03-23T14:23:01.310Z"},"bugs":{"url":"https://github.com/cookiefirst-dds/fastdetect/issues"},"author":{"name":"Kees van den Bos"},"license":"AGPL-3.0","homepage":"https://github.com/cookiefirst-dds/fastdetect#readme","keywords":["user-agent","device-detection","browser-detection","mobile-detection","os-detection","high-performance","api","parser","useragent","device"],"repository":{"type":"git","url":"git+https://github.com/cookiefirst-dds/fastdetect.git"},"description":"High-performance device detection library optimized for API usage with comprehensive device, browser, and OS detection","maintainers":[{"name":"keesvdb","email":"info@cookiefirst.com"},{"name":"jedlikk","email":"jedlikowskib@gmail.com"},{"name":"rafal-cf","email":"rafal@cookiefirst.com"}],"readme":"# FastDetect 🚀\n\nHigh-performance device detection library optimized for API usage with comprehensive device, browser, and OS detection.\n\n[![npm version](https://badge.fury.io/js/%40cookiefirst%2Ffastdetect.svg)](https://badge.fury.io/js/%40cookiefirst%2Ffastdetect)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)\n[![AGPL-3.0 License](https://img.shields.io/badge/License-AGPL--3.0-green.svg)](https://www.gnu.org/licenses/agpl-3.0)\n[![Bundle Size](https://img.shields.io/bundlephobia/minzip/%40cookiefirst%2Ffastdetect)](https://bundlephobia.com/package/%40cookiefirst%2Ffastdetect)\n<a href=\"https://codecov.io/gh/cookiefirst-dds/fastdetect\" target=\"_blank\">\n  <img src=\"https://codecov.io/gh/cookiefirst-dds/fastdetect/graph/badge.svg?token=YOUR_CODECOV_TOKEN_HERE\" alt=\"Codecov\" />\n</a>\n\n## ✨ Features\n\n- **🏃‍♂️ High Performance**: Optimized for 10,000+ detections per second with sub-millisecond response times\n- **🎯 Comprehensive Detection**: Device types, brands, models, browsers, operating systems, and bots\n- **💾 Smart Caching**: Built-in LRU cache with configurable size for optimal memory usage\n- **📱 Mobile-First**: Optimized patterns for modern mobile devices and emerging technologies\n- **🤖 AI-Ready**: Detection for modern AI crawlers (GPTBot, ClaudeBot, PerplexityBot)\n- **🌳 Tree-Shakeable**: Modular architecture allows importing only needed components\n- **📘 TypeScript**: Full type definitions with comprehensive IntelliSense support\n- **🔒 Zero Dependencies**: No external runtime dependencies for maximum security\n- **⚖️ AGPL-3.0 Licensed**: Free software with copyleft protection\n\n## 🚀 Installation\n\n```bash\nnpm install @cookiefirst/fastdetect\n```\n\n```bash\nyarn add @cookiefirst/fastdetect\n```\n\n```bash\npnpm add @cookiefirst/fastdetect\n```\n\n## 📖 Quick Start\n\n### Basic Usage\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\nconst result = detector.parse('Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1');\n\nconsole.log(result);\n// Output:\n// {\n//   browser: { name: 'Safari', version: '16.6', major: '16', engine: 'WebKit', isMobile: true },\n//   os: { name: 'iOS', version: '16.6', family: 'iOS' },\n//   device: { type: 'smartphone', brand: 'Apple', model: 'iPhone' },\n//   bot: { isBot: false, name: null, category: null },\n//   userAgent: '...',\n//   timestamp: 1703932800000\n// }\n```\n\n### Modular Usage (Tree-Shaking Optimized)\n\n```typescript\nimport { BrowserParser, DeviceParser } from '@cookiefirst/fastdetect';\n\nconst browserParser = new BrowserParser();\nconst deviceParser = new DeviceParser();\n\nconst browser = browserParser.parse(userAgent);\nconst device = deviceParser.parse(userAgent);\n```\n\n### Express.js Middleware\n\n```typescript\nimport express from 'express';\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst app = express();\nconst detector = new FastDetect({ cacheSize: 5000 });\n\napp.use((req, res, next) => {\n  req.device = detector.parse(req.headers['user-agent'] || '');\n  next();\n});\n\napp.get('/api/analytics', (req, res) => {\n  const { device } = req;\n  \n  // Log device information for analytics\n  console.log(`Device: ${device.device.type}, Browser: ${device.browser.name}`);\n  \n  res.json({ success: true });\n});\n```\n\n## 🔧 API Reference\n\n### FastDetect Class\n\n#### Constructor\n\n```typescript\nnew FastDetect(options?: ParseOptions)\n```\n\n**Options:**\n- `cacheSize?: number` - LRU cache size (default: 1000)\n- `skipCache?: boolean` - Disable caching (default: false)\n- `detailed?: boolean` - Enable detailed parsing (default: false)\n- `maxLength?: number` - Maximum UA string length before rejection (default: 8192)\n\n#### Methods\n\n##### `parse(userAgent: string, options?: ParseOptions): DetectionResult`\n\nParse complete device information from user agent string.\n\n```typescript\nconst result = detector.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');\n```\n\n##### `parseBrowser(userAgent: string): BrowserInfo`\n\nParse browser information only (lightweight).\n\n```typescript\nconst browser = detector.parseBrowser(userAgent);\n// { name: 'Chrome', version: '91.0.4472.124', major: '91', engine: 'Blink' }\n```\n\n##### `parseDevice(userAgent: string): DeviceInfo`\n\nParse device information only.\n\n```typescript\nconst device = detector.parseDevice(userAgent);\n// { type: 'smartphone', brand: 'Apple', model: 'iPhone 14 Pro' }\n```\n\n##### `parseOS(userAgent: string): OSInfo`\n\nParse operating system information only.\n\n```typescript\nconst os = detector.parseOS(userAgent);\n// { name: 'iOS', version: '16.6', family: 'iOS' }\n```\n\n##### `parseBot(userAgent: string): BotInfo`\n\nParse bot/crawler information only.\n\n```typescript\nconst bot = detector.parseBot(userAgent);\n// { isBot: true, name: 'Googlebot', category: 'search-engine' }\n```\n\n#### Quick Detection Methods\n\n```typescript\ndetector.isMobile(userAgent)    // boolean\ndetector.isTablet(userAgent)    // boolean\ndetector.isDesktop(userAgent)   // boolean\ndetector.isBot(userAgent)       // boolean\n```\n\n#### Cache Management\n\n```typescript\ndetector.clearCache()           // Clear cache\ndetector.getCacheStats()        // Get cache statistics\n```\n\n## 📊 Supported Detections\n\n### Device Types\n- **Smartphones** - iPhone, Android phones, etc.\n- **Tablets** - iPad, Android tablets, Surface tablets\n- **Desktops** - Windows, macOS, Linux computers\n- **Smart TVs** - Android TV, webOS, Tizen, Roku, Apple TV\n- **Gaming Consoles** - PlayStation, Xbox, Nintendo Switch, Steam Deck\n- **VR/AR Headsets** - Meta Quest, Apple Vision Pro, HTC Vive\n- **Wearables** - Apple Watch, Galaxy Watch, Wear OS\n- **E-readers** - Kindle, Kobo, Nook\n- **Automotive** - Android Automotive, CarPlay systems\n- **IoT Devices** - Smart home devices, embedded systems\n\n### Browsers (50+ supported)\n- **Desktop**: Chrome, Firefox, Safari, Edge, Opera, Internet Explorer\n- **Mobile**: Chrome Mobile, Safari Mobile, Samsung Internet, UC Browser\n- **WebViews**: Android WebView, iOS WebView, Facebook Browser\n\n### Operating Systems (30+ supported)\n- **Desktop**: Windows (7-10/11), macOS, Linux distributions\n\n> **Note:** Windows 10 and Windows 11 both report `NT 10.0` in the user-agent string and cannot be reliably distinguished via UA alone. FastDetect returns `\"Windows 10/11\"` for these. Accurate Windows 11 detection requires [Client Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Client_hints) (`Sec-CH-UA-Platform-Version`).\n- **Mobile**: iOS, iPadOS, Android, Windows Phone\n- **Specialized**: Chrome OS, Tizen, webOS, KaiOS\n\n### Device Brands (100+ supported)\n- **Mobile**: Apple, Samsung, Google, Huawei, Xiaomi, OPPO, vivo, OnePlus\n- **Desktop**: Dell, HP, Lenovo, ASUS, Microsoft Surface\n- **Gaming**: Sony, Microsoft, Nintendo, Valve\n\n### Bots & Crawlers (50+ supported)\n- **Search Engines**: Googlebot, Bingbot, Yahoo Slurp, Baidu Spider\n- **AI Crawlers**: GPTBot, ClaudeBot, PerplexityBot (2024-2025)\n- **Social Media**: Facebook, Twitter, LinkedIn, Pinterest bots\n- **SEO Tools**: Ahrefs, Semrush, Majestic crawlers\n- **Monitoring**: UptimeRobot, Pingdom, DataDog\n\n## 🎯 Performance\n\nFastDetect is optimized for high-throughput API usage:\n\n- **Speed**: 5,000,000+ detections per second (cached)\n- **Memory**: < 1MB memory usage with default cache\n- **Latency**: Sub-microsecond response time for cached UAs\n- **Accuracy**: 99%+ accuracy for known devices\n- **Cache Hit Rate**: 85-95% in typical usage\n\n### Benchmark Results\n\n```\nFastDetect Performance Benchmarks (Node.js v20, Apple M-series)\n───────────────────────────────────────────────────────────────\n✓ Mixed Workload:      5,745,475 ops/sec  (0.0002ms avg)\n✓ Cache Hit:           8,565,310 ops/sec  (0.0001ms avg)\n✓ Mobile Detection:    4,824,509 ops/sec  (0.0002ms avg)\n✓ Cold Parse:            170,703 ops/sec  (0.006ms avg)\n✓ Memory per Detection:  0.82 KB\n```\n\n## 🔧 Configuration\n\n### Cache Configuration\n\n```typescript\nconst detector = new FastDetect({\n  cacheSize: 2000,        // Increase cache for high-traffic APIs\n  skipCache: false        // Enable caching for better performance\n});\n\n// Monitor cache performance\nconst stats = detector.getCacheStats();\nconsole.log(`Cache hit rate: ${stats.hitRate}%`);\n```\n\n### Memory Management\n\n```typescript\n// Clear cache periodically in long-running processes\nsetInterval(() => {\n  const stats = detector.getCacheStats();\n  if (stats.hitRate < 50) {\n    detector.clearCache(); // Clear ineffective cache\n  }\n}, 300000); // Every 5 minutes\n```\n\n### Cache sizing and tradeoffs\n\n- **What the cache does**: Stores parsed results by exact user agent string for O(1) reuse. Great when UA strings repeat; less useful when every request is unique.\n- **Memory vs. speed**: Larger caches increase hit rate (more reuse) but consume more memory. With typical detection results, expect roughly ~0.7–0.9 KB per cached entry. For example, a cacheSize of 5,000 used ~7.5 MB in our stress test with 10,000 unique UAs.\n- **When to increase cache**: High-traffic APIs with meaningful UA repetition (e.g., mobile apps, crawlers, corporate fleets). Aim for hitRate ≥ 80%.\n- **When to decrease/disable cache**: Workloads with many unique UAs (e.g., logs/backfills). If hitRate < 50%, consider smaller cache or disabling per-call.\n\nRecommended defaults by environment:\n- **Serverless/function**: `cacheSize: 200–1000`\n- **Container/service (2–4 GB RAM)**: `cacheSize: 1000–5000`\n- **Batch/log processing (low repetition)**: use `skipCache: true` on parse calls\n\nExamples\n\n```typescript\n// 1) Tune via env var with safe default\nconst detector = new FastDetect({\n  cacheSize: Number(process.env.FD_CACHE_SIZE ?? 1000)\n});\n\n// 2) Disable caching for specific calls (e.g., batch jobs)\ndetector.parse(ua, { skipCache: true });\n\n// 3) Monitor and adjust based on hit rate\nconst { hitRate, size, capacity } = detector.getCacheStats();\nif (hitRate < 50) {\n  // Consider recreating detector with a smaller cacheSize or using skipCache\n}\n```\n\n## 🚦 Browser Usage Warning\n\n**⚠️ Important**: FastDetect is optimized for **server-side usage**. For browser usage, consider the lightweight alternatives:\n\n```typescript\n// ✅ Recommended for browsers (lightweight)\nimport { BrowserParser } from '@cookiefirst/fastdetect/parsers/browser';\n\nconst browserParser = new BrowserParser();\nconst browser = browserParser.parse(navigator.userAgent);\n```\n\n## 📈 Migration Guide\n\n### From ua-parser-js\n\n```typescript\n// Before (ua-parser-js)\nimport { UAParser } from 'ua-parser-js';\nconst parser = new UAParser();\nconst result = parser.setUA(userAgent).getResult();\n\n// After (FastDetect)\nimport FastDetect from '@cookiefirst/fastdetect';\nconst detector = new FastDetect();\nconst result = detector.parse(userAgent);\n\n// Mapping\nresult.browser.name    // ✓ Same\nresult.device.type     // ✓ Same concept\nresult.os.name         // ✓ Same\n```\n\n### From mobile-detect\n\n```typescript\n// Before (mobile-detect)\nimport MobileDetect from 'mobile-detect';\nconst md = new MobileDetect(userAgent);\nconst isMobile = md.mobile();\n\n// After (FastDetect) \nimport FastDetect from '@cookiefirst/fastdetect';\nconst detector = new FastDetect();\nconst isMobile = detector.isMobile(userAgent);\n```\n\n## 🧪 Testing\n\n```bash\nnpm test                # Run all tests\nnpm run test:coverage   # Run with coverage\nnpm run benchmark       # Performance benchmarks\n```\n\n## 📄 License\n\nAGPL-3.0 License - see [LICENSE](LICENSE) file for details.\n\n## 🤝 Contributing\n\nContributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\ngit clone https://github.com/cookiefirst-dds/fastdetect.git\ncd fastdetect\nnpm install\nnpm run build\nnpm test\n```\n\n### Adding New Device Patterns\n\n1. **Add pattern to parser**: Update the relevant parser in `src/parsers/`\n2. **Add test cases**: Create comprehensive test cases\n3. **Update documentation**: Document new detections\n4. **Performance test**: Ensure no regression in performance\n\n## 🔍 Examples\n\n### Real-World Usage Examples\n\n#### API Analytics Service\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\nimport express from 'express';\n\nconst app = express();\nconst detector = new FastDetect({ cacheSize: 10000 });\n\n// Analytics middleware\napp.use('/api', (req, res, next) => {\n  const userAgent = req.headers['user-agent'];\n  const detection = detector.parse(userAgent || '');\n  \n  // Log for analytics\n  console.log({\n    timestamp: Date.now(),\n    deviceType: detection.device.type,\n    browser: detection.browser.name,\n    os: detection.os.name,\n    isBot: detection.bot.isBot\n  });\n  \n  // Add to request for downstream handlers\n  req.deviceInfo = detection;\n  next();\n});\n\napp.get('/api/content', (req, res) => {\n  const { deviceInfo } = req;\n  \n  // Serve optimized content based on device\n  if (deviceInfo.device.type === 'smartphone') {\n    res.json({ content: 'mobile-optimized-content' });\n  } else {\n    res.json({ content: 'desktop-content' });\n  }\n});\n```\n\n#### Bot Detection Service\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\nfunction handleRequest(userAgent: string) {\n  const detection = detector.parse(userAgent);\n  \n  if (detection.bot.isBot) {\n    console.log(`Bot detected: ${detection.bot.name} (${detection.bot.category})`);\n    \n    // Handle different bot types\n    switch (detection.bot.category) {\n      case 'search-engine':\n        return { action: 'allow', priority: 'high' };\n      case 'ai-crawler':\n        return { action: 'rate-limit', priority: 'medium' };\n      case 'seo-tool':\n        return { action: 'allow', priority: 'low' };\n      default:\n        return { action: 'block', priority: 'none' };\n    }\n  }\n  \n  return { action: 'allow', priority: 'high' };\n}\n```\n\n#### Device-Specific Feature Detection\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\nfunction getAvailableFeatures(userAgent: string) {\n  const detection = detector.parse(userAgent);\n  const features = [];\n  \n  // Device-specific features\n  switch (detection.device.type) {\n    case 'smartphone':\n      features.push('touch', 'geolocation', 'camera', 'push-notifications');\n      break;\n    case 'tablet':\n      features.push('touch', 'large-screen', 'orientation');\n      break;\n    case 'desktop':\n      features.push('keyboard', 'mouse', 'large-screen', 'file-system');\n      break;\n    case 'smart-tv':\n      features.push('large-screen', 'remote-control');\n      break;\n  }\n  \n  // Browser-specific features\n  if (detection.browser.name === 'Chrome' && \n      parseInt(detection.browser.major || '0') >= 90) {\n    features.push('webrtc', 'webassembly', 'service-worker');\n  }\n  \n  return features;\n}\n```\n\n### Batch Processing Example\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect({ cacheSize: 5000 });\n\n// Process large user agent logs efficiently\nfunction processUserAgentLogs(userAgents: string[]) {\n  const results = [];\n  const uniqueUAs = [...new Set(userAgents)]; // Deduplicate for performance\n  \n  // Process unique user agents once\n  const detectionMap = new Map();\n  for (const ua of uniqueUAs) {\n    detectionMap.set(ua, detector.parse(ua));\n  }\n  \n  // Map results back to original array\n  for (const ua of userAgents) {\n    results.push(detectionMap.get(ua));\n  }\n  \n  return results;\n}\n```\n\n## 🔬 Advanced Configuration\n\n### Custom Pattern Extensions\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\nimport { DeviceParser } from '@cookiefirst/fastdetect/parsers/device';\n\n// Extend DeviceParser for custom patterns\nclass CustomDeviceParser extends DeviceParser {\n  parse(userAgent: string) {\n    const result = super.parse(userAgent);\n    \n    // Add custom business logic\n    if (userAgent.includes('CustomDevice')) {\n      result.brand = 'CustomBrand';\n      result.model = 'Custom Model';\n    }\n    \n    return result;\n  }\n}\n\nconst detector = new FastDetect();\n// Replace internal parser (advanced usage)\ndetector['deviceParser'] = new CustomDeviceParser();\n```\n\n### Performance Monitoring\n\n```typescript\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect({ cacheSize: 2000 });\n\n// Monitor performance metrics\nsetInterval(() => {\n  const stats = detector.getCacheStats();\n  \n  console.log('FastDetect Performance Metrics:');\n  console.log(`Cache Size: ${stats.size}/${stats.capacity}`);\n  console.log(`Hit Rate: ${stats.hitRate}%`);\n  console.log(`Total Hits: ${stats.hits}`);\n  console.log(`Total Misses: ${stats.misses}`);\n  \n  // Alert if performance degrades\n  if (stats.hitRate < 70) {\n    console.warn('Cache hit rate below 70%, consider increasing cache size');\n  }\n}, 60000); // Every minute\n```\n\n## 🌐 Framework Integration\n\n### Next.js Integration\n\n```typescript\n// pages/api/device-info.ts\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\nexport default function handler(req: NextApiRequest, res: NextApiResponse) {\n  const userAgent = req.headers['user-agent'] || '';\n  const deviceInfo = detector.parse(userAgent);\n  \n  res.status(200).json(deviceInfo);\n}\n\n// Middleware example\n// middleware.ts\nimport { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\nexport function middleware(request: NextRequest) {\n  const userAgent = request.headers.get('user-agent') || '';\n  const deviceInfo = detector.parse(userAgent);\n  \n  // Add device info to headers\n  const response = NextResponse.next();\n  response.headers.set('x-device-type', deviceInfo.device.type);\n  response.headers.set('x-is-mobile', deviceInfo.device.type === 'smartphone' ? 'true' : 'false');\n  \n  return response;\n}\n```\n\n### Fastify Plugin\n\n```typescript\nimport fastify from 'fastify';\nimport FastDetect from '@cookiefirst/fastdetect';\n\nconst detector = new FastDetect();\n\n// Create Fastify plugin\nconst deviceDetectionPlugin = async (fastify: any) => {\n  fastify.decorateRequest('device', null);\n  \n  fastify.addHook('preHandler', async (request: any) => {\n    const userAgent = request.headers['user-agent'] || '';\n    request.device = detector.parse(userAgent);\n  });\n};\n\nconst app = fastify();\napp.register(deviceDetectionPlugin);\n\napp.get('/api/info', async (request: any, reply) => {\n  return { deviceInfo: request.device };\n});\n```\n\n## 📊 Type Definitions\n\n### Complete TypeScript Interfaces\n\n```typescript\ninterface DetectionResult {\n  browser: BrowserInfo;\n  os: OSInfo;\n  device: DeviceInfo;\n  bot: BotInfo;\n  userAgent: string;\n  timestamp: number;\n}\n\ninterface BrowserInfo {\n  name: string;\n  version: string | null;\n  major: string | null;\n  engine?: string;\n  isMobile?: boolean;\n  isWebView?: boolean;\n}\n\ninterface DeviceInfo {\n  type: 'smartphone' | 'tablet' | 'desktop' | 'laptop' | 'smart-tv' | \n        'gaming-console' | 'wearable' | 'iot-device' | 'automotive' | \n        'vr-headset' | 'e-reader' | 'unknown';\n  brand: string;\n  model: string | null;\n  marketingName?: string;\n}\n\ninterface OSInfo {\n  name: string;\n  version: string | null;\n  family?: string;\n  architecture?: string;\n}\n\ninterface BotInfo {\n  isBot: boolean;\n  name: string | null;\n  category: string | null;\n  company?: string;\n  purpose?: string;\n}\n```\n\n## 🚀 Performance Tips\n\n### Optimization Best Practices\n\n1. **Use Appropriate Cache Size**\n   ```typescript\n   // High-traffic API (>10k requests/min)\n   const detector = new FastDetect({ cacheSize: 5000 });\n   \n   // Low-traffic API (<1k requests/min)  \n   const detector = new FastDetect({ cacheSize: 500 });\n   ```\n\n2. **Deduplicate User Agents**\n   ```typescript\n   // Efficient batch processing\n   const uniqueUAs = [...new Set(userAgents)];\n   const results = uniqueUAs.map(ua => detector.parse(ua));\n   ```\n\n3. **Use Quick Detection Methods**\n   ```typescript\n   // Fast path for simple checks\n   if (detector.isMobile(userAgent)) {\n     // Mobile-specific logic\n   } else {\n     // Desktop logic\n   }\n   ```\n\n4. **Monitor Cache Performance**\n   ```typescript\n   const stats = detector.getCacheStats();\n   if (stats.hitRate < 80) {\n     // Consider increasing cache size or investigating patterns\n   }\n   ```\n\n## 🛠️ Troubleshooting\n\n### Common Issues\n\n**Q: High memory usage**\nA: Reduce cache size or clear cache periodically\n```typescript\ndetector.clearCache(); // Clear when hit rate is low\n```\n\n**Q: Low cache hit rate**\nA: User agents are highly diverse; increase cache size\n```typescript\nconst detector = new FastDetect({ cacheSize: 3000 });\n```\n\n**Q: Inaccurate detection**\nA: Please report with user agent string for pattern updates\n\n**Q: Bundle size too large**\nA: Use modular imports for tree-shaking\n```typescript\nimport { BrowserParser } from '@cookiefirst/fastdetect/parsers/browser';\n```\n\n## 📞 Support\n\n- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/cookiefirst-dds/fastdetect/issues)\n- 💡 **Feature Requests**: [GitHub Discussions](https://github.com/cookiefirst-dds/fastdetect/discussions)\n\n## 🏆 Acknowledgments\n\n> **Note**: Acknowledgments reflect inspiration for patterns and API design. No code was copied from these sources.\n\n- **51Degrees** - Device database inspiration\n- **Matomo Device Detector** - Pattern organization concepts  \n- **ua-parser-js** - API design reference\n- **Bowser** - Performance optimization techniques\n\n---\n\n**Made with ❤️ for the JavaScript community**\n\n*FastDetect is optimized for production API usage. Star ⭐ us on GitHub if this project helps you!*","readmeFilename":"README.md"}