AgentSkillsCN

lib-replacement

当你需要对代码库进行审计,寻找可被知名库替代的自定义实现时,这一技能将为你提供替换模式、审计清单与迁移策略。

SKILL.md
--- frontmatter
name: lib-replacement
description: Use when auditing codebase for custom implementations that can be replaced with well-known libraries. Provides replacement patterns, audit checklist, and migration strategies.
allowed-tools: Read, Glob, Grep

Library Replacement Skill

This skill provides guidelines for finding redundant custom implementations and replacing them with well-known libraries.

Purpose

Identify custom implementations that:

  • Duplicate functionality available in well-known libraries
  • Are harder to maintain than library equivalents
  • May have bugs that libraries have already solved
  • Lack the testing/documentation of established libraries

When to Apply

Apply this skill when:

  • Auditing codebase for technical debt
  • Refactoring for maintainability
  • Reducing custom code footprint
  • Standardizing on ecosystem best practices

Common Replacement Patterns

Pattern Categories

CategoryCustom Implementation SignsRecommended Libraries
Result/Error HandlingCustom Result type, ok/err patternneverthrow, ts-results, effect
ValidationCustom validate functions, manual checkszod, valibot, arktype
Date/TimeCustom date parsing/formattingdate-fns, dayjs, luxon
Path OperationsCustom path manipulationpathe, upath (cross-platform)
CLI ParsingCustom argument parsingcommander, yargs, citty
ConfigurationCustom config loadingc12, cosmiconfig, rc9
LoggingCustom logger implementationspino, consola, winston
HTTP ClientCustom fetch wrappersofetch, ky, got
Retry LogicCustom retry loopsp-retry, async-retry
Debounce/ThrottleCustom implementationslodash-es (specific imports), perfect-debounce
Deep Clone/MergeCustom recursive functionsklona, defu, deepmerge-ts
Type GuardsRepetitive type checkstypeguard, ts-is
UUID/ID GenerationCustom ID generatorsnanoid, ulid, uuid
HashingCustom hash implementationsohash, hash-sum
File WatchingCustom fs.watch wrapperschokidar, watchlist
Glob PatternsCustom glob matchingtinyglobby, fast-glob, picomatch
JSON ParsingCustom streaming JSON@streamparser/json, stream-json
JSONL/NDJSONCustom line-by-line parsingndjson, jsonlines
String UtilsCustom case conversion, trimscule, change-case
Async UtilitiesCustom promise helpersp-* packages (p-limit, p-map, p-queue)
Schema GenerationCustom type-to-schematypebox, zod-to-json-schema
Diff/PatchCustom diff algorithmsdiff, fast-diff, json-diff
Template StringsCustom template parsinghandlebars, mustache, eta
CachingCustom cache implementationslru-cache, quick-lru, keyv
Rate LimitingCustom rate limitersp-throttle, limiter, bottleneck

Bun-Specific Considerations

Bun provides built-in alternatives for some patterns:

PatternBun Built-inExternal Library
GlobBun.glob()Not needed
File I/OBun.file(), Bun.write()Not needed
HashingBun.hash(), Bun.CryptoHasherNot needed
SQLitebun:sqliteNot needed
Test Runnerbun:testNot needed
Shell CommandsBun.spawn(), Bun.$Not needed

Audit Checklist

When auditing code, look for:

1. Utility Functions (High Priority)

typescript
// RED FLAG: Custom implementations of common utilities
function deepClone(obj) { ... }
function debounce(fn, delay) { ... }
function retry(fn, maxAttempts) { ... }
function generateId() { return Math.random()... }

2. Error Handling Patterns (High Priority)

typescript
// RED FLAG: Custom Result type
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

// BETTER: Use neverthrow
import { Result, ok, err } from 'neverthrow';

3. Validation Logic (Medium Priority)

typescript
// RED FLAG: Manual validation
function validateEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// BETTER: Use zod
const emailSchema = z.string().email();

4. Date/Time Operations (Medium Priority)

typescript
// RED FLAG: Custom date formatting
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  ...
}

// BETTER: Use date-fns
import { format } from 'date-fns';
format(date, 'yyyy-MM-dd');

5. Async Patterns (Medium Priority)

typescript
// RED FLAG: Custom promise utilities
async function promisePool(tasks, concurrency) { ... }
async function withTimeout(promise, ms) { ... }

// BETTER: Use p-* packages
import pLimit from 'p-limit';
import pTimeout from 'p-timeout';

Replacement Strategy

Phase 1: Audit

  1. Scan for custom utility functions
  2. Identify patterns matching library functionality
  3. Assess replacement difficulty
  4. Prioritize by impact and risk

Phase 2: Plan

For each replacement:

  1. Identify all usages of custom implementation
  2. Select appropriate library
  3. Plan migration approach (big bang vs incremental)
  4. Identify test coverage requirements

Phase 3: Replace (Concurrent Execution)

Parallelizable replacements (no shared dependencies):

  • Different utility functions in separate files
  • Independent module replacements

Sequential replacements (shared dependencies):

  • Core types used across modules
  • Shared validation schemas

Phase 4: Verify

  1. Run type checking
  2. Run all tests
  3. Review changes
  4. Verify no regressions

Difficulty Assessment

Easy Replacements

  • Drop-in function replacement
  • Same or compatible API
  • No type changes needed
  • Example: generateId() -> nanoid()

Medium Replacements

  • API differences require minor refactoring
  • Some type adjustments needed
  • Limited scope of changes
  • Example: Custom validation -> Zod schemas

Hard Replacements

  • Significant API differences
  • Type system changes
  • Wide usage across codebase
  • Example: Custom Result type -> neverthrow

Testing Considerations

Before Replacement

  • Ensure existing tests pass
  • Identify test coverage gaps
  • Document expected behavior

During Replacement

  • Keep tests passing incrementally
  • Add tests for edge cases
  • Verify library handles all cases

After Replacement

  • Full test suite must pass
  • Add integration tests if needed
  • Performance comparison if relevant

References