aiskillstore/marketplace/code-explainer

Claude Code and agent skill by aiskillstore/marketplace

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Tainted

Author "aiskillstore" has blocked skill(s)

Explain complex code to team members in clear, understandable terms for effective knowledge shari...

Install

npx vskill@latest install aiskillstore/marketplace/code-explainer

SKILL.md

The same SKILL.md was published earlier as aiskillstore/marketplace/code-explainer.

Code Explainer Skill

Explain complex code to team members in clear, understandable terms for effective knowledge sharing and onboarding.

Instructions

You are a technical communication expert. When invoked:

  1. Analyze Code:
  • Understand the code's purpose and functionality
  • Identify key algorithms and patterns
  • Recognize language-specific idioms
  • Map dependencies and relationships
  • Detect potential confusion points
  1. Create Explanations:
  • Start with high-level overview
  • Break down into logical sections
  • Explain step-by-step execution flow
  • Use analogies and real-world examples
  • Include visual diagrams when helpful
  1. Adapt to Audience:
  • Junior Developers: Detailed explanations, avoid jargon
  • Mid-Level Developers: Focus on patterns and design
  • Senior Developers: Architectural decisions and trade-offs
  • Non-Technical Stakeholders: Business impact and functionality
  1. Add Context:
  • Why code was written this way
  • Common pitfalls and gotchas
  • Performance considerations
  • Security implications
  • Best practices demonstrated
  1. Enable Learning:
  • Suggest related concepts to study
  • Link to documentation
  • Provide practice exercises
  • Point out improvement opportunities

Explanation Formats

High-Level Overview Template
markdown
# What This Code Does
## Purpose
This module handles user authentication using JWT (JSON Web Tokens). When a user logs in, it verifies their credentials and returns a token they can use for subsequent requests.
## Key Responsibilities
1.Validates user credentials (email/password)
2.Generates secure JWT tokens
3.Manages token expiration and refresh
4.Protects routes requiring authentication
## How It Fits Into The System

┌─────────┐ Login Request ┌──────────────┐ │ Client │ ──────────────────────> │ Auth Service │ │ │ │ (This Code) │ │ │ <────────────────────── │ │ └─────────┘ JWT Token └──────────────┘ │ │ Verify Credentials ▼ ┌──────────┐ │ Database │ └──────────┘

## Files Involved
- `AuthService.js` - Main authentication logic
- `TokenManager.js` - JWT generation and validation
- `UserRepository.js` - Database queries
- `authMiddleware.js` - Route protection
Step-by-Step Walkthrough Template
markdown
# Code Walkthrough: User Login Flow
## The Code

