CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-storybook--core-common

Deprecated compatibility shim for Storybook's framework-agnostic API utilities

Pending
Overview
Eval results
Files

caching.mddocs/

File System Caching

High-performance file system caching system with namespace support, TTL, and both synchronous and asynchronous operations. Built specifically for development workflow optimization and build performance.

Capabilities

FileSystemCache Class

Full-featured file system caching implementation with flexible configuration options.

/**
 * High-performance file system cache with TTL and namespace support
 */
class FileSystemCache {
  /**
   * Create a new file system cache instance
   * @param options - Cache configuration options
   */
  constructor(options?: {
    /** Cache namespace for isolation */
    ns?: string;
    /** Key prefix for all cache entries */
    prefix?: string;
    /** Hash algorithm for key generation */
    hash_alg?: string;
    /** Base path for cache storage */
    basePath?: string;
    /** Time-to-live in milliseconds */
    ttl?: number;
  });

  /**
   * Get cached value asynchronously
   * @param key - Cache key
   * @returns Promise resolving to cached value or undefined if not found/expired
   */
  get<T>(key: string): Promise<T | undefined>;

  /**
   * Get cached value synchronously
   * @param key - Cache key
   * @returns Cached value or undefined if not found/expired
   */
  getSync<T>(key: string): T | undefined;

  /**
   * Set cached value asynchronously
   * @param key - Cache key
   * @param value - Value to cache
   * @returns Promise resolving when value is cached
   */
  set<T>(key: string, value: T): Promise<void>;

  /**
   * Set cached value synchronously
   * @param key - Cache key
   * @param value - Value to cache
   */
  setSync<T>(key: string, value: T): void;

  /**
   * Set multiple cached values asynchronously
   * @param entries - Array of key-value pairs to cache
   * @returns Promise resolving when all values are cached
   */
  setMany<T>(entries: Array<[string, T]>): Promise<void>;

  /**
   * Set multiple cached values synchronously
   * @param entries - Array of key-value pairs to cache
   */
  setManySync<T>(entries: Array<[string, T]>): void;

  /**
   * Remove cached value asynchronously
   * @param key - Cache key to remove
   * @returns Promise resolving when value is removed
   */
  remove(key: string): Promise<void>;

  /**
   * Remove cached value synchronously
   * @param key - Cache key to remove
   */
  removeSync(key: string): void;

  /**
   * Clear all cached values asynchronously
   * @returns Promise resolving when cache is cleared
   */
  clear(): Promise<void>;

  /**
   * Clear all cached values synchronously
   */
  clearSync(): void;

  /**
   * Get all cached values asynchronously
   * @returns Promise resolving to array of key-value pairs
   */
  getAll<T>(): Promise<Array<[string, T]>>;

  /**
   * Load cache from disk
   * @returns Promise resolving when cache is loaded
   */
  load(): Promise<void>;
}

Usage Examples:

import { FileSystemCache } from "@storybook/core-common";

// Create cache with default settings
const cache = new FileSystemCache();

// Cache with custom configuration
const customCache = new FileSystemCache({
  ns: 'storybook-dev',
  prefix: 'build-',
  ttl: 60 * 60 * 1000, // 1 hour TTL
  basePath: './node_modules/.cache/storybook'
});

// Basic async operations
await cache.set('webpack-config', compiledConfig);
const config = await cache.get('webpack-config');

// Sync operations for performance-critical paths
cache.setSync('fast-lookup', data);
const result = cache.getSync('fast-lookup');

// Batch operations
await cache.setMany([
  ['stories', storyEntries],
  ['metadata', projectMeta],
  ['dependencies', deps]
]);

// Cleanup
await cache.remove('outdated-key');
await cache.clear();

Cache Factory Function

Factory function for creating FileSystemCache instances with predefined configurations.

/**
 * Create a FileSystemCache instance with specified options
 * @param options - Cache configuration options
 * @returns Configured FileSystemCache instance
 */
function createFileSystemCache(options?: {
  ns?: string;
  prefix?: string;
  hash_alg?: string;
  basePath?: string;
  ttl?: number;
}): FileSystemCache;

