Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Bun Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-bun-knowledge-patch)
---
name: bun-knowledge-patch
description: Bun
version: "1.4.5"
license: MIT
metadata:
author: Nevaberry
---
# Bun knowledge patch
Load this skill for Bun migrations, package management, builds, testing,
runtime APIs, database clients, HTTP servers, and Node.js compatibility.
Use the quick reference for common decisions and the topic files for detailed
options, examples, limitations, and version-specific behavior.
## Reference index
| Reference | Topics |
| --- | --- |
| [Builds and frontend](references/build-and-frontend.md) | HTML, CSS, HMR, plugins, transforms, checking, formatting, executable assets, bytecode, sourcemaps |
| [Databases and storage](references/databases-and-storage.md) | SQL adapters, parameters, transactions, SQLite, Redis, S3, credentials |
| [HTTP and networking](references/http-and-networking.md) | Routes, cookies, CSRF, HTTP protocols, fetch, proxies, TLS, WebSockets, sockets, DNS |
| [Node.js compatibility](references/node-compatibility.md) | Built-ins, native addons, workers, VM, files, streams, cryptography, diagnostics, remaining differences |
| [Packages and workspaces](references/packages-and-workspaces.md) | Lockfiles, linkers, catalogs, registries, trust, audits, updates, scripts, packing, publishing |
| [Runtime and platforms](references/runtime-and-platform.md) | CLI, environment, subprocesses, FFI, data formats, images, Markdown, WebView, cron, WebAssembly, profiling |
| [Testing](references/testing.md) | Isolation, parallel workers, sharding, selection, hooks, retries, mocks, snapshots, reporting, Node tests |
## Breaking changes and deprecations
| Area | Guidance |
| --- | --- |
| HTTP routing | The `static` option became `routes`. Providing `routes` makes the top-level `fetch` handler optional. |
| Server types | `Bun.Server<Data>` describes WebSocket `.data`; use `Bun.Server<undefined>` without WebSockets. Replace `Bun.ServeOptions` with `Bun.Serve.Options`. |
| Build types | Replace `Bun.Build.Target` with `Bun.Build.CompileTarget`. |
| Spawn types | Replace deprecated `Bun.Spawn.OptionsObject` with `Bun.Spawn.BaseOptions` or the specific `spawn` or `spawnSync` option type. |
| Server debugging | `Bun.serve()` ignores the removed `inspector` option. Start with `bun --inspect server.ts`. |
| Build errors | `Bun.build()` rejects on failure. Set `throw: false` to receive errors in `result.logs`. |
| Filesystem removal | `fs.rmdir(path, { recursive: true })` throws `ERR_INVALID_ARG_VALUE`. Use `await fs.rm(path, { recursive: true, force: true })` with `node:fs/promises`; omit unset options instead of explicitly passing `undefined`. |
| Node HTTP | Replace `res.writeHeader()` with `res.writeHead()`. |
| Mock resets | `jest.resetAllMocks()` and `vi.resetAllMocks()` reset implementations and calls. Use `clearAllMocks()` to retain implementations. |
| C strings | `new CString(ptr)` returns a string without pointer or byte-buffer accessors. Retain the C pointer separately if the caller owns the allocation. |
| SQL passwords | `Bun.SQL` stops reading generic `PASSWORD`. Use `PGPASSWORD`, `MYSQL_PASSWORD`, a connection URL, or the `password` option. |
| SQL transpilation | Babel and SWC loose-mode output for `sql` tagged templates throws `TypeError`. Disable loose mode for template literals. |
| Runtime CSS | Runtime stylesheet default exports are `{}`. A `.module.css` class-name map comes from bundling. |
| Node mode | Bun running as `node` skips automatic environment files. Use `node --env-file=.env ./app.js` for explicit loading. |
| TOML | Invalid unquoted strings, missing newlines between pairs, and unsafe integers raise `SyntaxError`, including in `bunfig.toml`. |
| Client certificates | For mTLS with `Bun.serve()` or `Bun.listen()`, set `requestCert: true` alongside `ca`; `ca` alone no longer requests a certificate. |
| Publishing | Prerelease publishing requires an explicit tag such as `bun publish --tag beta` or `publishConfig.tag`. Git dependencies require Git 2.24 or newer. |
## Package and workspace decisions
New projects use the JSONC `bun.lock`. Existing binary lockfiles can migrate
with `bun install --save-text-lockfile`.
New text lockfiles use `lockfileVersion: 2`; nested or version-scoped overrides
produce version 3 and require a reader supporting that format.
Default linker selection depends on the lockfile's `configVersion`:
version `1` defaults to isolated workspaces and hoisted installs elsewhere;
version `0` defaults to hoisted installs even in workspaces.
Set the linker explicitly when retaining an isolated workspace layout:
```toml
[install]
linker = "isolated"
```
Selecting the isolated linker enables its shared global store.
`install.hoist = false` disables its hidden fallback; undeclared dependencies
that relied on the fallback can then fail with `MODULE_NOT_FOUND`.
Use root `packageExtensions` to supply a third-party package's missing dependency.
`bun update` updates transitive dependencies too. Use `bun update --depth 0`
to update manifest dependencies while keeping transitive versions pinned.
`bun audit fix --dry-run` previews vulnerability fixes; `--latest` allows major upgrades.
`bun dedupe --check` fails when locked versions need deduplication.
`bun prune --check` exits with status 1 when anything would be removed.
`bun install --offline` skips network requests and fails on cache misses.
`bun install --prefer-offline` reuses expired metadata and downloads missing data.
Project `bunfig.toml` settings take precedence over `.npmrc` for shared keys.
Lifecycle scripts for `file:`, `link:`, `git:`, and `github:` dependencies
require explicit entries in `trustedDependencies`, which matches exact names.
```sh
bun run --sequential build test
bun run --parallel --filter '*' --no-exit-on-error build lint test
```
Both script modes preserve each script's `pre` and `post` lifecycle order
while skipping workspace dependency ordering. `--if-present` skips missing scripts.
## Builds, frontend development, and tools
Run `bun ./index.html` for a development server with hot reloading.
HTML imports bundle linked scripts and styles; server builds can embed the frontend:
```sh
bun build ./src/server.ts --target=bun --outdir ./dist
bun build ./src/server.ts --compile --outfile=my-app
```
For self-contained browser HTML, use
`bun build --compile --target=browser ./index.html`.
Every entry point must be HTML, and that mode does not support splitting.
`bun build --bytecode --outdir=dist app.ts` emits `app.js` and `app.jsc`;
deploy both because JavaScript remains necessary for async functions and generators.
For ESM bytecode in an executable:
```sh
bun build --compile --bytecode --format=esm ./index.ts
```
Use `--keep-names` or `keepNames: true` when runtime code depends on function
and class names. A bare `--sourcemap` produces linked maps;
use `--sourcemap=inline` to embed them in a bundle.
Compiled executables emit external maps even when inline maps are requested.
`bun check` reads `tsconfig.json` and reports diagnostics with the bundled checker.
`bun test --check` includes type diagnostics in a test run.
`bun fmt` uses existing Prettier or oxfmt flags and configuration;
`bun fmt --init` creates `[fmt]` in `bunfig.toml`.
Use `--no-script` with `bun check` or `bun fmt` when a package script has that name.
## Tests and CI
Use `bun test --isolate` for fresh globals per file and cleanup of timers,
sockets, and subprocesses. `bun test --parallel=8` runs isolated files in workers.
`--parallel --no-isolate` shares globals and the module registry within each worker.
Isolated preloads run for every file and finish top-level `await` before tests start.
```sh
bun test --changed=main --watch
bun test --shard=2/3
bun test --timings=timings.json --update-timings
bun test --parallel --timings=timings.json
```
`test.concurrent()` opts into concurrency within a file; the default limit is 20.
Keep `expect.assertions()`, `expect.hasAssertions()`, and `toMatchSnapshot()` serial.
Concurrent tests support inline snapshots; `beforeAll` and `afterAll` remain sequential.
With `CI=true`, `test.only()` is an error and creating snapshots requires
`--update-snapshots`. `--pass-with-no-tests` allows empty selections to succeed.
`test.failing(name, fn)` passes when its callback throws and fails when it succeeds.
Set `retry` or `repeats` per test; retries pass on one success, repetitions fail on one failure.
`using` restores a `mock()` or `spyOn()` at scope exit.
```sh
bun test --reporter=junit --reporter-outfile=junit.xml
```
Parallel runs merge JUnit and coverage reports. JUnit represents each retry attempt
as a separate test case, including failed attempts before an eventual success.
## HTTP, TLS, and WebSockets
Directory routes provide content types, validators, byte ranges, and `index.html`:
```js
Bun.serve({ routes: { "/static/*": { dir: "./public" } } });
```
`http2: true` serves HTTP/2 and HTTP/1.x on the same port; `http1: false` selects
HTTP/2 only. WebSockets and response trailers are unsupported over HTTP/2.
HTTP/3 server and fetch support remains experimental; see the networking reference.
Clone requests and responses before reading their bodies or locking their streams.
Network and body-read failures reject with `TypeError` while preserving `code`;
a failed read marks `bodyUsed`, so retry with a new fetch.
`await server.stop()` waits for in-flight connections; `server.stop(true)` force-closes them.
`request.cookies` parses lazily and adds response `Set-Cookie` headers when mutated.
Pass the same `sessionId` to `Bun.CSRF.generate()` and `Bun.CSRF.verify()`.
For file download resumption, send the original `Last-Modified` as `If-Range`
with `Range`: unchanged files yield `206`, changed files yield a full `200` response.
`Bun.FetchSession` supplies an isolated pool and TLS, proxy, and keep-alive defaults.
Its `tls.checkServerIdentity` runs once per connection.
For `fetch()` certificate checks, a falsy return accepts and a truthy return rejects.
With HTTPS proxies, `proxy.tls` separates proxy TLS settings from origin `tls` settings.
Add an `'error'` listener to `ws` clients and accepted sockets: unhandled errors
are uncaught exceptions. `ws` defaults `maxPayload` to 100 MiB on clients and servers.
Native WebSocket handshake, TLS, proxy, and protocol failures emit `error` then
`close` with code 1006; a TCP loss after `open` emits only `close`.
## Database and runtime essentials
Use tagged SQL for bound values or `sql.unsafe(query)` for explicit raw SQL.
`sql({...})` omits `undefined`, rejects an entirely omitted object, and uses
`null` for SQL `NULL`. Use `sql.json(null)` to bind JSON `null` explicitly.
PostgreSQL queries with more than 65,535 bound parameters throw
`ERR_POSTGRES_TOO_MANY_PARAMETERS`. Split bulk writes into batches that fit the limit.
`COPY ... FROM STDIN` uses `query.writable()` and `COPY ... TO STDOUT` uses
`query.readable()`; plain execution rejects with `ERR_POSTGRES_COPY_NOT_SUPPORTED`.
PostgreSQL `query.cancel()` asks the server to cancel an in-flight query.
In-flight MySQL and MariaDB queries still run to completion.
MySQL `DATETIME` and `TIMESTAMP` and PostgreSQL `timestamp` read through `.simple()`
are UTC; remove manual time-zone corrections. On MariaDB 10.5 and newer,
JSON columns and JSON function results are decoded, so remove manual `JSON.parse()` calls.
`Bun.markdown.html()` passes raw HTML, event attributes, and `javascript:` links
through verbatim; sanitize rendered HTML from untrusted Markdown.
`Bun.cron` uses local time by default and accepts `{ tz }` for an explicit zone.
Experimental `Bun.ModuleGraph` separates module state, timers, and I/O for trusted apps.
Memory64 is disabled by default; enable it with `BUN_JSC_useWasmMemory64=1 bun app.js`.
Use `Bun.plugin()` for loader customization: `module.register()` has no effect
and `registerHooks()` is missing. Bun/Node IPC needs JSON serialization;
`serialization: "advanced"` requires Bun at both ends.
Read and write `node:v8` serialized data with the same runtime because Bun's
wire format is incompatible with Node.js.