AgentSkillsCN

bun-knowledge-patch

当编写 Bun 代码、使用 Bun 特定的 API、bun:* 模块、Bun.serve()、打包工具功能,或使用 1.2+ 版本(2025–2026)中的任何 Bun 特性时,应使用此技能。

SKILL.md
--- frontmatter
name: bun-knowledge-patch
description: This skill should be used when writing Bun code, using Bun-specific APIs, bun:* modules, Bun.serve(), bundler features, or any Bun features from 1.2+ (2025-2026).
license: MIT
metadata:
  author: Nevaberry
  version: "1.3.8"

Bun 1.2+ Knowledge Patch

Claude's baseline knowledge covers Bun through 1.1.x. This skill provides features from 1.2 (January 2025) onwards.

Quick Reference

HTTP Server (Bun.serve)

FeatureExample
Routes with params"/api/users/:id"req.params.id
Method handlers{ GET: fn, POST: fn }
Static routes"/health": new Response("OK")
HTML importsimport page from "./index.html"
Cookiesreq.cookies.set("name", "value")
CSRFawait Bun.CSRF.generate(sessionId)

See references/http-server.md for routes, cookies, dev server, WebSocket proxy.

SQL & Database

ClientConnection
PostgreSQLimport { sql } from "bun"
MySQL/MariaDBnew SQL("mysql://...")
SQLitenew SQL(":memory:")
Redisimport { redis } from "bun"
ts
const users = await sql`SELECT * FROM users WHERE age >= ${minAge}`;
await sql`INSERT INTO users ${sql(user, "name", "email")}`;

See references/sql-database.md for tagged templates, dynamic columns, Redis pub/sub.

S3 Storage (Bun.s3)

ts
const file = s3.file("path/file.txt");
await file.text();  // Same API as Bun.file()
await file.write("data");
const url = s3.presign("file", { expiresIn: 3600 });

See references/s3-storage.md for bucket listing, upload options.

Test Runner (bun:test)

FeatureAPI
Fake timersjest.useFakeTimers()
Concurrent teststest.concurrent()
Retry flakytest("name", fn, { retry: 3 })
Type testingexpectTypeOf(x).toBeString()
vi globalvi.fn(), vi.mock(), vi.spyOn()

See references/test-runner.md for matchers, mocking, configuration.

Package Manager

CommandPurpose
bun outdatedView outdated deps
bun auditSecurity scan
bun why <pkg>Dependency path
bun pm pkg get/setManage package.json
bun pm version patchBump version

See references/package-manager.md for workspaces, catalogs, linker modes.

Bundler (bun build)

FlagPurpose
--compileStandalone executable
--target=bun-*Cross-compile
--productionProduction HTML build
--metafile / --metafile-mdBundle analysis
--feature=XCompile-time flags

See references/bundler.md for plugins, JSX config, virtual files.

New APIs

APIPurpose
Bun.markdownMD → HTML/React
Bun.YAMLYAML parse/stringify
Bun.JSON5JSON5 with comments
Bun.ArchiveTar creation/extraction
Bun.TerminalPTY support
Bun.secretsOS credential storage

See references/new-apis.md for JSONC, JSONL, compression, text utilities.

Runtime & CLI

FeatureExample
Spawn timeoutBun.spawn({ cmd, timeout: 1000 })
CPU profilingbun --cpu-prof script.js
Heap profilingbun --heap-prof script.js
Fetch proxyfetch(url, { proxy: "http://..." })

See references/runtime-cli.md for spawn options, profiling, CLI flags.

Node.js Compatibility

APIStatus
fs.globSupported
node:http2Supported
node:vmSourceTextModule, SyntheticModule
node:inspectorProfiler API
ReadableStream.json()Direct consumption

See references/node-compat.md for full compatibility details.

Reference Files

FileContents
http-server.mdRoutes, static, cookies, HTML imports, dev server
sql-database.mdPostgres, MySQL, SQLite, Redis clients
s3-storage.mdS3 client, presigned URLs, bucket listing
test-runner.mdMatchers, mocking, fake timers, concurrent
package-manager.mdInstall, audit, workspaces, catalogs
bundler.mdCompile, plugins, metafile, feature flags
new-apis.mdMarkdown, YAML, JSON5, Archive, Terminal
node-compat.mdfs.glob, vm, inspector, streams
runtime-cli.mdSpawn, profiling, CLI flags

Critical Examples

Full-Stack Server with Routes

ts
import homepage from "./index.html";  // Auto-bundles JS/CSS
import { sql } from "bun";

Bun.serve({
  routes: {
    "/": homepage,
    "/api/users/:id": (req) => {
      const { id } = req.params;
      return Response.json({ id });
    },
    "/api/users": {
      GET: async () => Response.json(await sql`SELECT * FROM users`),
      POST: async (req) => {
        const { name } = await req.json();
        const [user] = await sql`INSERT INTO users (name) VALUES (${name}) RETURNING *`;
        return Response.json(user);
      },
    },
  },
});

Cookies

ts
// In route handler
req.cookies.set("session", token, { httpOnly: true, sameSite: "strict" });
req.cookies.get("session");
req.cookies.delete("session");

SQL Dynamic Columns

ts
// Insert/update specific columns from object
await sql`INSERT INTO users ${sql(user, "name", "email")}`;
await sql`UPDATE users SET ${sql(user, "name")} WHERE id = ${user.id}`;

// WHERE IN with array
await sql`SELECT * FROM users WHERE id IN ${sql([1, 2, 3])}`;

Test Runner Essentials

ts
import { test, expect, jest, mock } from "bun:test";

test("with fake timers", () => {
  jest.useFakeTimers();
  setTimeout(() => {}, 1000);
  jest.advanceTimersByTime(1000);
  jest.useRealTimers();
});

test.concurrent("runs in parallel", async () => {});
test("retry flaky", () => {}, { retry: 3 });