Usage Example:

import { createFileSystemCache } from "@storybook/core-common";

// Create specialized caches for different purposes
const buildCache = createFileSystemCache({
  ns: 'build',
  ttl: 24 * 60 * 60 * 1000 // 24 hours
});

const devCache = createFileSystemCache({
  ns: 'dev-server',
  ttl: 60 * 60 * 1000 // 1 hour
});

// Use for different data types
await buildCache.set('webpack-stats', stats);
await devCache.set('hot-reload-state', hmrState);

Default Cache Instance

Pre-configured cache instance for immediate use in development workflows.

/**
 * Default file system cache instance configured for Storybook dev-server
 */
declare const cache: FileSystemCache;

Usage Example:

import { cache } from "@storybook/core-common";

// Use default cache directly
const cachedStories = await cache.get('normalized-stories');
if (!cachedStories) {
  const stories = await processStories();
  await cache.set('normalized-stories', stories);
}

// Cache build artifacts
await cache.set('babel-config', babelConfig);
await cache.set('webpack-config', webpackConfig);

Cache Path Resolution

Utility for resolving paths within the Storybook cache directory.

/**
 * Resolve path within Storybook cache directory
 * @param name - Cache entry name
 * @param sub - Optional subdirectory
 * @returns Resolved cache path
 */
function resolvePathInStorybookCache(name: string, sub?: string): string;

Usage Example:

import { resolvePathInStorybookCache } from "@storybook/core-common";

// Get cache paths for manual file operations
const buildCachePath = resolvePathInStorybookCache('build-artifacts');
const metaCachePath = resolvePathInStorybookCache('metadata', 'stories');

// Use with other file operations
const fs = require('fs');
const configPath = resolvePathInStorybookCache('webpack.config.js');
fs.writeFileSync(configPath, configContent);

Advanced Caching Patterns

Conditional Caching

import { cache } from "@storybook/core-common";

async function getProcessedStories(configDir: string, isDev: boolean) {
  const cacheKey = `stories-${configDir}-${isDev ? 'dev' : 'prod'}`;
  
  // Try cache first
  let stories = await cache.get(cacheKey);
  
  if (!stories) {
    // Process stories if not cached
    stories = await processStoryEntries(configDir, isDev);
    
    // Cache with appropriate TTL
    await cache.set(cacheKey, stories);
  }
  
  return stories;
}

Cache Invalidation

import { cache } from "@storybook/core-common";

async function invalidateRelatedCache(pattern: string) {
  const allEntries = await cache.getAll();
  
  // Remove entries matching pattern
  const keysToRemove = allEntries
    .map(([key]) => key)
    .filter(key => key.includes(pattern));
    
  for (const key of keysToRemove) {
    await cache.remove(key);
  }
}

// Usage
await invalidateRelatedCache('webpack-'); // Remove all webpack-related cache

Performance Monitoring

import { cache } from "@storybook/core-common";

async function cachedOperation<T>(
  key: string, 
  operation: () => Promise<T>
): Promise<T> {
  const start = performance.now();
  
  // Try cache first
  let result = await cache.get<T>(key);
  
  if (result) {
    console.log(`Cache hit for ${key}: ${performance.now() - start}ms`);
    return result;
  }
  
  // Execute operation and cache result
  result = await operation();
  await cache.set(key, result);
  
  console.log(`Cache miss for ${key}: ${performance.now() - start}ms`);
  return result;
}

Configuration Options

interface CacheOptions {
  /** Namespace for cache isolation between different tools/contexts */
  ns?: string;
  
  /** Prefix added to all cache keys */
  prefix?: string;
  
  /** Hash algorithm used for key generation (default: 'md5') */
  hash_alg?: string;
  
  /** Base directory for cache storage */
  basePath?: string;
  
  /** Time-to-live in milliseconds (0 = no expiration) */
  ttl?: number;
}

Install with Tessl CLI

npx tessl i tessl/npm-storybook--core-common

docs

caching.md

configuration.md

environment-cli.md

index.md

package-management.md

presets.md

story-processing.md

text-processing.md

tile.json