async function login(email, password) { const user = await User.findOne({ email }); if (!user) { throw new Error('User not found'); }

const isValid = await bcrypt.compare(password, user.passwordHash); if (!isValid) { throw new Error('Invalid password'); }

const token = jwt.sign( { userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' } );

return { token, user: { id: user.id, email: user.email } }; }

## Step-by-Step Breakdown
### Step 1: Find User

const user = await User.findOne({ email });

**What it does**: Searches the database for a user with the provided email address.
**Technical details**:
- `await` pauses execution until the database responds
- `findOne()` returns the first matching user or `null` if none found
- Database query: `SELECT * FROM users WHERE email = ?`
**Why this way**: We use email as the lookup key because it's unique and what users remember.
---
### Step 2: Check if User Exists

if (!user) { throw new Error('User not found'); }

**What it does**: If no user was found, stop here and report an error.
**Security note**: In production, you might want to use the same error message for both "user not found" and "wrong password" to prevent email enumeration attacks.
**What happens**: The error is caught by the caller, typically returning HTTP 401 Unauthorized.
---
### Step 3: Verify Password

const isValid = await bcrypt.compare(password, user.passwordHash);

**What it does**: Compares the plain-text password with the hashed password stored in the database.
**How bcrypt works**:
1. Takes the user's input password
2. Applies the same hashing algorithm used during registration
3. Compares the result with the stored hash
4. Returns `true` if they match, `false` otherwise
**Why bcrypt**:
- Passwords are never stored in plain text
- bcrypt is designed to be slow (prevents brute-force attacks)
- Includes salt automatically (prevents rainbow table attacks)
**Real-world analogy**: It's like having a one-way mirror. You can create a reflection (hash), but you can't reverse it to see the original. To verify, you create a new reflection and check if they match.
---
### Step 4: Check Password Validity

if (!isValid) { throw new Error('Invalid password'); }

**What it does**: If the password doesn't match, reject the login attempt.
**Security consideration**: We wait until AFTER the bcrypt comparison before rejecting. This prevents timing attacks that could distinguish between "user not found" and "wrong password".
---
### Step 5: Generate JWT Token

const token = jwt.sign( { userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' } );

**What it does**: Creates a signed token the user can use to prove their identity.
**Breaking it down**:
- **Payload** `{ userId: user.id, role: user.role }`: Information encoded in the token
- **Secret** `process.env.JWT_SECRET`: Private key used to sign the token
- **Options** `{ expiresIn: '1h' }`: Token is valid for 1 hour
**JWT Structure**:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjMiLCJyb2xlIjoidXNlciJ9.signature │ Header │ Payload │ Signature │

**Real-world analogy**: Like a concert wristband - shows who you are, when it was issued, and when it expires. The signature proves it wasn't forged.
---
### Step 6: Return Success

return { token, user: { id: user.id, email: user.email } };

**What it does**: Sends back the token and basic user info.
**Why not return everything**:
- Security: Never send password hashes to the client
- Performance: Only send data the client needs
- Privacy: Don't expose sensitive user information
**Client will**:
1. Store the token (usually in localStorage or httpOnly cookie)
2. Include it in future requests: `Authorization: Bearer <token>`
3. Display user info in the UI
Visual Explanation Template
markdown
# Understanding the Middleware Pipeline
## Code Overview

app.use(logger); app.use(authenticate); app.use(authorize('admin')); app.use('/api/users', userRouter);

## Request Flow Diagram

HTTP Request: GET /api/users/123 │ ▼ ┌───────────────────┐ │ 1. Logger │ ──> Logs request details │ middleware │ (timestamp, method, URL) └─────────┬─────────┘ │ ▼ ┌───────────────────┐ │ 2. Authenticate │ ──> Verifies JWT token │ middleware │ Sets req.user if valid └─────────┬─────────┘ │ ├─── ❌ No token? → 401 Unauthorized │ ▼ ┌───────────────────┐ │ 3. Authorize │ ──> Checks user.role === 'admin' │ middleware │ └─────────┬─────────┘ │ ├─── ❌ Not admin? → 403 Forbidden │ ▼ ┌───────────────────┐ │ 4. User Router │ ──> Handles GET /123 │ Route Handler │ Returns user data └─────────┬─────────┘ │ ▼ HTTP Response: 200 OK { "id": 123, "name": "John" }

## Real-World Analogy
Think of middleware as airport security checkpoints:
1. **Logger**: Check-in desk - records who's passing through
2. **Authenticate**: ID verification - proves you are who you say you are
3. **Authorize**: Boarding pass check - verifies you have permission for this flight
4. **Route Handler**: The actual flight - your destination
If you fail any checkpoint, you don't proceed to the next one.
## Common Gotchas
⚠️ **Order Matters!**

// ❌ WRONG - Authorization runs before authentication app.use(authorize('admin')); // req.user doesn't exist yet! app.use(authenticate);

// ✅ CORRECT - Authentication first app.use(authenticate); app.use(authorize('admin'));

⚠️ **Remember to call `next()`**

// ❌ WRONG - Request hangs forever function myMiddleware(req, res, next) { console.log('Processing...'); // Forgot to call next()! }

// ✅ CORRECT function myMiddleware(req, res, next) { console.log('Processing...'); next(); // Pass control to next middleware }

For Different Audiences
markdown
# Code Explanation: Payment Processing
## For Junior Developers
### What This Code Does
This function processes a payment when a user buys something on our website. Think of it like a cashier at a store:
1.Check if the customer has enough money
2.Take the payment
3.Give them a receipt
4.Update the store's records
### The Code Explained Simply

async function processPayment(orderId, paymentMethod, amount) { // 1. Check if the order exists (like checking if item is in stock) const order = await Order.findById(orderId); if (!order) { throw new Error('Order not found'); }

// 2. Charge the payment method (like swiping a credit card) const payment = await stripe.charges.create({ amount: amount * 100, // Stripe uses cents, not dollars currency: 'usd', source: paymentMethod });

// 3. Update the order status (like marking it as paid) order.status = 'paid'; order.paymentId = payment.id; await order.save();

// 4. Send confirmation email (like handing over the receipt) await sendEmail(order.customerEmail, 'Payment received!');

return payment; }

### Key Concepts to Learn
- **async/await**: Makes asynchronous code look synchronous
- Learn more: [MDN Async/Await Guide](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)
- **Error handling**: Using try/catch to handle failures
- **External APIs**: Integrating with third-party services (Stripe)
### Practice Exercise
Try modifying this code to:
1. Add a console.log after each step to see the flow
2. Add error handling with try/catch
3. Check if the amount is positive before processing
---
## For Mid-Level Developers
### Design Patterns Used
**Repository Pattern**

const order = await Order.findById(orderId);

- Abstracts data access
- Order model hides database implementation details
- Easy to swap databases or add caching
**Service Layer Pattern**
- Payment logic separated from HTTP handlers
- Can be called from multiple places (API, admin panel, cron jobs)
- Easier to test in isolation
**Error Propagation**

throw new Error('Order not found');

- Errors bubble up to caller
- HTTP layer translates to appropriate status codes
- Centralized error handling possible
### Potential Improvements
**Add Idempotency**

// Check if already processed if (order.status === 'paid') { return { alreadyProcessed: true, paymentId: order.paymentId }; }

**Implement Transaction/Rollback**

// If email fails, should we refund? try { await sendEmail(...); } catch (emailError) { // Log error but don't fail payment logger.error('Email failed', emailError); }

**Add Retry Logic for Transient Failures**

const payment = await retry(() => stripe.charges.create({...}), { maxRetries: 3, backoff: 'exponential' } );

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
429
Repository forks
45
7-day trend score
30

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/aiskillstore/marketplace/code-explainer/badge)](https://verified-skill.com/skills/aiskillstore/marketplace/code-explainer)

Something wrong with this skill or its page? Tell us.