bun
Build fast applications with Bun JavaScript runtime. Use when creating Bun projects, using Bun APIs, bundling, testing, or optimizing Node.js alternatives. Triggers on Bun, Bun runtime, bun.sh, bunx, Bun serve, Bun test, JavaScript runtime.
What this skill does
# Bun - The Fast JavaScript Runtime
Build and run JavaScript/TypeScript applications with Bun's all-in-one toolkit.
## Quick Start
```bash
# Install Bun (macOS, Linux, WSL)
curl -fsSL https://bun.sh/install | bash
# Windows
powershell -c "irm bun.sh/install.ps1 | iex"
# Create new project
bun init
# Run TypeScript directly (no build step!)
bun run index.ts
# Install packages (faster than npm)
bun install
# Run scripts
bun run dev
```
## Package Management
```bash
# Install dependencies
bun install # Install all from package.json
bun add express # Add dependency
bun add -d typescript # Add dev dependency
bun add -g serve # Add global package
# Remove packages
bun remove express
# Update packages
bun update
# Run package binaries
bunx prisma generate # Like npx but faster
bunx create-next-app
# Lockfile
bun install --frozen-lockfile # CI mode
```
### bun.lockb vs package-lock.json
```bash
# Bun uses binary lockfile (bun.lockb) - much faster
# To generate yarn.lock for compatibility:
bun install --yarn
# Import from other lockfiles
bun install # Auto-detects package-lock.json, yarn.lock
```
## Bun Runtime
### Run Files
```bash
# Run any file
bun run index.ts # TypeScript
bun run index.js # JavaScript
bun run index.jsx # JSX
# Watch mode
bun --watch run index.ts
# Hot reload
bun --hot run server.ts
```
### Built-in APIs
```typescript
// File I/O (super fast)
const file = Bun.file('data.json');
const content = await file.text();
const json = await file.json();
const bytes = await file.arrayBuffer();
// Write files
await Bun.write('output.txt', 'Hello, Bun!');
await Bun.write('data.json', JSON.stringify({ key: 'value' }));
await Bun.write('image.png', await fetch('https://example.com/img.png'));
// File metadata
const file = Bun.file('data.json');
console.log(file.size); // bytes
console.log(file.type); // MIME type
console.log(file.lastModified);
// Glob files
const glob = new Bun.Glob('**/*.ts');
for await (const file of glob.scan('.')) {
console.log(file);
}
```
### HTTP Server
```typescript
// Simple server
const server = Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/') {
return new Response('Hello, Bun!');
}
if (url.pathname === '/json') {
return Response.json({ message: 'Hello!' });
}
return new Response('Not Found', { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
```
### Advanced Server
```typescript
Bun.serve({
port: 3000,
// Main request handler
async fetch(req, server) {
const url = new URL(req.url);
// WebSocket upgrade
if (url.pathname === '/ws') {
const upgraded = server.upgrade(req, {
data: { userId: '123' }, // Attach data to socket
});
if (upgraded) return undefined;
}
// Static files
if (url.pathname.startsWith('/static/')) {
const filePath = `./public${url.pathname}`;
const file = Bun.file(filePath);
if (await file.exists()) {
return new Response(file);
}
}
// JSON API
if (url.pathname === '/api/data' && req.method === 'POST') {
const body = await req.json();
return Response.json({ received: body });
}
return new Response('Not Found', { status: 404 });
},
// WebSocket handlers
websocket: {
open(ws) {
console.log('Client connected:', ws.data.userId);
ws.subscribe('chat'); // Pub/sub
},
message(ws, message) {
// Broadcast to all subscribers
ws.publish('chat', message);
},
close(ws) {
console.log('Client disconnected');
},
},
// Error handling
error(error) {
return new Response(`Error: ${error.message}`, { status: 500 });
},
});
```
### WebSocket Client
```typescript
const ws = new WebSocket('ws://localhost:3000/ws');
ws.onopen = () => {
ws.send('Hello, server!');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
```
## Bun APIs
### SQLite (Built-in)
```typescript
import { Database } from 'bun:sqlite';
const db = new Database('mydb.sqlite');
// Create table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Insert
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
insert.run('Alice', '[email protected]');
// Query
const query = db.prepare('SELECT * FROM users WHERE id = ?');
const user = query.get(1);
// All results
const allUsers = db.prepare('SELECT * FROM users').all();
// Transaction
const insertMany = db.transaction((users) => {
for (const user of users) {
insert.run(user.name, user.email);
}
});
insertMany([
{ name: 'Bob', email: '[email protected]' },
{ name: 'Charlie', email: '[email protected]' },
]);
```
### Password Hashing (Built-in)
```typescript
// Hash password
const hash = await Bun.password.hash('mypassword', {
algorithm: 'argon2id', // or 'bcrypt'
memoryCost: 65536, // 64 MB
timeCost: 2,
});
// Verify password
const isValid = await Bun.password.verify('mypassword', hash);
```
### Spawn Processes
```typescript
// Spawn process
const proc = Bun.spawn(['ls', '-la'], {
cwd: '/home/user',
env: { ...process.env, MY_VAR: 'value' },
stdout: 'pipe',
});
const output = await new Response(proc.stdout).text();
console.log(output);
// Spawn sync
const result = Bun.spawnSync(['echo', 'hello']);
console.log(result.stdout.toString());
// Shell command
const { stdout } = Bun.spawn({
cmd: ['sh', '-c', 'echo $HOME'],
stdout: 'pipe',
});
```
### Hashing & Crypto
```typescript
// Hash strings
const hash = Bun.hash('hello world'); // Wyhash (fast)
// Crypto hashes
const sha256 = new Bun.CryptoHasher('sha256');
sha256.update('data');
const digest = sha256.digest('hex');
// One-liner
const md5 = Bun.CryptoHasher.hash('md5', 'data', 'hex');
// HMAC
const hmac = Bun.CryptoHasher.hmac('sha256', 'secret-key', 'data', 'hex');
```
## Bundler
```bash
# Bundle for browser
bun build ./src/index.ts --outdir ./dist
# Bundle options
bun build ./src/index.ts \
--outdir ./dist \
--minify \
--sourcemap \
--target browser \
--splitting \
--entry-naming '[dir]/[name]-[hash].[ext]'
```
### Build API
```typescript
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
minify: true,
sourcemap: 'external',
target: 'browser', // 'bun' | 'node' | 'browser'
splitting: true,
naming: {
entry: '[dir]/[name]-[hash].[ext]',
chunk: '[name]-[hash].[ext]',
asset: '[name]-[hash].[ext]',
},
external: ['react', 'react-dom'],
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
},
loader: {
'.png': 'file',
'.svg': 'text',
},
});
if (!result.success) {
console.error('Build failed:', result.logs);
}
```
## Testing
```typescript
// test.ts
import { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';
describe('Math operations', () => {
test('addition', () => {
expect(1 + 1).toBe(2);
});
test('array contains', () => {
expect([1, 2, 3]).toContain(2);
});
test('object matching', () => {
expect({ name: 'Alice', age: 30 }).toMatchObject({ name: 'Alice' });
});
test('async test', async () => {
const result = await Promise.resolve(42);
expect(result).toBe(42);
});
test('throws error', () => {
expect(() => {
throw new Error('fail');
}).toThrow('fail');
});
});
// Mocking
const mockFn = mock(() => 'mocked');
mockFn();
expect(mockFn).toHaveBeenCalled();
// Mock modules
mock.module('./database', () => ({
query: mock(() => [{ id: 1 }]),
}));
```
```bash
# Run tests
bun test
# Watch mode
bun test --watch
# Specific file
bun test user.test.ts
# Coverage
bun test --coverage
```
## Node.js Compatibility
```typescript
// Most Node.js APIs Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.