Examples & Tutorials
Real-world examples showing how to use B4M CLI effectively.
Development Workflows
Code Review Assistant
Get help reviewing code changes:
> Review the changes in my current git diff
[tool: bash_execute command="git diff"]
Let me analyze these changes...
**Summary:**
- Added input validation to user registration
- Fixed memory leak in event listeners
- Improved error messages
**Suggestions:**
1. Line 42: Consider using a more specific error type
2. Line 58: This could be extracted into a helper function
3. Line 73: Add a comment explaining the regex pattern
**Security:**
- ✓ Input sanitization looks good
- ✓ No obvious vulnerabilities
Overall, the changes look solid!
Bug Investigation
Debug issues step-by-step:
> Help me debug why my tests are failing
Let me investigate. First, let's run the tests:
[tool: bash_execute command="npm test"]
Found 3 failing tests. Let me check the first one:
[tool: bash_execute command="npm test -- user.test.ts"]
The test is failing because... [analysis]
Let's check the implementation:
[tool: bash_execute command="cat src/user.ts"]
I see the issue! The function expects... [explanation]
**Fix:**
[Provides code fix with explanation]
**Why it works:**
[Detailed explanation]
Try this and run the tests again.
Project Setup
Set up a new project with best practices:
> Set up a new TypeScript + React project with testing
I'll help you set up a complete project. Here's my plan:
1. Initialize package.json
2. Install TypeScript and React
3. Configure TypeScript
4. Set up Jest for testing
5. Add ESLint and Prettier
6. Create project structure
Let's start:
[tool: bash_execute command="npm init -y"]
[tool: bash_execute command="npm install react react-dom"]
[tool: bash_execute command="npm install -D typescript @types/react @types/react-dom"]
[Continues with setup steps...]
✅ Project setup complete!
**Structure created:**
my-project/ ├── src/ │ ├── App.tsx │ ├── App.test.tsx │ └── index.tsx ├── tsconfig.json ├── jest.config.js └── package.json
**Next steps:**
1. Run `npm start` to start dev server
2. Run `npm test` to run tests
3. Run `npm run build` to create production build
Research & Learning
Technology Research
Research a technology using web search:
> Search for WebAssembly performance compared to JavaScript
[tool: web_search query="WebAssembly vs JavaScript performance 2025"]
Top results on WebAssembly vs JavaScript performance:
1. **WebAssembly Performance Guide (MDN)**
- Near-native speed for CPU-intensive tasks
- 50-80% of native C++ performance
- Best for: Image processing, games, simulations
2. **JavaScript vs WebAssembly Benchmark (2025)**
- JavaScript faster for startup and DOM manipulation
- WebAssembly shines in computational workloads
- Use cases and trade-offs explained
3. **When to Use WebAssembly (web.dev)**
- Decision tree for choosing between JS and WASM
- Real-world performance comparisons
- Tooling and ecosystem considerations
Based on these results, here's a summary:
**WebAssembly advantages:**
- Near-native performance for computations
- Predictable performance (no JIT warmup)
- Compact binary format
**JavaScript advantages:**
- Faster startup for small apps
- Direct DOM access
- Mature ecosystem
**Recommendation:** Use WebAssembly for CPU-intensive tasks like image/video processing, simulations, or games. Stick with JavaScript for DOM manipulation and most web apps.
Want me to search for more specific performance benchmarks?
Learning New Concepts
Get explanations with examples:
> Explain React Server Components with a practical example
# React Server Components
## What They Are
Server Components render on the server and send HTML to the client,
reducing JavaScript bundle size and improving performance.
## Key Differences
**Server Component (default in Next.js 13+):**
```typescript
// app/components/UserList.tsx
async function UserList() {
// This runs on the server
const users = await fetch('https://api.example.com/users').then(r => r.json());
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Client Component:
'use client'; // Mark as client component
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
When to Use Each
Server Components for:
- Data fetching
- Accessing backend resources
- Keeping sensitive data on server
- Large dependencies
Client Components for:
- Interactivity (onClick, onChange)
- State management (useState, useReducer)
- Browser APIs (localStorage, geolocation)
- React hooks (useEffect, etc.)
Complete Example
[Provides full working example with file structure]
Would you like me to explain any specific aspect in more detail?
---
## Data Analysis
### Log Analysis
Analyze application logs:
```bash
> Analyze the error logs from yesterday
[tool: bash_execute command="grep ERROR /var/log/app.log | grep '2025-01-13'"]
Found 147 errors yesterday. Let me categorize them:
## Error Summary
**Database Connection Errors (89 instances)**
[2025-01-13 14:23:15] ERROR: Connection timeout to db-primary
Pattern: Peak at 2-3 PM, suggests database overload
**API Rate Limiting (42 instances)**
[2025-01-13 16:45:22] ERROR: Rate limit exceeded for /api/users
Pattern: Afternoon traffic spike
**Authentication Failures (16 instances)**
[2025-01-13 09:12:08] ERROR: Invalid token for user@example.com
Pattern: Isolated incidents, no pattern
## Recommendations
1. **Database**: Increase connection pool size or add read replica
2. **Rate Limiting**: Increase limits or add caching layer
3. **Auth**: Investigate if tokens are expiring prematurely
Want me to investigate any of these in detail?
Data Transformation
Process and transform data:
> Convert this CSV data to JSON format and calculate averages
[tool: bash_execute command="cat data.csv"]
```csv
name,score,department
Alice,85,Engineering
Bob,92,Sales
Charlie,78,Engineering
Let me process this...
[tool: bash_execute command="python3 -c 'import csv, json; ...'"]
JSON Output:
[
{"name": "Alice", "score": 85, "department": "Engineering"},
{"name": "Bob", "score": 92, "department": "Sales"},
{"name": "Charlie", "score": 78, "department": "Engineering"}
]
Statistics:
- Average score: 85.0
- Engineering average: 81.5
- Sales average: 92.0
- Highest: Bob (92)
- Lowest: Charlie (78)
---
## DevOps Tasks
### Deployment Checks
Pre-deployment verification:
```bash
> Check if the app is ready to deploy
Running deployment checklist...
**1. Tests**
[tool: bash_execute command="npm test"]
✅ All tests passing (42 passed)
**2. Build**
[tool: bash_execute command="npm run build"]
✅ Build successful (no errors)
**3. Type Check**
[tool: bash_execute command="tsc --noEmit"]
✅ No TypeScript errors
**4. Lint**
[tool: bash_execute command="npm run lint"]
⚠️ 3 warnings (non-blocking)
- Unused variable at src/utils.ts:42
- Missing prop types at src/components/Card.tsx:12
- Console.log at src/debug.ts:8
**5. Security**
[tool: bash_execute command="npm audit"]
✅ No vulnerabilities
**6. Environment**
[tool: bash_execute command="cat .env.production"]