{"_id":"@beshu-tech/trcf-ts","_rev":"2-84c4303217f3da19dea240159eeeae6a","name":"@beshu-tech/trcf-ts","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.0":{"name":"@beshu-tech/trcf-ts","version":"1.0.0","keywords":["anomaly-detection","time-series","machine-learning","random-cut-forest","trcf","streaming","typescript","monitoring","alerting","aws","performance","real-time","beshu"],"author":{"name":"Beshu Limited"},"license":"Apache-2.0","_id":"@beshu-tech/trcf-ts@1.0.0","maintainers":[{"name":"sscarduzio","email":"scarduzio@gmail.com"}],"homepage":"https://github.com/beshu-tech/trcf-ts#readme","bugs":{"url":"https://github.com/beshu-tech/trcf-ts/issues"},"dist":{"shasum":"2e6744cd8ab57d74fc159292dbb68ebd772208bf","tarball":"https://registry.npmjs.org/@beshu-tech/trcf-ts/-/trcf-ts-1.0.0.tgz","fileCount":68,"integrity":"sha512-GXpVH6v4Y9NOHau1/sDZ6Fh03srL9dXUBNHFCsGyXvjDE6ol4kawCKLcZGMjJbIkKZ/qL1WMATwYFVD8YrXPig==","signatures":[{"sig":"MEUCIEJfWvXKR4LfZQo2o8CN8YeMIZYETZZTtlYn/XzzZIBRAiEAnBVtZ0SteazjBkzCx8fSDLyGWXxsDdyShyQMOJgHC1M=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":229124},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=14.0.0"},"gitHead":"48125e720ae0fff9efe3dc72861e9fb7e442f8f9","scripts":{"test":"jest","build":"tsc","clean":"rm -rf dist","test:watch":"jest --watch","test:coverage":"jest --coverage"},"_npmUser":{"name":"sscarduzio","email":"scarduzio@gmail.com"},"repository":{"url":"git+https://github.com/beshu-tech/trcf-ts.git","type":"git"},"_npmVersion":"10.9.2","description":"TypeScript implementation of AWS Thresholded Random Cut Forest for anomaly detection","directories":{},"_nodeVersion":"22.16.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^30.1.3","ts-jest":"^29.4.2","typescript":"^5.9.2","@types/jest":"^30.0.0","@types/node":"^24.5.0"},"_npmOperationalInternal":{"tmp":"tmp/trcf-ts_1.0.0_1758036485127_0.8594019214545918","host":"s3://npm-registry-packages-npm-production"}},"1.1.0":{"name":"@beshu-tech/trcf-ts","version":"1.1.0","description":"TypeScript implementation of AWS Thresholded Random Cut Forest for anomaly detection","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","clean":"rm -rf dist"},"keywords":["anomaly-detection","time-series","machine-learning","random-cut-forest","trcf","streaming","typescript","monitoring","alerting","aws","performance","real-time","beshu"],"author":{"name":"Beshu Limited"},"license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/beshu-tech/trcf-ts.git"},"homepage":"https://github.com/beshu-tech/trcf-ts#readme","bugs":{"url":"https://github.com/beshu-tech/trcf-ts/issues"},"engines":{"node":">=14.0.0"},"devDependencies":{"@types/jest":"^30.0.0","@types/node":"^24.5.0","jest":"^30.1.3","ts-jest":"^29.4.2","typescript":"^5.9.2"},"_id":"@beshu-tech/trcf-ts@1.1.0","gitHead":"36de9e358b50bfaf32e15aff296da3c95b9e7255","_nodeVersion":"22.16.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-IHOGjEKyz2iT/kZ6SSoMPNluOwQ7rvErRMzZt5pRZ0Dn0QgEkifYXGbTTIb6VR4qcvRo/2vOU0MD/zhLnM+Rlw==","shasum":"515cfc40652c058841610dbfee25fd3c035db445","tarball":"https://registry.npmjs.org/@beshu-tech/trcf-ts/-/trcf-ts-1.1.0.tgz","fileCount":68,"unpackedSize":210676,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIG1d/vhfEN0rHN5Y9cSUmyNXc7N0pL23hFQ/mJ6h0DLQAiAHYyyi47uYpp81naHgXU5g0pLybQhrGueIss4RshOqhQ=="}]},"_npmUser":{"name":"sscarduzio","email":"scarduzio@gmail.com"},"directories":{},"maintainers":[{"name":"sscarduzio","email":"scarduzio@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/trcf-ts_1.1.0_1758119463384_0.9999507817865034"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-16T15:28:05.052Z","modified":"2025-09-17T14:31:03.744Z","1.0.0":"2025-09-16T15:28:05.341Z","1.1.0":"2025-09-17T14:31:03.561Z"},"bugs":{"url":"https://github.com/beshu-tech/trcf-ts/issues"},"author":{"name":"Beshu Limited"},"license":"Apache-2.0","homepage":"https://github.com/beshu-tech/trcf-ts#readme","keywords":["anomaly-detection","time-series","machine-learning","random-cut-forest","trcf","streaming","typescript","monitoring","alerting","aws","performance","real-time","beshu"],"repository":{"type":"git","url":"git+https://github.com/beshu-tech/trcf-ts.git"},"description":"TypeScript implementation of AWS Thresholded Random Cut Forest for anomaly detection","maintainers":[{"name":"sscarduzio","email":"scarduzio@gmail.com"}],"readme":"# TRCF TypeScript - Real-time Anomaly Detection 🚨\n\n**Catch anomalies in your data streams before they become incidents.** Production-ready TypeScript implementation of AWS's Thresholded Random Cut Forest algorithm with up to **100K+ ops/sec** throughput and **25-58x faster** than Java.\n\n[![npm version](https://img.shields.io/npm/v/@beshu-tech/trcf-ts.svg)](https://www.npmjs.com/package/@beshu-tech/trcf-ts)\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)\n[![CI](https://img.shields.io/badge/CI-GitHub%20Actions-green.svg)](.github/workflows/ci.yml)\n[![Performance](https://img.shields.io/badge/Throughput-100K%2B%20ops%2Fsec-orange.svg)](#performance)\n\n## Why TRCF?\n\n✅ **Real-time Detection** - Process streaming data with 0.017ms latency\n✅ **Self-Learning** - Adapts to your data patterns automatically\n✅ **Production Ready** - Battle-tested algorithm from AWS\n✅ **Zero Config** - Works out of the box with sensible defaults\n✅ **TypeScript Native** - Full type safety and IntelliSense support\n\n## Java Comparison 🔥\n\n| Aspect | Implementation | Status |\n|--------|---------------|--------|\n| Precision | Float64Array | ✅ Exact |\n| Random | Java LCG | ✅ Exact |\n| Defaults | All aligned | ✅ Exact |\n| Score Accuracy | - | 91-96% match |\n| Performance | - | 25-58x faster |\n\n## Installation\n\n```bash\nnpm install @beshu-tech/trcf-ts\n```\n\n## Quick Start - 30 Seconds to First Anomaly\n\n```typescript\nimport { createTimeSeriesDetector } from '@beshu-tech/trcf-ts';\n\n// Create detector\nconst detector = createTimeSeriesDetector();\n\n// Feed your data\nconst metrics = [50, 52, 48, 51, 200, 49, 52]; // Anomaly at 200!\n\nmetrics.forEach(value => {\n  const result = detector.detect([value]);\n\n  if (result.isAnomaly) {\n    console.log(`🚨 Anomaly detected: ${value}`);\n    // Send alert, trigger automation, etc.\n  }\n});\n```\n\nThat's it! The detector automatically learns what's normal and flags anomalies.\n\n## Real-World Use Cases\n\n### 🖥️ Server Monitoring\n```typescript\nconst detector = createTimeSeriesDetector({\n  anomalyRate: 0.01  // Expect 1% anomalies\n});\n\n// Monitor CPU usage\nsetInterval(async () => {\n  const cpu = await getCpuUsage();\n  const result = detector.detect([cpu]);\n\n  if (result.isAnomaly && result.confidence > 0.8) {\n    await scaleUpServers();\n    await notifyOpsTeam(`CPU spike: ${cpu}%`);\n  }\n}, 1000);\n```\n\n### 💳 Fraud Detection\n```typescript\nconst detector = createMultiVariateDetector({\n  anomalyRate: 0.001,  // Very low false positives\n  numberOfTrees: 50    // Higher accuracy\n});\n\nfunction checkTransaction(amount, frequency, riskScore, timeSinceLast) {\n  const result = detector.detect([amount, frequency, riskScore, timeSinceLast]);\n\n  if (result.isAnomaly) {\n    return {\n      action: 'REVIEW',\n      confidence: result.confidence,\n      reason: `Anomaly score: ${result.grade.toFixed(3)}`\n    };\n  }\n  return { action: 'APPROVE' };\n}\n```\n\n### 🌡️ IoT Sensor Monitoring\n```typescript\nconst detector = createMultiVariateDetector({\n  timeAware: true  // Handle irregular readings\n});\n\nfunction processSensorData(temperature, humidity, pressure, timestamp) {\n  const result = detector.detect(\n    [temperature, humidity, pressure],\n    timestamp\n  );\n\n  if (result.isAnomaly) {\n    // Sensor malfunction or environmental anomaly\n    logIncident({\n      severity: result.confidence > 0.9 ? 'HIGH' : 'MEDIUM',\n      readings: { temperature, humidity, pressure },\n      anomalyGrade: result.grade\n    });\n  }\n}\n```\n\n## API Overview\n\n### Simple API\n```typescript\n// Single metric monitoring\nconst detector = createTimeSeriesDetector(config?);\n\n// Multi-metric monitoring\nconst detector = createMultiVariateDetector(config?);\n\n// Detect anomaly\nconst result = detector.detect(values, timestamp?);\n\n// result = {\n//   isAnomaly: boolean,      // Is this anomalous?\n//   confidence: number,      // How confident? (0-1)\n//   grade: number,          // Anomaly severity (0-1)\n//   score: number,          // Raw anomaly score\n//   threshold: number       // Current threshold\n// }\n```\n\n### Configuration Options\n```typescript\n{\n  windowSize?: number,      // Memory size (default: 256)\n  anomalyRate?: number,     // Expected anomaly % (default: 0.005)\n  numberOfTrees?: number,   // Accuracy vs speed (default: 30)\n  normalize?: boolean,      // Auto-normalize (default: true)\n  timeAware?: boolean      // Use timestamps (default: false)\n}\n```\n\n## Performance\n\n**Blazing fast with minimal resource usage:**\n\n| Metric | Value | Comparison |\n|--------|-------|------------|\n| **Throughput** | 30-100K+ ops/sec* | 25-58x faster than Java |\n| **Latency P99** | <10 ms | Sub-millisecond |\n| **Accuracy** | 91-96% | Matches Java implementation |\n| **Memory** | ~1GB for 1M points | Efficient |\n| **Package Size** | <100 KB | Lightweight |\n\n*Throughput varies by configuration: 30K ops/sec (default: 30 trees, 256 samples), 100K+ ops/sec (optimized: 3-5 trees, 32-64 samples)\n\n## Getting Started\n\n### Step 1: Choose Your Detector Type\n\n```typescript\n// For single metrics (CPU, memory, temperature, etc.)\nimport { createTimeSeriesDetector } from '@beshu-tech/trcf-ts';\n\n// For multiple related metrics\nimport { createMultiVariateDetector } from '@beshu-tech/trcf-ts';\n\n// For advanced control\nimport { ThresholdedRandomCutForest } from '@beshu-tech/trcf-ts';\n```\n\n### Step 2: Configure for Your Use Case\n\n```typescript\n// High accuracy (more trees, stricter threshold)\nconst accurate = createTimeSeriesDetector({\n  numberOfTrees: 50,\n  anomalyRate: 0.001\n});\n\n// High performance (fewer trees, smaller window)\nconst fast = createTimeSeriesDetector({\n  numberOfTrees: 20,\n  windowSize: 128\n});\n\n// Irregular data (timestamps matter)\nconst irregular = createTimeSeriesDetector({\n  timeAware: true\n});\n```\n\n### Step 3: Process Your Data\n\n```typescript\n// Single point\nconst result = detector.detect([value]);\n\n// With timestamp\nconst result = detector.detect([value], Date.now());\n\n// Batch processing\nconst results = detector.detectBatch(values, timestamps);\n```\n\n### Step 4: Handle Anomalies\n\n```typescript\nif (result.isAnomaly && result.confidence > 0.7) {\n  // High confidence anomaly\n  await sendAlert(result);\n} else if (result.grade > 0.5) {\n  // Moderate anomaly\n  await logWarning(result);\n}\n```\n\n## Advanced Features\n\n<details>\n<summary><b>State Persistence</b> - Save and restore detector state</summary>\n\n```typescript\n// Save state\nconst state = detector.getState();\nawait saveToDatabase(state);\n\n// Restore state\nconst savedState = await loadFromDatabase();\nconst detector = AnomalyDetector.fromState(savedState);\n```\n</details>\n\n<details>\n<summary><b>Custom Forest Implementation</b> - Bring your own RCF</summary>\n\n```typescript\nimport { ThresholdedRandomCutForest, OptimizedRCF } from '@beshu-tech/trcf-ts';\n\nconst rcf = new OptimizedRCF({\n  dimensions: 4,\n  numberOfTrees: 30,\n  sampleSize: 256\n});\n\nconst trcf = new ThresholdedRandomCutForest({\n  dimensions: 4,\n  anomalyRate: 0.01\n});\n\ntrcf.setForest(rcf);\n```\n</details>\n\n<details>\n<summary><b>Fine-Tuned Configuration</b> - Full control</summary>\n\n```typescript\nconst detector = new ThresholdedRandomCutForest({\n  // Forest settings\n  dimensions: 4,\n  numberOfTrees: 30,\n  sampleSize: 256,\n  timeDecay: 0.001,\n\n  // Preprocessing\n  forestMode: ForestMode.TIME_AUGMENTED,\n  transformMethod: TransformMethod.NORMALIZE,\n  imputationMethod: ImputationMethod.PREVIOUS,\n\n  // Thresholding\n  anomalyRate: 0.01,\n  zFactor: 2.5,\n  autoAdjust: true\n});\n```\n</details>\n\n## Examples\n\nFull working examples in the [`examples/`](examples/) directory:\n- [`simple-usage.ts`](examples/simple-usage.ts) - Basic anomaly detection\n- [`complete-example.ts`](examples/complete-example.ts) - Advanced features\n\n## Contributing\n\nWe welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n## License\n\nApache 2.0 - See [LICENSE](LICENSE) for details.\n\nBased on [AWS Random Cut Forest](https://github.com/aws/random-cut-forest-by-aws).\n\n---\n\n## Technical Details\n\n<details>\n<summary><b>Architecture Overview</b></summary>\n\n### Data Flow Pipeline\n```\nInput → Preprocessor → RCF Forest → PredictorCorrector → Thresholder → Result\n         ↓               ↓            ↓                    ↓\n      Shingling    Anomaly Score  Correction      Grade/Threshold\n      Normalize    Attribution     Time Decay     Auto-adjust\n```\n\n### Key Components\n- **ThresholdedRandomCutForest**: Main orchestrator\n- **OptimizedRCF**: High-performance forest implementation\n- **Preprocessor**: Data transformation and shingling\n- **PredictorCorrector**: Score refinement and smoothing\n- **BasicThresholder**: Dynamic threshold calculation\n\n</details>\n\n\n<details>\n<summary><b>Benchmarks</b></summary>\n\nRun benchmarks:\n```bash\nnpm run build\nnpx ts-node benchmarks/java-typescript-comparison.ts\nnpx ts-node benchmarks/kibana-alerting-benchmark.ts\n```\n\nResults in [`benchmarks/results/`](benchmarks/results/).\n\n</details>\n\n<details>\n<summary><b>CI/CD Pipeline</b></summary>\n\nGitHub Actions automates:\n- Testing on Node 16/18/20\n- Coverage reporting\n- Auto version bump on merge\n- npm publishing\n\nSee [`.github/workflows/`](.github/workflows/) for configuration.\n\n</details>\n\n## Support\n\n- 📖 [Documentation](docs/)\n- 🐛 [Issue Tracker](https://github.com/beshu-tech/trcf-ts/issues)\n- 💬 [Discussions](https://github.com/beshu-tech/trcf-ts/discussions)\n- 📦 [npm Package](https://www.npmjs.com/package/@beshu-tech/trcf-ts)\n\n---\n\n**Ready to detect anomalies?** Install now and catch issues before they escalate:\n\n```bash\nnpm install @beshu-tech/trcf-ts\n```","readmeFilename":"README.md"}