Skip to content

suneelkumarr/cache-shield-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ Cache Shield SDK

Clear browser caches from client-side with ease. Service Workers, Storage, IndexedDB, Cookies & more.

npm version bundle size TypeScript

✨ Features

  • 🧹 Clear All Cache Types - Service Workers, Cache API, localStorage, sessionStorage, IndexedDB, Cookies
  • ⚑ Lightweight - ~4KB gzipped, zero dependencies
  • 🎯 Selective Clearing - Target specific caches, preserve essential data
  • πŸ›‘οΈ Mobile Optimized - BfCache protection & Smart Reloading for iOS/Android
  • πŸ”Œ Framework Plugins - React, Vue, Svelte, Preact
  • πŸ“¦ TypeScript - Full type definitions included
  • 🌐 Universal - Works in any browser environment

πŸ“¦ Installation

npm install cache-shield-sdk
# or
yarn add cache-shield-sdk
# or
pnpm add cache-shield-sdk

πŸ“‚ Examples

Check out the examples directory for complete working demos:

  • Basic - Vanilla JS implementation
  • React - React Hook & Component usage
  • Vue 3 - Vue Composable & Plugin usage

πŸš€ Quick Start

Basic Usage

import CacheShield from 'cache-shield-sdk';

// Create instance
const shield = new CacheShield();

// Clear all caches
await shield.clear();

// Clear specific types
await shield.clearServiceWorkers();
await shield.clearLocalStorage();
await shield.clearCookies();

One-liner

import { clearCache } from 'cache-shield-sdk';

await clearCache(); // Clears everything!

With Options

const shield = new CacheShield({
  targets: ['localStorage', 'sessionStorage', 'cookies'],
  cookies: {
    preserveEssential: true,
    essentialCookies: ['auth_token', 'csrf']
  },
  storage: {
    preserveKeys: ['user_preferences']
  },
  debug: true,
  autoReload: true
});

const result = await shield.clear();
console.log(`Cleared ${result.cleared.length} cache types`);

βš›οΈ React

import { CacheShieldProvider, useCacheShield, ClearCacheButton } from 'cache-shield-sdk/react';

// Wrap your app
function App() {
  return (
    <CacheShieldProvider config={{ debug: true }}>
      <MyComponent />
    </CacheShieldProvider>
  );
}

// Use the hook
function MyComponent() {
  const { clear, isClearing, lastResult } = useCacheShield();

  return (
    <div>
      <button onClick={() => clear()} disabled={isClearing}>
        {isClearing ? 'Clearing...' : 'Clear Cache'}
      </button>
      
      {/* Or use the built-in button */}
      <ClearCacheButton onSuccess={(result) => console.log(result)} />
    </div>
  );
}

πŸ’š Vue 3

// main.ts
import { createApp } from 'vue';
import { CacheShieldPlugin } from 'cache-shield-sdk/vue';

const app = createApp(App);
app.use(CacheShieldPlugin, { debug: true });
app.mount('#app');

// Component
<script setup>
import { useCacheShield } from 'cache-shield-sdk/vue';

const { clear, isClearing, capabilities } = useCacheShield();
</script>

<template>
  <button @click="clear()" :disabled="isClearing">
    {{ isClearing ? 'Clearing...' : 'Clear Cache' }}
  </button>
</template>

🧑 Svelte

// App.svelte
<script>
  import { onMount } from 'svelte';
  import { createCacheShieldStore, setCacheShield } from 'cache-shield-sdk/svelte';
  
  const store = createCacheShieldStore({ debug: true });
  setCacheShield(store);
</script>

<slot />

// Component.svelte
<script>
  import { useCacheShield } from 'cache-shield-sdk/svelte';
  const { clear, isClearing } = useCacheShield();
</script>

<button on:click={() => clear()} disabled={$isClearing}>
  {$isClearing ? 'Clearing...' : 'Clear Cache'}
</button>

βš›οΈ Preact

import { CacheShieldProvider, useCacheShield } from 'cache-shield-sdk/preact';

function App() {
  return (
    <CacheShieldProvider config={{ debug: true }}>
      <MyComponent />
    </CacheShieldProvider>
  );
}

🌐 CDN / Browser

<script src="https://unpkg.com/cache-shield-sdk"></script>
<script>
  const shield = new CacheShield.default();
  shield.clear().then(result => {
    console.log('Cache cleared!', result);
  });
</script>

πŸ“‹ API Reference

CacheShield

Constructor Options

Option Type Default Description
targets CacheType[] ['all'] Cache types to clear
include (string | RegExp)[] [] Only clear matching patterns
exclude (string | RegExp)[] [] Skip matching patterns
cookies CookieOptions {} Cookie-specific options
storage StorageOptions {} Storage-specific options
indexedDB IndexedDBOptions {} IndexedDB-specific options
debug boolean false Enable debug logging
autoReload boolean false Reload after clearing
preventBfCache boolean false Force reload on back button (iOS fix)
hooks CacheShieldHooks {} Lifecycle callbacks

Methods

Method Returns Description
clear(options?) Promise<ClearResult> Clear all targeted caches
clearServiceWorkers() Promise<CacheTypeResult> Clear only Service Workers
clearCacheAPI() Promise<CacheTypeResult> Clear only Cache API
clearLocalStorage() Promise<CacheTypeResult> Clear only localStorage
clearSessionStorage() Promise<CacheTypeResult> Clear only sessionStorage
clearIndexedDB() Promise<CacheTypeResult> Clear only IndexedDB
clearCookies() Promise<CacheTypeResult> Clear only cookies
hardReload() void Force reload bypassing cache
clearAndReload(options?) Promise<void> Clear then reload
getStorageEstimate() Promise<StorageEstimate> Get storage usage
getCapabilities() Capabilities Check browser support

Types

type CacheType = 
  | 'all'
  | 'serviceWorker'
  | 'cacheAPI'
  | 'localStorage'
  | 'sessionStorage'
  | 'indexedDB'
  | 'cookies';

interface ClearResult {
  success: boolean;
  cleared: CacheTypeResult[];
  failed: CacheTypeResult[];
  timestamp: number;
  duration: number;
}

🎯 Common Use Cases

PWA Update Handler

const shield = new CacheShield({
  targets: ['serviceWorker', 'cacheAPI'],
  hooks: {
    onAfterClear: () => {
      // Show "New version available" toast
      showUpdateNotification();
    }
  }
});

// When user clicks "Update"
await shield.clearAndReload();

Logout Cleanup

async function logout() {
  await shield.clear({
    targets: ['localStorage', 'sessionStorage', 'cookies', 'indexedDB'],
    cookies: {
      preserveEssential: false // Clear everything including auth
    }
  });
  
  window.location.href = '/login';
}

Debug Mode

const shield = new CacheShield({
  debug: true,
  hooks: {
    onProgress: ({ current, percentage }) => {
      console.log(`Clearing ${current}: ${percentage}%`);
    }
  }
});

πŸ“Š Browser Support

Feature Chrome Firefox Safari Edge
Service Workers βœ… 40+ βœ… 44+ βœ… 11.1+ βœ… 17+
Cache API βœ… 40+ βœ… 39+ βœ… 11.1+ βœ… 16+
localStorage βœ… All βœ… All βœ… All βœ… All
IndexedDB βœ… 23+ βœ… 10+ βœ… 10+ βœ… 12+

πŸ“„ License

MIT Suneel Kumar

About

cache-shield-sdk - A lightweight TypeScript SDK for clearing browser caches from the client-side.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors