Smart offline-first JavaScript SDK with intelligent caching for web applications
npm install @soham20/smart-offline-sdkbash
npm install @soham20/smart-offline-sdk
`
Or directly from GitHub:
`bash
npm install git+https://github.com/OwaisShaikh1/Hackvision2026.git
`
Quick Start
`javascript
import { setupSmartOffline } from "@soham20/smart-offline-sdk";
// Initialize early in your app
await setupSmartOffline({
pages: ["/dashboard/", "/products/"],
apis: ["/api/v1/*"],
debug: true,
});
`
Configuration Options
| Option | Type | Default | Description |
| -------------------- | --------------------------------- | ------------------------ | ------------------------------------------------------- |
| pages | string[] | [] | URL patterns for pages to cache (supports * wildcard) |
| apis | string[] | [] | URL patterns for API endpoints to cache |
| debug | boolean | false | Enable debug logging in console |
| frequencyThreshold | number | 3 | Number of accesses before URL is high priority |
| recencyThreshold | number | 86400000 | Time in ms for "recent" access (default: 24h) |
| maxResourceSize | number | 10485760 | Max bytes to cache per resource (default: 10MB) |
| networkQuality | 'auto' \| 'slow' \| 'fast' | 'auto' | Network quality detection mode |
| significance | Record | {} | Priority overrides for URL patterns |
| weights | { frequency, recency, size } | { 1, 1, 1 } | Weights for priority calculation |
| customPriorityFn | Function | null | Custom priority function (0-100) |
| enableDetailedLogs | boolean | false | Enable detailed event logging |
| onCacheEvent | Function | undefined | Callback for cache events |
| serviceWorkerPath | string | '/smart-offline-sw.js' | Path to service worker file |
| serviceWorkerScope | string | '/' | Service worker scope |
Complete Example
`javascript
import { setupSmartOffline, SmartOffline } from "@soham20/smart-offline-sdk";
// Full configuration example
const result = await setupSmartOffline({
// URL patterns to cache
pages: ["/admin/", "/dashboard", "/products/"],
apis: ["/api/v1/*", "/graphql"],
// Enable debug logging
debug: true,
// Priority tuning
frequencyThreshold: 5, // 5 accesses = high priority
recencyThreshold: 12 60 60 * 1000, // 12 hours
maxResourceSize: 5 1024 1024, // 5MB max
// Network detection
networkQuality: "auto",
// Manual priority overrides
significance: {
"/api/critical/*": "high", // Always cache
"/api/logs/*": "low", // Never cache
},
// Weight configuration
weights: {
frequency: 2, // Frequency is 2x more important
recency: 1,
size: 1,
},
// Custom priority function
customPriorityFn: (usage, url, config) => {
if (url.includes("vip")) return 100;
if (!usage) return 0;
return usage.count >= 5 ? 100 : 25;
},
// Event callback
onCacheEvent: (event) => {
console.log(Cache event: ${event.type}, event.url);
},
});
if (result.success) {
console.log("SmartOffline ready!");
}
`
API Reference
$3
`javascript
import {
setupSmartOffline, // Initialize SDK (async)
updateConfig, // Update config at runtime
getConfig, // Get current configuration
isSmartOfflineReady, // Check if initialized
clearAllCache, // Clear all cached data
getCacheStats, // Get cache statistics
forceUpdate, // Force SW update
uninstall, // Uninstall SDK
} from "@soham20/smart-offline-sdk";
`
$3
`javascript
import { on, off } from "@soham20/smart-offline-sdk";
// Listen for cache events
on("cache", (event) => console.log("Cached:", event.url));
on("skip", (event) => console.log("Skipped:", event.url));
on("serve", (event) => console.log("Served from cache:", event.url));
on("error", (event) => console.log("Error:", event.url));
// Remove listener
off("cache", myCallback);
`
$3
`javascript
import { SmartOffline } from "@soham20/smart-offline-sdk";
// All methods available on SmartOffline object
SmartOffline.setup(config); // setupSmartOffline
SmartOffline.updateConfig(cfg); // Update configuration
SmartOffline.getConfig(); // Get current config
SmartOffline.isReady(); // Check if ready
SmartOffline.clearCache(); // Clear all cache
SmartOffline.getStats(); // Get cache stats
SmartOffline.forceUpdate(); // Force SW update
SmartOffline.uninstall(); // Clean uninstall
`
Test Utilities
`javascript
import {
SmartOfflineTestSuite,
runSmartOfflineTests,
CacheInspector,
} from "@soham20/smart-offline-sdk";
// Run all tests
const results = await runSmartOfflineTests();
// Or use the test suite directly
const suite = new SmartOfflineTestSuite({ pages: ["/test/*"] });
await suite.runAll();
suite.printResults();
// Inspect cache
const inspector = new CacheInspector();
await inspector.showAll();
const data = await inspector.getAllData();
`
Browser Console Testing
`javascript
// After SDK is loaded, these are available globally:
await runSmartOfflineTests();
await SmartOffline.getStats();
new CacheInspector().showAll();
`
How the Algorithm Works
1. URL Pattern Matching: Caches pages/APIs matching configured patterns
2. Frequency Scoring: URLs accessed >= frequencyThreshold times get higher score
3. Recency Scoring: URLs accessed within recencyThreshold get higher score
4. Weighted Calculation:
- frequencyScore = min(100, (accessCount / threshold) * 100)
- recencyScore = max(0, 100 - (timeSinceAccess / threshold) * 100)
- weightedScore = (freqScore freqWeight + recencyScore recencyWeight) / totalWeight
- HIGH priority if weightedScore > 50
5. Network Awareness: On slow networks, only HIGH priority resources are cached
6. Size Limits: Resources exceeding maxResourceSize are skipped
Service Worker Setup
Copy smart-offline-sw.js to your public directory:
`bash
cp node_modules/@soham20/smart-offline-sdk/smart-offline-sw.js public/
`
TypeScript
Full TypeScript support with exported types:
`typescript
import type {
SmartOfflineConfig,
CacheEvent,
UsageData,
SetupResult,
CacheStats,
} from "@soham20/smart-offline-sdk";
``