{"name": "bun", "version": "0.1.0", "hash": "sha256:57616b6ace047f14a1e6b4a7f3fee4991bd70514444fd1d16bf90c72a0e08f4e", "files": {"ABSORB_REPORT.md": "# Absorb report: bun\n\n- **Source:** https://github.com/oven-sh/bun at `e13b16bc7ed7`\n- **Licence:** MIT\n- **Project names searched for:** oven-sh_bun\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| implementing-jsc-classes-cpp | skill | mixed |  | src/jsc/bindings/webcore/DOMClientIsoSubspaces.h, src/jsc/bindings/webcore/DOMIsoSubspaces.h, src/jsc/bindings/BunClientData.cpp, test/internal/source-lints/iso-subspace-creation.test.ts |\n| implementing-jsc-classes-rust | skill | mixed |  | src/codegen/bindgen.ts, docs/project/bindgen.mdx, src/jsc/bindgen_test.bind.ts, src/jsc/bindgen_test.rs, src/jsc/resolve_message.bind.ts, src/runtime/webcore/fetch/FetchSession.bind.ts |\n| javascriptcore-garbage-collector | skill | mixed |  | src/jsc/bindings/BunGCOutputConstraint.cpp, src/jsc/bindings/webcore/JSDOMInterface.h, src/jsc/bindings/JSDOMWrapperCache.h, src/jsc/JSRef.rs |\n| rust-system-calls | skill | mixed |  | src/CLAUDE.md |\n| slowest-tests | skill | mixed |  | scripts/ci-slowest-tests.ts, test/js/bun/cron/in-process-cron.test.ts, test/js/bun/http/serve-body-leak.test.ts, test |\n| verify | skill | mixed |  | src/js, src/jsc/bindings/InternalModuleRegistry.cpp |\n| writing-bundler-tests | skill | mixed |  | test/bundler/expectBundled.ts, test/bundler, test/bundler/bundler_banner.test.ts |\n| writing-dev-server-tests | skill | mixed |  | test/bake/bake-harness.ts, test/bake/client-fixture.mjs, test/bake/dev |\n| find-duplicate-prs | command | mechanics |  |  |\n| find-issues | command | mechanics |  |  |\n| upgrade-boringssl | command | mixed |  | scripts/build/deps/boringssl.ts, src/js/node/tls.ts, test/js/node/crypto, test/js/bun/crypto, test/js/node/tls, test/js/web/fetch/fetch.tls.test.ts, src/boringssl_sys/boringssl.rs, packages/bun-usockets/src/crypto/openssl.cpp, src/runtime/socket/UpgradedDuplex.rs |\n| upgrade-nodejs | command | mixed |  | scripts/build/ci-images/spec.ts, scripts/darwin-ci, scripts/build/deps/nodejs-headers.ts, src/jsc/bindings/BunProcess.cpp, src/runtime/napi/js_native_api_types.h, src/runtime/napi/README.md, src/jsc/bindings/v8, test/v8/v8.test.ts, test/napi/napi.test.ts |\n| upgrade-webkit | command | mixed |  | scripts/build/deps/webkit.ts, scripts/build/deps/webkit.sha256, src/jsc/JSType.rs, src/icu, src/icu/README.md, .github/workflows |\n| hooks/post-edit-format.js | hook-file | mechanics |  |  |\n| hooks/pre-bash-guard.js | hook-file | mechanics |  |  |\n| PreToolUse [Bash] | hook | mechanics |  |  |\n| PostToolUse [Write|Edit|MultiEdit] | hook | mechanics |  |  |\n\n## Needs review before sharing\n\nThese pieces mention the project by name or lean on its files. Move those facts into configuration, or keep the piece out of a shared starter.\n\n- **implementing-jsc-classes-cpp** (skill): paths src/jsc/bindings/webcore/DOMClientIsoSubspaces.h, src/jsc/bindings/webcore/DOMIsoSubspaces.h, src/jsc/bindings/BunClientData.cpp, test/internal/source-lints/iso-subspace-creation.test.ts\n- **implementing-jsc-classes-rust** (skill): paths src/codegen/bindgen.ts, docs/project/bindgen.mdx, src/jsc/bindgen_test.bind.ts, src/jsc/bindgen_test.rs, src/jsc/resolve_message.bind.ts, src/runtime/webcore/fetch/FetchSession.bind.ts\n- **javascriptcore-garbage-collector** (skill): paths src/jsc/bindings/BunGCOutputConstraint.cpp, src/jsc/bindings/webcore/JSDOMInterface.h, src/jsc/bindings/JSDOMWrapperCache.h, src/jsc/JSRef.rs\n- **rust-system-calls** (skill): paths src/CLAUDE.md\n- **slowest-tests** (skill): paths scripts/ci-slowest-tests.ts, test/js/bun/cron/in-process-cron.test.ts, test/js/bun/http/serve-body-leak.test.ts, test\n- **verify** (skill): paths src/js, src/jsc/bindings/InternalModuleRegistry.cpp\n- **writing-bundler-tests** (skill): paths test/bundler/expectBundled.ts, test/bundler, test/bundler/bundler_banner.test.ts\n- **writing-dev-server-tests** (skill): paths test/bake/bake-harness.ts, test/bake/client-fixture.mjs, test/bake/dev\n- **upgrade-boringssl** (command): paths scripts/build/deps/boringssl.ts, src/js/node/tls.ts, test/js/node/crypto, test/js/bun/crypto, test/js/node/tls, test/js/web/fetch/fetch.tls.test.ts, src/boringssl_sys/boringssl.rs, packages/bun-usockets/src/crypto/openssl.cpp, src/runtime/socket/UpgradedDuplex.rs\n- **upgrade-nodejs** (command): paths scripts/build/ci-images/spec.ts, scripts/darwin-ci, scripts/build/deps/nodejs-headers.ts, src/jsc/bindings/BunProcess.cpp, src/runtime/napi/js_native_api_types.h, src/runtime/napi/README.md, src/jsc/bindings/v8, test/v8/v8.test.ts, test/napi/napi.test.ts\n- **upgrade-webkit** (command): paths scripts/build/deps/webkit.ts, scripts/build/deps/webkit.sha256, src/jsc/JSType.rs, src/icu, src/icu/README.md, .github/workflows\n- **find-duplicate-prs**: was a slash command; now a skill\n- **find-issues**: was a slash command; now a skill\n- **upgrade-boringssl**: was a slash command; now a skill\n- **upgrade-nodejs**: was a slash command; now a skill\n- **upgrade-webkit**: was a slash command; now a skill\n\n## Not absorbed\n\n- instruction files (CLAUDE.md): they describe the project, so they stay with it. Pass --with-instructions to absorb them for review\n- `.claude/docs/` (1 file(s)): this version of absorb does not read it, so it stays with the project\n- `.claude/skills/sync-react-compiler.md`: not a skill (a skill is a folder with a SKILL.md)\n\n## Self-test\n\n1 generated case(s) in `selftest/cases.yaml`.\n2 hook(s) were absorbed. A hook that guards something is only proven once a case shows it blocking: add `block` and `allow` cases for each, then run `baudrier selftest`.\n\n## Warnings\n\n- the licence MIT was named with --license-reviewed, not recognised from LICENSE.md: the harness records that\n", "ATTRIBUTION.md": "# Attribution: bun\n\nThis harness was absorbed from https://github.com/oven-sh/bun at commit `e13b16bc7ed7f69252196cb5c93852d6337fbcba` on 2026-11-26 with `baudrier absorb`.\n\n- **Licence:** MIT (named by the person who absorbed it: the licence file was not recognised automatically, so read it before sharing this harness further). Licence and notice files kept unchanged in this folder: `LICENSE.md`.\n- **Credit:** every file listed below is the work of the source repository's authors. Files were copied unchanged, except that hook commands name their folder as `${HARNESS_HOOKS}` and slash commands were wrapped as skills.\n\n## Absorbed files\n\n- `skills/implementing-jsc-classes-cpp/SKILL.md` (skill)\n- `skills/implementing-jsc-classes-rust/SKILL.md` (skill)\n- `skills/javascriptcore-garbage-collector/SKILL.md` (skill)\n- `skills/rust-system-calls/SKILL.md` (skill)\n- `skills/slowest-tests/SKILL.md` (skill)\n- `skills/verify/SKILL.md` (skill)\n- `skills/writing-bundler-tests/SKILL.md` (skill)\n- `skills/writing-dev-server-tests/SKILL.md` (skill)\n- `skills/find-duplicate-prs/SKILL.md` (command)\n- `skills/find-issues/SKILL.md` (command)\n- `skills/upgrade-boringssl/SKILL.md` (command)\n- `skills/upgrade-nodejs/SKILL.md` (command)\n- `skills/upgrade-webkit/SKILL.md` (command)\n- `hooks/post-edit-format.js` (hook-file)\n- `hooks/pre-bash-guard.js` (hook-file)\n", "LICENSE.md": "Bun itself is MIT-licensed.\n\n## JavaScriptCore\n\nBun statically links JavaScriptCore (and WebKit) which is LGPL-2 licensed. WebCore files from WebKit are also licensed under LGPL2. Per LGPL2:\n\n> (1) If you statically link against an LGPL’d library, you must also provide your application in an object (not necessarily source) format, so that a user has the opportunity to modify the library and relink the application.\n\nYou can find the patched version of WebKit used by Bun here: <https://github.com/oven-sh/webkit>. If you would like to relink Bun with changes:\n\n- `git clone https://github.com/oven-sh/WebKit vendor/WebKit`\n- `bun sync-webkit-source` (checks out the version pinned in `WEBKIT_VERSION` in `scripts/build/deps/webkit.ts`)\n- `bun run build:local`\n\nThis compiles JavaScriptCore, compiles Bun’s `.cpp` bindings for JavaScriptCore (which are the object files using JavaScriptCore) and outputs a new `bun` binary with your changes.\n\n## Linked libraries\n\nBun statically links these libraries:\n\n| Library | License |\n|---------|---------|\n| [`boringssl`](https://boringssl.googlesource.com/boringssl/) | [several licenses](https://boringssl.googlesource.com/boringssl/+/refs/heads/master/LICENSE) |\n| [`brotli`](https://github.com/google/brotli) (not linked: the Brotli codec is derived from parts of it) | MIT |\n| [`libarchive`](https://github.com/libarchive/libarchive) (not linked: `src/tar` is derived from parts of it) | [several licenses](https://github.com/libarchive/libarchive/blob/master/COPYING) |\n| [`llhttp`](https://github.com/nodejs/llhttp) (not linked: `src/http1` is derived from parts of it) | MIT |\n| [`lol-html`](https://github.com/cloudflare/lol-html/tree/master/c-api) | BSD 3-Clause |\n| [`ls-hpack`](https://github.com/litespeedtech/ls-hpack) (not linked: `src/hpack` is derived from parts of it) | MIT |\n| [`ls-qpack`](https://github.com/litespeedtech/ls-qpack) | MIT |\n| [`lsquic`](https://github.com/litespeedtech/lsquic) | MIT (portions derived from [Chromium proto-quic](https://github.com/litespeedtech/lsquic/blob/master/LICENSE.chrome), BSD 3-Clause) |\n| [`mimalloc`](https://github.com/microsoft/mimalloc) | MIT |\n| [`picohttpparser`](https://github.com/h2o/picohttpparser) (not linked: `src/http1` is derived from parts of it) | dual-licensed under the Perl License or the MIT License |\n| [`zstd`](https://github.com/facebook/zstd) (not linked: `src/zstd` is derived from parts of it) | dual-licensed under the BSD License or GPLv2 license |\n| [`simdutf`](https://github.com/simdutf/simdutf) | Apache 2.0 |\n| [`tinycc`](https://github.com/tinycc/tinycc) | LGPL v2.1 |\n| [`uSockets`](https://github.com/uNetworking/uSockets) | Apache 2.0 |\n| [`zlib-ng`](https://github.com/zlib-ng/zlib-ng) (not linked: `src/zlib` is derived from parts of it) | zlib |\n| [`c-ares`](https://github.com/c-ares/c-ares) (not linked: `src/dns` is derived from parts of it) | MIT licensed |\n| [`libicu`](https://github.com/unicode-org/icu) 79 (its data are linked, and `src/icu` is derived from parts of its code) | [license here](https://github.com/unicode-org/icu/blob/main/icu4c/LICENSE) |\n| [`libbase64`](https://github.com/aklomp/base64/blob/master/LICENSE) | BSD 2-Clause |\n| [`libuv`](https://github.com/libuv/libuv) (on Windows) | MIT |\n| [`libdeflate`](https://github.com/ebiggers/libdeflate) (not linked: `src/deflate` and its checksum kernels are derived from it) | [MIT](https://github.com/ebiggers/libdeflate/blob/master/COPYING) |\n| [`libjpeg-turbo`](https://github.com/libjpeg-turbo/libjpeg-turbo) (not linked: the JPEG codec is derived from parts of it, and so based in part on the work of the Independent JPEG Group) | [BSD 3-Clause / IJG / zlib](https://github.com/libjpeg-turbo/libjpeg-turbo/blob/main/LICENSE.md) |\n| [`libspng`](https://github.com/randy408/libspng) (not linked: `src/png` is derived from parts of it) | BSD 2-Clause |\n| [`stb_image`](https://github.com/nothings/stb) (not linked: the PNG codec finds the Paeth predictor its way) | MIT or public domain |\n| [`libwebp`](https://github.com/webmproject/libwebp) (not linked: `src/webp` is derived from parts of it) | BSD 3-Clause |\n| [`highway`](https://github.com/google/highway) | Apache 2.0 |\n| [`uucode`](https://github.com/jacobsandlund/uucode) | MIT |\n| A fork of [`uWebsockets`](https://github.com/jarred-sumner/uwebsockets) (`src/http1` and `src/websocket` are derived from parts of it) | Apache 2.0 licensed |\n| Parts of [Tigerbeetle's IO code](https://github.com/tigerbeetle/tigerbeetle/blob/532c8b70b9142c17e07737ab6d3da68d7500cbca/src/io/windows.zig#L1) | Apache 2.0 licensed |\n| `__cxa_thread_atexit` fallback from [LLVM libc++abi](https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/libcxxabi/src/cxa_thread_atexit.cpp) | Apache 2.0 with LLVM exception |\n| The type checker behind `bun check` and the parser it shares with `bun lint` and `bun fmt` are ports of [`typescript-go`](https://github.com/microsoft/typescript-go). They use TypeScript's diagnostic messages and `lib.*.d.ts` files | Apache 2.0 |\n| `bun lint` ports large parts of [ESLint](https://github.com/eslint/eslint): code path analysis, rule helpers such as `ast-utils.js`, config and comment handling, and many rules. The ESLint rules in `bun lint` use ESLint's rule names, options, option schemas, messages and descriptions. The `eslint:recommended` and `eslint:all` presets are ESLint's. Parts of `main.js` in `src/lint/js_plugin/worker` are copied from ESLint, and parts of `LintReport.cpp`, `LintSourceCode.cpp` and `LintTokens.cpp` in `src/jsc/bindings` are ported from it | MIT |\n| `bun lint` does the same with the rules of [`typescript-eslint`](https://github.com/typescript-eslint/typescript-eslint). It also ports `type-utils` and the plugin's `util` helpers, and uses its presets, the error messages of `typescript-estree` and the `lib` globals of `scope-manager` | MIT |\n| Selectors in `bun lint` are a port of [`esquery`](https://github.com/estools/esquery) | BSD 3-Clause |\n| `bun lint` has ports of [`@eslint-community/regexpp`](https://github.com/eslint-community/regexpp), [`@eslint-community/eslint-utils`](https://github.com/eslint-community/eslint-utils), [`levn`](https://github.com/gkz/levn) and [`natural-compare`](https://github.com/litejs/natural-compare-lite), and of parts of [`ts-api-utils`](https://github.com/JoshuaKGoldberg/ts-api-utils) and [`@eslint/eslintrc`](https://github.com/eslint/eslintrc) | MIT |\n| `bun lint` uses the error messages of [`ajv`](https://github.com/ajv-validator/ajv), [`acorn`](https://github.com/acornjs/acorn) and [`optionator`](https://github.com/gkz/optionator), and the lists in [`globals`](https://github.com/sindresorhus/globals) and [`is-core-module`](https://github.com/inspect-js/is-core-module) | MIT |\n| `bun lint` uses the error messages of [`espree`](https://github.com/eslint/js/tree/main/packages/espree) | BSD 2-Clause |\n| `bun lint` uses the `JSON.parse` error messages of [V8](https://github.com/v8/v8) | BSD 3-Clause |\n| `bun lint` has ports of parts of [`@eslint/plugin-kit`, `@eslint/config-array`, `@eslint/config-helpers` and `@eslint/compat`](https://github.com/eslint/rewrite) | Apache 2.0 |\n| `bun lint` and `bun fmt` have a port of the pattern-to-regular-expression table of [`ignore`](https://github.com/kaelzhang/node-ignore) | MIT |\n| `bun lint` and `bun fmt` have ports of [`is-glob`](https://github.com/micromatch/is-glob) and [`is-extglob`](https://github.com/jonschlinkert/is-extglob) | MIT |\n| `bun lint` and `bun fmt` have a port of [`glob-parent`](https://github.com/gulpjs/glob-parent) | ISC |\n| The `react-hooks`, `import`, `n`, `react` and `prettier` rules in `bun lint` are ports of the rules in [`eslint-plugin-react-hooks`](https://github.com/facebook/react/tree/main/packages/eslint-plugin-react-hooks), [`eslint-plugin-import`](https://github.com/import-js/eslint-plugin-import), [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n), [`eslint-plugin-es-x`](https://github.com/eslint-community/eslint-plugin-es-x), [`eslint-plugin-react`](https://github.com/jsx-eslint/eslint-plugin-react) and [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier), with the same rule names, options and messages. They include the Node.js version tables of `eslint-plugin-n` and a few functions from [`jsx-ast-utils`](https://github.com/jsx-eslint/jsx-ast-utils) and [`prettier-linter-helpers`](https://github.com/prettier/prettier-linter-helpers) | MIT |\n| The text diff used by `bun test` and the `prettier/prettier` rule has parts of [`diff-match-patch`](https://github.com/google/diff-match-patch) and of [`fast-diff`](https://github.com/jhchen/fast-diff), which is derived from it | Apache 2.0 |\n| `Bun.diff` has a port of the search, the tokenizers and the patch functions of [`diff`](https://github.com/kpdecker/jsdiff) | BSD 3-Clause |\n| The `unicorn`, `oxc`, `react-perf`, `jsx-a11y`, `nextjs`, `promise`, `node`, `jest` and `vitest` rules in `bun lint` are ports of the rules in [`oxlint`](https://github.com/oxc-project/oxc), with its messages and help text. With an oxlint config, the other rules use the messages of oxlint and [`tsgolint`](https://github.com/oxc-project/tsgolint) too. `bun lint` also ports parts of `oxc_jsdoc` and `oxc_react_compiler` | MIT |\n| oxlint ported those rules from [`eslint-plugin-unicorn`](https://github.com/sindresorhus/eslint-plugin-unicorn), [`eslint-plugin-react-perf`](https://github.com/cvazac/eslint-plugin-react-perf), [`eslint-plugin-jsx-a11y`](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y), [`@next/eslint-plugin-next`](https://github.com/vercel/next.js/tree/canary/packages/eslint-plugin-next), [`eslint-plugin-n`](https://github.com/eslint-community/eslint-plugin-n), [`eslint-plugin-jest`](https://github.com/jest-community/eslint-plugin-jest) and [`@vitest/eslint-plugin`](https://github.com/vitest-dev/eslint-plugin-vitest). Their rule names, options and some of their messages are in `bun lint` | MIT |\n| oxlint ported its `promise` rules from [`eslint-plugin-promise`](https://github.com/eslint-community/eslint-plugin-promise) | ISC |\n| The ARIA tables of the `jsx-a11y` rules come from [`aria-query`](https://github.com/A11yance/aria-query) by way of oxlint | Apache 2.0 |\n| `bun fmt` is a port of [Prettier](https://github.com/prettier/prettier): its printers for CSS, SCSS, Less, HTML, Vue, Angular, Markdown, YAML, GraphQL and Handlebars, its document printer, its handling of options, pragmas, ranges, cursor offsets and embedded code, and the HTML tables it is built with | MIT |\n| The JavaScript and TypeScript printer of `bun fmt`, its JSDoc formatting and its oxfmt-style import sorting are a port of [`oxc_formatter`](https://github.com/oxc-project/oxc/tree/main/crates/oxc_formatter), which is a port of the [Biome](https://github.com/biomejs/biome) formatter. The intermediate representation and its printer come from Biome by way of `oxc_formatter_core` | MIT |\n| `bun fmt` has ports of the parsers in [`postcss`](https://github.com/postcss/postcss), [`postcss-scss`](https://npmjs.com/package/postcss-scss), [`postcss-less`](https://npmjs.com/package/postcss-less), [`postcss-selector-parser`](https://github.com/postcss/postcss-selector-parser), [`postcss-media-query-parser`](https://github.com/dryoma/postcss-media-query-parser), [`postcss-values-parser`](https://npmjs.com/package/postcss-values-parser), [`angular-html-parser`](https://npmjs.com/package/angular-html-parser), [`graphql-js`](https://github.com/graphql/graphql-js), [`@glimmer/syntax`](https://github.com/glimmerjs/glimmer-vm), [`simple-html-tokenizer`](https://github.com/tildeio/simple-html-tokenizer) and [`@angular/compiler`](https://github.com/angular/angular), and of parts of [`yaml-unist-parser`](https://npmjs.com/package/yaml-unist-parser) and [`angular-estree-parser`](https://npmjs.com/package/angular-estree-parser) | MIT |\n| `bun fmt` also has a port of [`@handlebars/parser`](https://github.com/handlebars-lang/handlebars-parser) and of one file of [`yaml`](https://npmjs.com/package/yaml) | ISC |\n| Import sorting in `bun fmt` has ports of [`@trivago/prettier-plugin-sort-imports`](https://github.com/trivago/prettier-plugin-sort-imports) and [`@ianvs/prettier-plugin-sort-imports`](https://github.com/ianvs/prettier-plugin-sort-imports), and of `organizeImports.ts` in [TypeScript](https://github.com/microsoft/TypeScript) | Apache 2.0 |\n| `bun fmt` has ports of [`jest-docblock`](https://github.com/jestjs/jest/tree/main/packages/jest-docblock) and the crates [`sort-package-json`](https://crates.io/crates/sort-package-json) and [`oxc-toml`](https://crates.io/crates/oxc-toml) (a fork of taplo), and of parts of [`@babel/generator`](https://github.com/babel/babel), [`micromark`](https://github.com/micromark/micromark) and [`editorconfig-without-wasm`](https://github.com/fisker/editorconfig-core-js-without-wasm). Its character width tables are generated from [`emoji-regex`](https://github.com/mathiasbynens/emoji-regex), [`get-east-asian-width`](https://github.com/sindresorhus/get-east-asian-width) and [`narrow-emojis`](https://npmjs.com/package/narrow-emojis) | MIT |\n| Tailwind class sorting in `bun fmt` is a port of parts of [`prettier-plugin-tailwindcss`](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) | MIT |\n| Svelte formatting in `bun fmt` is a port of [`prettier-plugin-svelte`](https://github.com/sveltejs/prettier-plugin-svelte) and of the template parser of [Svelte](https://github.com/sveltejs/svelte) | MIT |\n| With `prettier-plugin-packagejson` in a Prettier config, `bun fmt` sorts `package.json` with a port of the npm package [`sort-package-json`](https://github.com/keithamus/sort-package-json) and the list in [`git-hooks-list`](https://github.com/fisker/git-hooks-list) | MIT |\n\nThe tests in `test/cli/lint/conformance` and `test/cli/format` include test cases from ESLint, typescript-eslint, the ESLint plugins above, oxc, tsgolint, Prettier and the two import sorting plugins. They are not part of the `bun` binary. Their licenses are next to them.\n\n## Polyfills\n\nFor compatibility reasons, the following packages are embedded into Bun's binary and injected if imported.\n\n| Package | License |\n|---------|---------|\n| [`acorn`](https://github.com/acornjs/acorn) | MIT |\n| [`acorn-walk`](https://github.com/acornjs/acorn) | MIT |\n| [`assert`](https://npmjs.com/package/assert) | MIT |\n| [`browserify-zlib`](https://npmjs.com/package/browserify-zlib) | MIT |\n| [`buffer`](https://npmjs.com/package/buffer) | MIT |\n| [`constants-browserify`](https://npmjs.com/package/constants-browserify) | MIT |\n| [`crypto-browserify`](https://npmjs.com/package/crypto-browserify) | MIT |\n| [`domain-browser`](https://npmjs.com/package/domain-browser) | MIT |\n| [`events`](https://npmjs.com/package/events) | MIT |\n| [`https-browserify`](https://npmjs.com/package/https-browserify) | MIT |\n| [`os-browserify`](https://npmjs.com/package/os-browserify) | MIT |\n| [`path-browserify`](https://npmjs.com/package/path-browserify) | MIT |\n| [`process`](https://npmjs.com/package/process) | MIT |\n| [`punycode`](https://npmjs.com/package/punycode) | MIT |\n| [`querystring-es3`](https://npmjs.com/package/querystring-es3) | MIT |\n| [`stream-browserify`](https://npmjs.com/package/stream-browserify) | MIT |\n| [`stream-http`](https://npmjs.com/package/stream-http) | MIT |\n| [`string_decoder`](https://npmjs.com/package/string_decoder) | MIT |\n| [`timers-browserify`](https://npmjs.com/package/timers-browserify) | MIT |\n| [`tty-browserify`](https://npmjs.com/package/tty-browserify) | MIT |\n| [`url`](https://npmjs.com/package/url) | MIT |\n| [`util`](https://npmjs.com/package/util) | MIT |\n| [`vm-browserify`](https://npmjs.com/package/vm-browserify) | MIT |\n\n## Type declarations\n\nThe type declarations of these packages are embedded into Bun's binary. `bun build --compile --aot` reads them in a project that hasn't installed `@types/bun`. They're embedded without their comments, except for copyright notices. The `LICENSE` files of `@types/node` and `undici-types` are embedded next to them.\n\n| Package | License |\n|---------|---------|\n| [`@types/node`](https://npmjs.com/package/@types/node) | MIT |\n| [`undici-types`](https://npmjs.com/package/undici-types) | MIT |\n| [`expect-type`](https://npmjs.com/package/expect-type), which `bun-types` includes | Apache 2.0 |\n| Types from [`jest-mock`](https://npmjs.com/package/jest-mock), which `bun-types` includes | MIT |\n\n## Additional credits\n\n- Bun's JS transpiler, CSS lexer, and Node.js module resolver source code is a port of [@evanw](https://github.com/evanw)’s [esbuild](https://github.com/evanw/esbuild) project.\n- Credit to [@kipply](https://github.com/kipply) for the name \"Bun\"!", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: bun\n  description: 'How the Bun repository runs its agents: a shell guard that stops slow\n    or wrong build and test commands, format on edit, and skills for its C++, Rust\n    and test work.'\n  version: 0.1.0\n  license: MIT\nskills:\n- name: implementing-jsc-classes-cpp\n  source: ./skills/implementing-jsc-classes-cpp\n- name: implementing-jsc-classes-rust\n  source: ./skills/implementing-jsc-classes-rust\n- name: javascriptcore-garbage-collector\n  source: ./skills/javascriptcore-garbage-collector\n- name: rust-system-calls\n  source: ./skills/rust-system-calls\n- name: slowest-tests\n  source: ./skills/slowest-tests\n- name: verify\n  source: ./skills/verify\n- name: writing-bundler-tests\n  source: ./skills/writing-bundler-tests\n- name: writing-dev-server-tests\n  source: ./skills/writing-dev-server-tests\n- name: find-duplicate-prs\n  source: ./skills/find-duplicate-prs\n- name: find-issues\n  source: ./skills/find-issues\n- name: upgrade-boringssl\n  source: ./skills/upgrade-boringssl\n- name: upgrade-nodejs\n  source: ./skills/upgrade-nodejs\n- name: upgrade-webkit\n  source: ./skills/upgrade-webkit\nx-hooks:\n  runtime: claude-code\n  files: ./hooks\n  handlers:\n  - event: PreToolUse\n    matcher: Bash\n    command: ${HARNESS_HOOKS}/pre-bash-guard.js\n  - event: PostToolUse\n    matcher: Write|Edit|MultiEdit\n    command: ${HARNESS_HOOKS}/post-edit-format.js\nx-origin:\n  repository: https://github.com/oven-sh/bun\n  commit: e13b16bc7ed7f69252196cb5c93852d6337fbcba\n  license: MIT\n  license_basis: reviewed\n  license_files:\n  - LICENSE.md\n  absorbed_at: '2026-11-26'\nx-selftest: file://./selftest/cases.yaml\n", "hooks/post-edit-format.js": "#!/usr/bin/env bun\nimport { extname } from \"path\";\nimport { spawnSync } from \"child_process\";\n\nconst input = await Bun.stdin.json();\n\nconst toolName = input.tool_name;\nconst toolInput = input.tool_input || {};\nconst filePath = toolInput.file_path;\n\n// Only process Write, Edit, and MultiEdit tools\nif (![\"Write\", \"Edit\", \"MultiEdit\"].includes(toolName)) {\n  process.exit(0);\n}\n\nconst ext = extname(filePath);\n\n// Only format known files\nif (!filePath) {\n  process.exit(0);\n}\n\nfunction formatTypeScriptFile() {\n  try {\n    // Format only — NO organize-imports plugin. That plugin strips imports\n    // it thinks are unused, which breaks split edits (add import → use it\n    // in next edit). CI's `bun run prettier` runs the plugin, so imports\n    // still get cleaned up before merge.\n    const result = spawnSync(\"./node_modules/.bin/prettier\", [\"--config\", \".prettierrc\", \"--write\", filePath], {\n      cwd: process.env.CLAUDE_PROJECT_DIR || process.cwd(),\n      encoding: \"utf-8\",\n    });\n  } catch (error) {}\n}\n\nif (\n  [\n    \".cjs\",\n    \".css\",\n    \".html\",\n    \".js\",\n    \".json\",\n    \".jsonc\",\n    \".jsx\",\n    \".less\",\n    \".mjs\",\n    \".pcss\",\n    \".postcss\",\n    \".sass\",\n    \".scss\",\n    \".styl\",\n    \".stylus\",\n    \".toml\",\n    \".ts\",\n    \".tsx\",\n    \".yaml\",\n  ].includes(ext)\n) {\n  formatTypeScriptFile();\n}\n\nprocess.exit(0);\n", "hooks/pre-bash-guard.js": "#!/usr/bin/env bun\nimport { basename, extname } from \"path\";\n\nconst input = await Bun.stdin.json();\n\nconst toolName = input.tool_name;\nconst toolInput = input.tool_input || {};\nconst command = toolInput.command || \"\";\nconst timeout = toolInput.timeout;\nconst cwd = input.cwd || \"\";\n\n// Get environment variables from the hook context\n// Note: We check process.env directly as env vars are inherited\nlet useSystemBun = process.env.USE_SYSTEM_BUN;\n\nif (toolName !== \"Bash\" || !command) {\n  process.exit(0);\n}\n\nfunction denyWithReason(reason) {\n  const output = {\n    hookSpecificOutput: {\n      hookEventName: \"PreToolUse\",\n      permissionDecision: \"deny\",\n      permissionDecisionReason: reason,\n    },\n  };\n  console.log(JSON.stringify(output));\n  process.exit(0);\n}\n\n// Parse the command to extract argv0 and positional args\nlet tokens;\ntry {\n  // Simple shell parsing - split on spaces but respect quotes (both single and double)\n  tokens = command.match(/(?:[^\\s\"']+|\"[^\"]*\"|'[^']*')+/g)?.map(t => t.replace(/^['\"]|['\"]$/g, \"\")) || [];\n} catch {\n  process.exit(0);\n}\n\nif (tokens.length === 0) {\n  process.exit(0);\n}\n\n// Strip inline environment variable assignments (e.g., FOO=1 bun test)\nconst inlineEnv = new Map();\nlet commandStart = 0;\nwhile (\n  commandStart < tokens.length &&\n  /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[commandStart]) &&\n  !tokens[commandStart].includes(\"/\")\n) {\n  const [name, value = \"\"] = tokens[commandStart].split(\"=\", 2);\n  inlineEnv.set(name, value);\n  commandStart++;\n}\nif (commandStart >= tokens.length) {\n  process.exit(0);\n}\ntokens = tokens.slice(commandStart);\nuseSystemBun = inlineEnv.get(\"USE_SYSTEM_BUN\") ?? useSystemBun;\n\n// Get the executable name (argv0)\nconst argv0 = basename(tokens[0], extname(tokens[0]));\n\n\n// Disallow direct `rustfmt`: it doesn't read the workspace edition from\n// Cargo.toml the way `cargo fmt` does, so its output can disagree with CI's\n// Format job (`cargo fmt --all --check`).\nif (argv0 === \"rustfmt\") {\n  denyWithReason(\"error: Don't run `rustfmt` directly. Run `cargo fmt --all` — it's what CI checks.\");\n}\n\n// Check if argv0 is timeout and the command is \"bun bd\"\nif (argv0 === \"timeout\") {\n  // Find the actual command after timeout and its arguments\n  const timeoutArgEndIndex = tokens.slice(1).findIndex(t => !t.startsWith(\"-\") && !/^\\d/.test(t));\n  if (timeoutArgEndIndex === -1) {\n    process.exit(0);\n  }\n\n  const actualCommandIndex = timeoutArgEndIndex + 1;\n  if (actualCommandIndex >= tokens.length) {\n    process.exit(0);\n  }\n\n  const actualCommand = basename(tokens[actualCommandIndex]);\n  const restArgs = tokens.slice(actualCommandIndex + 1);\n\n  // Check if it's \"bun bd\" or \"bun-debug bd\" without other positional args\n  if (actualCommand === \"bun\" || actualCommand.includes(\"bun-debug\")) {\n    // Claude is a sneaky fucker\n    let positionalArgs = restArgs.filter(arg => !arg.startsWith(\"-\"));\n    const redirectStderrToStdoutIndex = positionalArgs.findIndex(arg => arg === \"2>&1\");\n    if (redirectStderrToStdoutIndex !== -1) {\n      positionalArgs.splice(redirectStderrToStdoutIndex, 1);\n    }\n    const redirectStdoutToStderrIndex = positionalArgs.findIndex(arg => arg === \"1>&2\");\n    if (redirectStdoutToStderrIndex !== -1) {\n      positionalArgs.splice(redirectStdoutToStderrIndex, 1);\n    }\n\n    const redirectToFileIndex = positionalArgs.findIndex(arg => arg === \">\");\n    if (redirectToFileIndex !== -1) {\n      positionalArgs.splice(redirectToFileIndex, 2);\n    }\n\n    const redirectToFileAppendIndex = positionalArgs.findIndex(arg => arg === \">>\");\n    if (redirectToFileAppendIndex !== -1) {\n      positionalArgs.splice(redirectToFileAppendIndex, 2);\n    }\n\n    const redirectTOFileInlineIndex = positionalArgs.findIndex(arg => arg.startsWith(\">\"));\n    if (redirectTOFileInlineIndex !== -1) {\n      positionalArgs.splice(redirectTOFileInlineIndex, 1);\n    }\n\n    const pipeIndex = positionalArgs.findIndex(arg => arg === \"|\");\n    if (pipeIndex !== -1) {\n      positionalArgs = positionalArgs.slice(0, pipeIndex);\n    }\n\n    positionalArgs = positionalArgs.map(arg => arg.trim()).filter(Boolean);\n\n    if (positionalArgs.length === 1 && positionalArgs[0] === \"bd\") {\n      denyWithReason(\"error: Run `bun bd` without a timeout\");\n    }\n  }\n}\n\n// Check if command is \"bun .* test\" or \"bun-debug test\" with -u/--update-snapshots AND -t/--test-name-pattern\nif (argv0 === \"bun\" || argv0.includes(\"bun-debug\")) {\n  const allArgs = tokens.slice(1);\n\n  // Check if \"test\" is in positional args or \"bd\" followed by \"test\"\n  const positionalArgs = allArgs.filter(arg => !arg.startsWith(\"-\"));\n  const hasTest = positionalArgs.includes(\"test\") || (positionalArgs[0] === \"bd\" && positionalArgs[1] === \"test\");\n\n  if (hasTest) {\n    const hasUpdateSnapshots = allArgs.some(arg => arg === \"-u\" || arg === \"--update-snapshots\");\n    const hasTestNamePattern = allArgs.some(arg => arg === \"-t\" || arg === \"--test-name-pattern\");\n\n    if (hasUpdateSnapshots && hasTestNamePattern) {\n      denyWithReason(\"error: Cannot use -u/--update-snapshots with -t/--test-name-pattern\");\n    }\n  }\n}\n\n// Check if timeout option is set for \"bun bd\" command\nif (timeout !== undefined && (argv0 === \"bun\" || argv0.includes(\"bun-debug\"))) {\n  const positionalArgs = tokens.slice(1).filter(arg => !arg.startsWith(\"-\"));\n  if (positionalArgs.length === 1 && positionalArgs[0] === \"bd\") {\n    denyWithReason(\"error: Run `bun bd` without a timeout\");\n  }\n}\n\n// Check if running \"bun test <file>\" without USE_SYSTEM_BUN=1\nif ((argv0 === \"bun\" || argv0.includes(\"bun-debug\")) && useSystemBun !== \"1\") {\n  const allArgs = tokens.slice(1);\n  const positionalArgs = allArgs.filter(arg => !arg.startsWith(\"-\"));\n\n  // Check if it's \"test\" (not \"bd test\")\n  if (positionalArgs.length >= 1 && positionalArgs[0] === \"test\" && positionalArgs[0] !== \"bd\") {\n    denyWithReason(\n      \"error: In development, use `bun bd test <file>` to test your changes. If you meant to use a release version, set USE_SYSTEM_BUN=1\",\n    );\n  }\n}\n\n// Check if running \"bun bd test\" from bun repo root or test folder without a file path\nif (argv0 === \"bun\" || argv0.includes(\"bun-debug\")) {\n  const allArgs = tokens.slice(1);\n  const positionalArgs = allArgs.filter(arg => !arg.startsWith(\"-\"));\n\n  // Check if it's \"bd test\"\n  if (positionalArgs.length >= 2 && positionalArgs[0] === \"bd\" && positionalArgs[1] === \"test\") {\n    // Check if cwd is the bun repo root or test folder\n    const isBunRepoRoot = cwd === \"/workspace/bun\" || cwd.endsWith(\"/bun\");\n    const isTestFolder = cwd.endsWith(\"/bun/test\");\n\n    if (isBunRepoRoot || isTestFolder) {\n      // Check if there's a file path argument (looks like a path: contains / or has test extension)\n      const hasFilePath = positionalArgs\n        .slice(2)\n        .some(\n          arg =>\n            arg.includes(\"/\") ||\n            arg.endsWith(\".test.ts\") ||\n            arg.endsWith(\".test.js\") ||\n            arg.endsWith(\".test.tsx\") ||\n            arg.endsWith(\".test.jsx\"),\n        );\n\n      if (!hasFilePath) {\n        denyWithReason(\n          \"error: `bun bd test` from repo root or test folder will run all tests. Use `bun bd test <path>` with a specific test file.\",\n        );\n      }\n    }\n  }\n}\n\n// Allow the command to proceed\nprocess.exit(0);\n", "selftest/cases.yaml": "cases:\n- name: rustfmt run directly\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: rustfmt src/main.rs\n  expect: block\n- name: cargo fmt\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: cargo fmt --all\n  expect: allow\n- name: bun bd under a timeout\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: timeout 60 bun bd\n  expect: block\n- name: bun bd without a timeout\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: bun bd\n  expect: allow\n- name: updating snapshots with a test name filter\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: bun bd test -u -t parses test/js/a.test.ts\n  expect: block\n- name: the release bun used for tests\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: bun test test/js/a.test.ts\n  expect: block\n- name: the release bun, asked for on purpose\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: USE_SYSTEM_BUN=1 bun test test/js/a.test.ts\n  expect: allow\n- name: the debug build testing one file\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: bun bd test test/js/a.test.ts\n  expect: allow\n- name: a harmless command\n  event: PreToolUse\n  tool: Bash\n  input:\n    command: ls -la\n  expect: allow\n", "skills/find-duplicate-prs/SKILL.md": "---\nname: find-duplicate-prs\ndescription: Find open PRs that may duplicate a given PR\nallowed-tools: Bash(gh pr view:*), Bash(gh pr diff:*), Bash(gh search:*), Bash(gh\n  pr list:*), Bash(gh api:*), Bash(gh pr comment:*), Bash(git diff:*), Bash(git log:*),\n  Bash(git show:*), Bash(git status:*), Bash(git rev-parse:*), Bash(git ls-files:*),\n  Bash(git grep:*), Bash(git branch:*), Bash(git remote:*)\n---\n\n# Find duplicate PRs command\n\nFind other open, unmerged pull requests that may be duplicates of (or substantially overlap with) a given PR.\n\nTo do this, follow these steps precisely:\n\n1. Use an agent to check if the PR (a) is closed/merged, or (b) already has a duplicate-PR comment (check for the exact HTML marker `<!-- find-duplicate-prs-bot:marker -->` in the PR comments — ignore other bot comments). If so, do not proceed.\n2. Use an agent to view the PR title, body, and diff (`gh pr view` and `gh pr diff`), and ask the agent to return a summary of:\n   - What the PR changes (files modified, functions changed, features added/fixed)\n   - Key technical terms, error messages, API names, or module names involved\n   - Any issue numbers referenced (e.g. \"fixes #123\") — two PRs that fix the same issue are likely duplicates\n3. Then, launch 3 parallel agents to search GitHub for other **open, unmerged** pull requests that may duplicate this one, using diverse keywords derived from the summary in Step 2. **IMPORTANT**: Always scope searches with `repo:owner/repo is:pr is:open is:unmerged` to constrain results to the current repository. Each agent should try a different search strategy:\n   - Agent 1: Search using the PR title keywords and referenced issue numbers\n   - Agent 2: Search using `gh pr list` filtered by the same files/paths touched in the diff\n   - Agent 3: Search using feature/API/function names from the changed code\n4. Next, feed the results from Steps 2 and 3 into another agent, so that it can filter out false positives that are not actually duplicates. Exclude the PR itself. Only keep PRs that change the same code area for the same purpose, or fix the same referenced issue. **If there are no likely duplicates remaining, do not comment at all** — silently exit.\n5. Finally, if and only if at least one likely duplicate was found, comment on the PR.\n\nNotes (be sure to tell this to your agents, too):\n\n- Use `gh` to interact with GitHub, rather than web fetch\n- You may also use read-only `git` commands (`git diff`, `git log`, `git show`, `git grep`, etc.) against the local checkout\n- Do not use other tools beyond `gh` and `git` (eg. don't use other MCP servers, file edit, etc.)\n- Make a todo list first\n- Always scope searches with `repo:owner/repo` to prevent cross-repo false positives\n- Only match against **open, unmerged** PRs — do not suggest closed, merged, or draft PRs\n- Never include the input PR in the results\n- **Do not post a comment if zero duplicates are found**\n- For your comment, follow the following format precisely (assuming for this example that you found 2 likely duplicates):\n\n---\n\nThis PR may be a duplicate of:\n\n1. <link to PR> - <one-line summary of why it overlaps>\n2. <link to PR> - <one-line summary of why it overlaps>\n\n🤖 Generated with [Claude Code](https://claude.ai/code)\n\n<!-- find-duplicate-prs-bot:marker -->\n\n---\n", "skills/find-issues/SKILL.md": "---\nname: find-issues\ndescription: Find GitHub issues that a PR might fix\nallowed-tools: Bash(gh pr view:*), Bash(gh pr diff:*), Bash(gh search:*), Bash(gh\n  issue list:*), Bash(gh issue view:*), Bash(gh api:*), Bash(gh pr comment:*), Bash(git\n  diff:*), Bash(git log:*), Bash(git show:*), Bash(git status:*), Bash(git rev-parse:*),\n  Bash(git ls-files:*), Bash(git grep:*), Bash(git branch:*), Bash(git remote:*)\n---\n\n# Find issues for PR command\n\nFind open GitHub issues that a pull request might fix. Include all likely matches — do not artificially limit the number of results.\n\nTo do this, follow these steps precisely:\n\n1. Use an agent to check if the PR (a) is closed/merged, or (b) already has a related-issues comment (check for the exact HTML marker `<!-- find-issues-bot:marker -->` in the PR comments - ignore other bot comments). If so, do not proceed.\n2. Use an agent to view the PR title, body, and diff (`gh pr view` and `gh pr diff`), and ask the agent to return a summary of:\n   - What the PR changes (files modified, functions changed, features added/fixed)\n   - Key technical terms, error messages, API names, or module names involved\n   - Any issue numbers already referenced in the PR body or commit messages\n3. Then, launch 5 parallel agents to search GitHub for open issues that this PR might fix, using diverse keywords and search approaches derived from the summary in Step 2. **IMPORTANT**: Always scope searches with `repo:owner/repo` to constrain results to the current repository only. Each agent should try a different search strategy:\n   - Agent 1: Search using error messages or symptoms described in the diff\n   - Agent 2: Search using feature/module names from the changed files\n   - Agent 3: Search using API names or function names that were modified\n   - Agent 4: Search using keywords from the PR title and description\n   - Agent 5: Search using broader terms related to the area of code changed\n4. Next, feed the results from Steps 2 and 3 into another agent, so that it can filter out false positives that are likely not actually related to the PR's changes. Exclude issues already referenced in the PR body (e.g. \"fixes #123\", \"closes #456\", \"resolves #789\"). Only keep issues where the PR changes are clearly relevant to the issue. If there are no related issues remaining, do not proceed.\n5. Finally, comment on the PR with all related open issues found (or zero, if there are no likely matches). Do not cap the number — list every issue that is a likely match.\n\nNotes (be sure to tell this to your agents, too):\n\n- Use `gh` to interact with GitHub, rather than web fetch\n- You may also use read-only `git` commands (`git diff`, `git log`, `git show`, `git grep`, etc.) against the local checkout\n- Do not use other tools beyond `gh` and `git` (eg. don't use other MCP servers, file edit, etc.)\n- Make a todo list first\n- Always scope searches with `repo:owner/repo` to prevent cross-repo false positives\n- Only match against **open** issues - do not suggest closed issues\n- Exclude issues that are already linked in the PR description\n- For your comment, follow the following format precisely (assuming for this example that you found 3 related issues). The fenced block at the bottom must contain one `Fixes #<number>` line per issue, in the same order, so the PR author can copy-paste it directly into the PR description:\n\n---\n\nFound 3 issues this PR may fix:\n\n1. <link to issue> - <one-line summary of why this PR is relevant>\n2. <link to issue> - <one-line summary of why this PR is relevant>\n3. <link to issue> - <one-line summary of why this PR is relevant>\n\n> If this is helpful, copy the block below into the PR description to auto-close these issues on merge.\n\n```\nFixes #<number>\nFixes #<number>\nFixes #<number>\n```\n\n🤖 Generated with [Claude Code](https://claude.ai/code)\n\n<!-- find-issues-bot:marker -->\n\n---\n", "skills/implementing-jsc-classes-cpp/SKILL.md": "---\nname: implementing-jsc-classes-cpp\ndescription: How the JavaScript classes that are written by hand in C++ are built. Use when changing one of them. For a new class use implementing-jsc-classes-rust.\n---\n\n# Implementing JavaScript Classes in C++\n\nA new class is written in Rust, with the bindings generator: see the `implementing-jsc-classes-rust` skill. This is for the classes that are still C++.\n\n## Class Structure\n\nFor publicly accessible Constructor and Prototype, create 3 classes:\n\n1. **`class Foo : public JSC::DestructibleObject`** - if C++ fields exist; otherwise use `JSC::constructEmptyObject` with `putDirectOffset`\n2. **`class FooPrototype : public JSC::JSNonFinalObject`**\n3. **`class FooConstructor : public JSC::InternalFunction`**\n\nNo public constructor? Only Prototype and class needed.\n\nA wrapper around a ref-counted C++ object derives from `JSDOMInterface` and uses `JSDOMPrototype` and `JSDOMConstructor` instead (see `src/jsc/bindings/webcore/JSAbortController.{h,cpp}`).\n\n## Iso Subspaces\n\nClasses with C++ fields need subspaces in:\n\n- `src/jsc/bindings/webcore/DOMClientIsoSubspaces.h`\n- `src/jsc/bindings/webcore/DOMIsoSubspaces.h`\n\n```cpp\ntemplate<typename MyClassT, JSC::SubspaceAccess mode>\nstatic JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) {\n    if constexpr (mode == JSC::SubspaceAccess::Concurrently)\n        return nullptr;\n    return WebCore::subspaceForImpl<MyClassT, WebCore::UseCustomHeapCellType::No>(\n        vm, BUN_SUBSPACE_SLOTS(m_clientSubspaceForMyClassT, m_subspaceForMyClassT));\n}\n```\n\n`subspaceForImpl` only reads the slots inline. The subspaces themselves are created by `subspaceForImplSlow` in `src/jsc/bindings/BunClientData.cpp`, which is the only place that constructs an `IsoSubspace` (`test/internal/source-lints/iso-subspace-creation.test.ts` checks this).\n\n## Property Definitions\n\n```cpp\nstatic JSC_DECLARE_HOST_FUNCTION(jsFooProtoFuncMethod);\nstatic JSC_DECLARE_CUSTOM_GETTER(jsFooGetter_property);\n\nstatic const HashTableValue JSFooPrototypeTableValues[] = {\n    { \"property\"_s, static_cast<unsigned>(PropertyAttribute::ReadOnly | PropertyAttribute::CustomAccessor), NoIntrinsic, { HashTableValue::GetterSetterType, jsFooGetter_property, 0 } },\n    { \"method\"_s, static_cast<unsigned>(PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsFooProtoFuncMethod, 1 } },\n};\n```\n\n## Prototype Class\n\n```cpp\nclass JSFooPrototype final : public JSC::JSNonFinalObject {\npublic:\n    using Base = JSC::JSNonFinalObject;\n    static constexpr unsigned StructureFlags = Base::StructureFlags;\n\n    static JSFooPrototype* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure) {\n        JSFooPrototype* prototype = new (NotNull, allocateCell<JSFooPrototype>(vm)) JSFooPrototype(vm, structure);\n        prototype->finishCreation(vm);\n        return prototype;\n    }\n\n    template<typename, JSC::SubspaceAccess>\n    static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) { return &vm.plainObjectSpace(); }\n\n    DECLARE_INFO;\n\n    static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) {\n        auto* structure = JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());\n        structure->setMayBePrototype(true);\n        return structure;\n    }\n\nprivate:\n    JSFooPrototype(JSC::VM& vm, JSC::Structure* structure) : Base(vm, structure) {}\n    void finishCreation(JSC::VM& vm);\n};\n\nvoid JSFooPrototype::finishCreation(VM& vm) {\n    Base::finishCreation(vm);\n    reifyStaticProperties(vm, JSFoo::info(), JSFooPrototypeTableValues, *this);\n    JSC_TO_STRING_TAG_WITHOUT_TRANSITION();\n}\n```\n\n## Getter/Setter/Function Definitions\n\n```cpp\n// Getter\nJSC_DEFINE_CUSTOM_GETTER(jsFooGetter_prop, (JSGlobalObject* globalObject, EncodedJSValue thisValue, PropertyName)) {\n    VM& vm = globalObject->vm();\n    auto scope = DECLARE_THROW_SCOPE(vm);\n    JSFoo* thisObject = jsDynamicCast<JSFoo*>(JSValue::decode(thisValue));\n    if (UNLIKELY(!thisObject)) {\n        Bun::throwThisTypeError(*globalObject, scope, \"JSFoo\"_s, \"prop\"_s);\n        return {};\n    }\n    return JSValue::encode(jsBoolean(thisObject->value()));\n}\n\n// Function\nJSC_DEFINE_HOST_FUNCTION(jsFooProtoFuncMethod, (JSGlobalObject* globalObject, CallFrame* callFrame)) {\n    VM& vm = globalObject->vm();\n    auto scope = DECLARE_THROW_SCOPE(vm);\n    auto* thisObject = jsDynamicCast<JSFoo*>(callFrame->thisValue());\n    if (UNLIKELY(!thisObject)) {\n        Bun::throwThisTypeError(*globalObject, scope, \"Foo\"_s, \"method\"_s);\n        return {};\n    }\n    return JSValue::encode(thisObject->doSomething(vm, globalObject));\n}\n```\n\n## Constructor Class\n\n```cpp\nclass JSFooConstructor final : public JSC::InternalFunction {\npublic:\n    using Base = JSC::InternalFunction;\n    static constexpr unsigned StructureFlags = Base::StructureFlags;\n\n    static JSFooConstructor* create(JSC::VM& vm, JSC::Structure* structure, JSC::JSObject* prototype) {\n        JSFooConstructor* constructor = new (NotNull, JSC::allocateCell<JSFooConstructor>(vm)) JSFooConstructor(vm, structure);\n        constructor->finishCreation(vm, prototype);\n        return constructor;\n    }\n\n    DECLARE_INFO;\n\n    template<typename CellType, JSC::SubspaceAccess>\n    static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) { return &vm.internalFunctionSpace(); }\n\n    static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) {\n        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::InternalFunctionType, StructureFlags), info());\n    }\n\nprivate:\n    JSFooConstructor(JSC::VM& vm, JSC::Structure* structure) : Base(vm, structure, callFoo, constructFoo) {}\n\n    void finishCreation(JSC::VM& vm, JSC::JSObject* prototype) {\n        Base::finishCreation(vm, 0, \"Foo\"_s);\n        putDirectWithoutTransition(vm, vm.propertyNames->prototype, prototype, JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly);\n    }\n};\n```\n\n## Structure Caching\n\nAdd to `ZigGlobalObject.h`:\n\n```cpp\nJSC::LazyClassStructure m_JSFooClassStructure;\n```\n\nInitialize in `ZigGlobalObject.cpp`:\n\n```cpp\nm_JSFooClassStructure.initLater([](LazyClassStructure::Initializer& init) {\n    Bun::initJSFooClassStructure(init);\n});\n```\n\nVisit in `visitChildrenImpl`:\n\n```cpp\nm_JSFooClassStructure.visit(visitor);\n```\n\n## Expose to Zig\n\n```cpp\nextern \"C\" JSC::EncodedJSValue Bun__JSFooConstructor(Zig::GlobalObject* globalObject) {\n    return JSValue::encode(globalObject->m_JSFooClassStructure.constructor(globalObject));\n}\n\nextern \"C\" EncodedJSValue Bun__Foo__toJS(Zig::GlobalObject* globalObject, Foo* foo) {\n    auto* structure = globalObject->m_JSFooClassStructure.get(globalObject);\n    return JSValue::encode(JSFoo::create(globalObject->vm(), structure, globalObject, WTFMove(foo)));\n}\n```\n\nInclude `#include \"root.h\"` at the top of C++ files.\n", "skills/implementing-jsc-classes-rust/SKILL.md": "---\nname: implementing-jsc-classes-rust\ndescription: Creates JavaScript classes using Bun's bindings generator (.bind.ts). Use when implementing new JS APIs in Rust with JSC integration, prototypes, or constructors.\n---\n\n# JavaScript classes implemented in Rust\n\nA class is a `b.class({..})` exported from a `*.bind.ts` file and a Rust struct. `src/codegen/bindgen.ts` generates the C++\ncell, prototype and constructor, the argument conversions, and the Rust functions that call the struct's methods.\n`docs/project/bindgen.mdx` is the reference: read its \"Classes\" section before writing one.\n\n## Schema\n\n```typescript\nimport * as b from \"../../codegen/bindgen-lib.ts\";\n\nexport const Matcher = b.class({\n  rustPath: \"crate::api::matcher::Matcher\",\n  construct: { args: { pattern: b.string.utf8 } },\n  internalFields: [\"callback\"],\n  proto: {\n    match: { args: { text: b.string.utf8 }, returns: b.bool },\n    pattern: { getter: b.string.utf8, cache: true },\n  },\n});\n```\n\n## Rust\n\n```rust\npub struct Matcher {\n    pattern: Box<[u8]>,\n}\n\nimpl Matcher {\n    pub fn constructor(pattern: &[u8]) -> Self {\n        Self { pattern: pattern.into() }\n    }\n\n    pub fn r#match(&self, text: &[u8]) -> bool {\n        bun_core::strings::contains(text, &self.pattern)\n    }\n\n    pub fn get_pattern(&self) -> &[u8] {\n        &self.pattern\n    }\n}\n```\n\nA missing or mis-typed method is a compile error: the generated code calls it directly.\n\n## Where the struct lives\n\n- Freed when its JS object is freed: it is stored inside the object. This is the default. Cleanup is `Drop`.\n- Can outlive its object (a timer, another thread or a C library still points at it): `refCounted: true`. It is a separate,\n  refcounted heap allocation, and the object holds one ref.\n\n## What a body may do\n\n`capability: \"heap\"` adds `heap: &JsHeap<'a>` (allocate, throw). `capability: \"js\"` adds `cx: &mut JsScope<'a>` (also run\nJavaScript); `cx.global()` is the `&JSGlobalObject` the rest of the tree takes. `throws: true` makes the result a\n`JsResult<T>`. `passThis: true` adds the object, `this_value: JsWrapper<'a, Self>`.\n\nEvery member takes `&self`; state that changes is in `Cell` or `JsCell`.\n\n## Holding JS values\n\nNever store a raw `JSValue` in a struct field. Declare an internal field (`internalFields: [\"callback\"]` or a `cache: true`\ngetter) and use `js_Matcher::callback_set_cached(this_value, global, value)` / `callback_get_cached(this_value)` from\n`crate::generated_bindgen::<file>`. To reach its own object the struct stores a `JsRef` in the field that `thisValue` names.\n\n## Reference implementations\n\n- `src/jsc/bindgen_test.bind.ts` + `src/jsc/bindgen_test.rs`: an example of most keys\n- `src/jsc/resolve_message.bind.ts`: cached getters, `prototypeBase`, `construct: \"illegal\"`\n- `src/runtime/webcore/fetch/FetchSession.bind.ts`: `refCounted`, `finalize`\n", "skills/javascriptcore-garbage-collector/SKILL.md": "---\nname: javascriptcore-garbage-collector\ndescription: JSC GC reference for Bun. Use for use-after-free, JS object leaks, \"collected too early\", or when touching WriteBarrier, visitChildren, visitAdditionalChildren, JSRef, JSC::Strong/Weak, hasPendingActivity, ensureStillAlive, addOpaqueRoot, reportExtraMemoryAllocated, IsoSubspace, HeapAnalyzer, finalize.\n---\n\n# JavaScriptCore's Garbage Collector (Riptide)\n\nRiptide is **non-moving, generational, parallel, mostly-concurrent, conservative-on-the-stack**. Understanding those five words prevents most GC bugs in Bun.\n\n## The mental model\n\nThe heap is a graph. GC does a breadth-first search from **roots** → marks everything it reaches → everything unmarked is freed (lazily, on next allocation from that block). It does NOT compact or move objects — pointers stay stable for an object's lifetime.\n\n**Two collection modes:**\n\n- **Eden GC**: only scans newly-allocated objects + remembered set. Fast, frequent.\n- **Full GC**: scans everything. Slower, rarer.\n\n**It runs concurrently.** Marking happens on background threads _while JS is executing_; the mutator only stops at brief safepoints. `visitChildren` runs **off the main thread, racing with your code**.\n\n## How the VM gathers roots\n\nRoots are not a hardcoded list — they are **marking constraints** registered with `Heap::addMarkingConstraint()` and run to fixpoint. The built-in set lives in `Heap::addCoreConstraints()` (`vendor/WebKit/Source/JavaScriptCore/heap/Heap.cpp:2970`):\n\n| Tag   | Name              | What it marks                                                                                                                                                           |\n| ----- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `Cs`  | Conservative Scan | Native stack + registers of every JS thread, scanned word-by-word (`gatherStackRoots` → `ConservativeRoots`). Also JIT stub routines. World is stopped for this.        |\n| `Msr` | Misc Small Roots  | `vm.smallStrings`, `m_protectedValues` (`JSValueProtect`/`gcProtect`), `MarkedArgumentBuffer` lists, `vm.exception()` / `lastException()` / `m_terminationException`    |\n| `Sh`  | Strong Handles    | `m_handleSet.visitStrongHandles()` — every `JSC::Strong<T>`. Also `vm().visitAggregate()` (atom string tables etc.)                                                     |\n| `D`   | Debugger          | Sampling profiler, type profiler, ShadowChicken                                                                                                                         |\n| `Ws`  | Weak Sets         | Iterates every `WeakBlock`; calls `WeakHandleOwner::isReachableFromOpaqueRoots()` to decide whether a weak ref should _become_ strong this cycle                        |\n| `O`   | Output            | Calls `visitOutputConstraints()` on already-marked cells in output-constraint subspaces (executables, WeakMaps). This is the \"re-run after marking discovers more\" hook |\n| `Jw`  | JIT Worklist      | CodeBlocks queued for compilation                                                                                                                                       |\n| `Cb`  | CodeBlocks        | Executing/compiling CodeBlocks                                                                                                                                          |\n\nBun registers an additional constraint, `DOMGCOutputConstraint` (`src/jsc/bindings/BunGCOutputConstraint.cpp`), which calls `visitOutputConstraints` on every marked cell in Bun's output-constraint subspaces (event targets, generated classes with `visitAdditionalChildren`, etc.).\n\n**Constraint volatility** controls when they re-run during the fixpoint:\n\n- `GreyedByExecution` — may produce new grey cells whenever the mutator runs (re-run after every resume)\n- `GreyedByMarking` — may produce new grey cells when _other_ marking happens (re-run after each drain)\n- `SeldomGreyed` — usually doesn't add anything; run last\n\n## Object layout: the 8-byte JSCell header\n\nEvery GC-managed object inherits `JSCell` (`runtime/JSCell.h`):\n\n```\n| StructureID (4) | indexingTypeAndMisc (1) | JSType (1) | flags (1) | cellState (1) |\n```\n\n- `StructureID` — compressed hidden-class pointer\n- `indexingTypeAndMisc` — 2 bits are an embedded `WTF::Lock` (the **cell lock**); always CAS this byte\n- `cellState` — inlined GC color, used by the write barrier\n\nOut-of-line, in the `MarkedBlock` footer (or `PreciseAllocation` header for objects >~8KB):\n\n- `isMarked` bit — survived last GC\n- `isNewlyAllocated` bit — allocated since last GC\n\nLiveness = `isMarked || isNewlyAllocated` (with logical-versioning so blocks aren't swept eagerly).\n\n## CellState and the write barrier\n\n`vendor/WebKit/Source/JavaScriptCore/heap/CellState.h`:\n\n```cpp\nPossiblyBlack   = 0   // visited (or old-space-pending-rescan during full GC)\nDefinitelyWhite = 1   // new / unmarked\nPossiblyGrey    = 2   // on the mark stack\n```\n\nGenerational + concurrent GC share **one** retreating-wavefront barrier:\n\n```cpp\n// After: obj->field = newValue\nif (obj->cellState <= blackThreshold)   // 0 normally, bumped while GC is marking\n    writeBarrierSlowPath(obj);          // → put obj on remembered set / revisit\n```\n\n**You almost never write this by hand.** Use `WriteBarrier<T>` as the field type and call `.set(vm, owner, value)` — it stores then barriers. A raw `JSCell*` / `JSValue` member without a `WriteBarrier` wrapper is a bug: eden GC will free the target out from under you.\n\n`LazyProperty<Owner, T>`, `LazyClassStructure`, and `WriteBarrierStructureID` are barrier-aware variants for lazily-initialized fields and structures.\n\n## Allocation: where objects live\n\n`bmalloc/libpas` provides pages; JSC carves them up:\n\n- **`MarkedBlock`** — 16KB block, fixed cell size (segregated free list). Footer holds bitvectors. 16-byte minimum cell alignment. `addr & ~(16KB-1)` → block, so liveness checks are O(1).\n- **`PreciseAllocation`** — large objects (>~8KB), individually `malloc`'d, 96-byte GC header. Always returns addresses with `addr % 16 == 8` so `ptr & 8` distinguishes them from MarkedBlock cells.\n- **`CompleteSubspace`** — size-segregated set of `BlockDirectory`s for general JS objects.\n- **`IsoSubspace`** — one subspace per C++ type (security: a freed cell can only be reused for the _same_ type, defeating type-confusion UAF). **Every Bun class with native fields needs its own IsoSubspace** — `subspaceFor<T>` in the header, slot in `BunClientData`/`DOMIsoSubspaces`.\n\n**Allocation may trigger GC.** A safepoint exists at every allocation. Never assume \"I just allocated X, so Y from before is still alive\" unless Y is rooted.\n\n## Conservative stack scanning — what it does and doesn't guarantee\n\n`vendor/WebKit/Source/JavaScriptCore/heap/ConservativeRoots.cpp` walks the native stack/registers word-by-word (after `MachineThreads::tryCopyOtherThreadStacks` snapshots them). Any aligned word inside a live `MarkedBlock` cell or `PreciseAllocation` is a root.\n\n**This means:** a `JSCell*` / `JSValue` in a C++/Rust local variable _usually_ keeps the object alive — no `Handle`/`Local` ceremony like V8.\n\n**This does NOT mean you're always safe.** The compiler may dead-store-eliminate the local after its last visible use, or never spill it. If you extract an interior pointer (`string->characters8()`, butterfly storage, typed-array `vector()`) and then call something that can allocate, the original cell may no longer be on the stack:\n\n```cpp\nJSC::EnsureStillAliveScope keepAlive(cell);   // RAII: forces cell onto stack until scope end\n// ... use interior pointer, call things that allocate ...\n```\n\nor `ensureStillAliveHere(cell)`. In Rust: `value.ensure_still_alive()`.\n\n## `visitChildren` — the per-cell tracing hook\n\n```cpp\n// In header:\nDECLARE_VISIT_CHILDREN;\nWriteBarrier<JSObject> m_callback;\nWriteBarrier<Unknown>  m_cachedValue;\n\n// In .cpp:\ntemplate<typename Visitor>\nvoid JSFoo::visitChildrenImpl(JSCell* cell, Visitor& visitor) {\n    auto* thisObject = jsCast<JSFoo*>(cell);\n    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n    Base::visitChildren(thisObject, visitor);   // ALWAYS call base first\n\n    visitor.append(thisObject->m_callback);\n    visitor.append(thisObject->m_cachedValue);\n}\nDEFINE_VISIT_CHILDREN(JSFoo);\n```\n\n**Rules — runs concurrently on a GC thread:**\n\n- No allocation. No `toJS`, no `jsString`, nothing that touches `vm.heap`.\n- No `ref()`/`deref()` of `RefCounted` (not thread-safe).\n- No locks the main thread might also take while allocating (deadlock).\n- If a field can be torn by a racing mutator, take `Locker locker { thisObject->cellLock() }` in both `visitChildren` and the mutating site.\n- Forgetting to `append()` a `WriteBarrier` field → use-after-free, often eden-GC-only, often only under load.\n\n## `visitAdditionalChildren` and output constraints\n\n`visitChildren` only sees the cell's own fields. When a JS wrapper's liveness should propagate to **other JS objects reachable through native state** (event listeners, observers, the JS values held inside a wrapped C++ object), Bun uses the WebCore pattern:\n\n```cpp\n// Custom hook called from BOTH places:\ntemplate<typename Visitor>\nvoid JSFoo::visitAdditionalChildren(Visitor& visitor) {\n    wrapped().listeners().visitJSEventListeners(visitor);\n    visitor.addOpaqueRoot(&wrapped());\n}\n\n// 1) From visitChildren (normal marking):\nDEFINE_VISIT_CHILDREN_WITH_MODIFIER(..., JSFoo) {\n    ...\n    thisObject->visitAdditionalChildren(visitor);\n}\n\n// 2) From visitOutputConstraints (constraint fixpoint re-scan):\ntemplate<typename Visitor>\nvoid JSFoo::visitOutputConstraints(JSCell* cell, Visitor& visitor) {\n    auto* thisObject = jsCast<JSFoo*>(cell);\n    Base::visitOutputConstraints(thisObject, visitor);\n    thisObject->visitAdditionalChildren(visitor);\n}\n```\n\nDOM wrappers get both entry points from `JSDOMInterfaceWithAdditionalChildren` (`src/jsc/bindings/webcore/JSDOMInterface.h`) and only define `visitAdditionalChildrenInGCThread`.\n\n**Why two entry points?** `visitChildren` runs once when the cell turns grey. But marking may later discover that some _other_ native object (an opaque root) is live, which retroactively makes more of _this_ cell's references live. `visitOutputConstraints` is re-invoked by `DOMGCOutputConstraint` during the constraint fixpoint to catch that.\n\nTo make a class participate, its IsoSubspace must be registered as an **output-constraint subspace** (`clientSubspaceFor*` with `outputConstraint` in `BunClientData`).\n\n## Opaque roots — liveness through non-JSCell pointers\n\nWhen native objects form a graph that should keep wrappers alive:\n\n```cpp\n// In some wrapper's visitAdditionalChildren:\nvisitor.addOpaqueRoot(nativePtr);          // \"nativePtr is reachable\"\n\n// Elsewhere, deciding whether ANOTHER wrapper survives:\nbool JSBarOwner::isReachableFromOpaqueRoots(Handle<Unknown> h, void* ctx,\n                                            AbstractSlotVisitor& v, ASCIILiteral* reason) {\n    auto* bar = static_cast<Bar*>(ctx);\n    if (UNLIKELY(reason)) *reason = \"Bar is in document tree\"_s;\n    return v.containsOpaqueRoot(bar->ownerNode());\n}\n```\n\nFor DOM wrappers the owner is `JSDOMWrapperOwner<JSBar>` (`src/jsc/bindings/JSDOMWrapperCache.h`), which keeps an `ActiveDOMObject` with pending activity alive and then asks `JSBar::isReachableFromOpaqueRoots(visitor, reason)`.\n\nThe opaque-root set is just a `HashSet<void*>` rebuilt each cycle. It's how DOM trees stay alive as a unit.\n\n## `JSC::Weak<T>`, `WeakImpl`, `WeakBlock`, `WeakHandleOwner`\n\n`JSC::Weak<T>` (`vendor/WebKit/Source/JavaScriptCore/heap/Weak.h`) is the GC-aware weak pointer. It does **not** keep its target alive; `.get()` returns `nullptr` after the target is collected.\n\nUnder the hood:\n\n- Each `Weak<T>` owns a `WeakImpl*` (`vendor/WebKit/Source/JavaScriptCore/heap/WeakImpl.h`): `{ JSValue, WeakHandleOwner* (low bits = state), void* context }`. State is `Live → Dead → Finalized → Deallocated`.\n- `WeakImpl`s are slab-allocated in 1KB **`WeakBlock`s** (`vendor/WebKit/Source/JavaScriptCore/heap/WeakBlock.h`, `blockSize = 1024`). Every `MarkedBlock` and `PreciseAllocation` has a `WeakSet` — a linked list of `WeakBlock`s for cells in that container.\n- During the `Ws` constraint, each `WeakBlock::visit()` walks its `WeakImpl`s; for each one whose target is **not yet marked**, it calls `WeakHandleOwner::isReachableFromOpaqueRoots(handle, context, visitor, &reason)`. Return `true` → the target is marked (the weak ref is \"upgraded\" this cycle). This is how `hasPendingActivity()` and opaque-root reachability keep wrappers alive even when nothing strongly references them.\n- After marking, `WeakBlock::reap()` flips unmarked `Live` impls to `Dead`. `WeakBlock::sweep()` later runs `WeakHandleOwner::finalize(handle, context)` on each `Dead` impl, then frees the slot. **`finalize` runs on the mutator thread but the cell is already dead — do not touch its JS fields.** Typical use: drop the wrapper from a native→JS wrapper cache.\n\n```cpp\nstruct MyOwner final : public JSC::WeakHandleOwner {\n    bool isReachableFromOpaqueRoots(Handle<Unknown>, void* ctx,\n                                    AbstractSlotVisitor& v, ASCIILiteral*) override {\n        return static_cast<NativeThing*>(ctx)->hasPendingActivity();\n    }\n    void finalize(Handle<Unknown>, void* ctx) override {\n        static_cast<NativeThing*>(ctx)->m_wrapper = nullptr;\n    }\n};\nJSC::Weak<JSFoo> m_wrapper { jsFoo, &myOwnerSingleton, nativeThing };\n```\n\n`Weak<T>` is **move-only** (allocates a `WeakImpl`). Don't put it in a hot path; cache it.\n\n## `JSRef` — the native↔wrapper reference pattern\n\nWhen a native object needs to hold a reference back to its own JS wrapper, **use `JSRef`** (`src/jsc/JSRef.rs`), not `gcProtect`, not a raw `JSValue` field, and usually not `Strong` directly.\n\n`JSRef` is a tagged union with three states:\n\n- `Weak` — a bare `JSValue`. Does **not** keep the wrapper alive. Valid only because the wrapper's generated finalizer will flip this to `Finalized` before the cell is freed, so `try_get()` returns `None` instead of a dangling pointer. (This is _not_ a `JSC::Weak`; it's cheaper — no `WeakImpl` allocation.)\n- `Strong` — wraps `bun_jsc::Strong` (a `JSC::Strong<Unknown>` root). Keeps the wrapper alive.\n- `Finalized` — terminal; `try_get()` returns `None`.\n\nPattern: **strong while busy, weak while idle.**\n\n```rust\nthis_value: JsCell<JsRef>, // `thisValue: \"this_value\"` in the `.bind.ts` file; initialized with JsRef::empty()\n\n// On construction:\njs_wrapper.set_js_ref_strong(global);             // or set_js_ref_weak() if it starts idle\n\n// When the last in-flight operation completes:\nself.this_value.with_mut(|r| r.downgrade());      // Strong -> Weak, GC may now collect\n\n// When work starts again:\nself.this_value.with_mut(|r| r.upgrade(global));  // Weak -> Strong\n\n// In any callback that needs the wrapper (`JsCellRefExt`):\nlet Some(js_this) = self.this_value.try_get() else { return };\n```\n\nSee `ServerWebSocket`, `UDPSocket`, `MySQLConnection` for real examples.\n\n**`JSRef` requires `thisValue`.** The `Weak` state is only sound because it is flipped to `Finalized` before the cell is reused. The class names the field with `thisValue` in its `.bind.ts` file, which generates that step and the only functions that can fill the field.\n\n## `gcProtect` / `JSValueProtect` — almost never\n\n`gcProtect()` / `JSValueProtect()` push into `Heap::m_protectedValues` (a ref-counted root map, visited by the `Msr` constraint). It's the legacy C-API mechanism. **Avoid it in Bun:**\n\n- It's a raw global root with manual unprotect — easy to leak.\n- It has no owner, so heap snapshots can't attribute the retention.\n- `bun_jsc::Strong` / `JSRef` give the same guarantee with RAII and a destructor.\n\nThe only legitimate uses are inside the JSC C API shims themselves, or one-off debugging.\n\n## Extra-memory reporting — `reportExtraMemoryAllocated` / `reportExtraMemoryVisited`\n\nThe GC schedules itself by bytes-allocated-since-last-GC. It only sees JSCell allocations, so a 32-byte wrapper around a 50MB native buffer looks like 32 bytes → GC never triggers → OOM.\n\n**Contract — both halves are required:**\n\n```cpp\n// 1) When the native memory is allocated (or the wrapper takes ownership):\nvm.heap.reportExtraMemoryAllocated(ownerCell, byteCount);\n\n// 2) In visitChildren, every time the cell is visited:\nvisitor.reportExtraMemoryVisited(thisObject->wrapped().byteSize());\n```\n\n- `reportExtraMemoryAllocated` adds to the \"since last GC\" counter and may **immediately trigger a GC** (it's a safepoint). Call it _after_ the cell is fully constructed.\n- `reportExtraMemoryVisited` adds to the \"live bytes after this GC\" counter, which sets the next trigger threshold. **If you forget this half**, the heap's high-water mark drifts down each cycle and you get back-to-back full GCs (the \"GC death spiral\").\n- If the size changes over time, report the delta on growth (`reportExtraMemoryAllocated(cell, newSize - oldSize)`) and report the current size in `visitChildren`.\n- `deprecatedReportExtraMemory` exists for callers that can't satisfy the visit-side half — avoid it.\n\nIn a `.bind.ts` class, `estimatedSize: true` generates both sides; you implement `estimated_size()` in Rust, which marking threads call. For growth after the object is created you still call `vm.report_extra_memory`.\n\n## `HeapAnalyzer` — heap snapshots and labelling\n\n`vendor/WebKit/Source/JavaScriptCore/heap/HeapAnalyzer.h` is the abstract visitor used to build heap snapshots (Web Inspector \"Heap Snapshot\", and Bun's V8-compatible `BunV8HeapSnapshotBuilder`). When a snapshot is requested, marking runs with an analyzer attached and each cell's `analyzeHeap` static is called:\n\n```cpp\nvoid JSFoo::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) {\n    auto* thisObject = jsCast<JSFoo*>(cell);\n    Base::analyzeHeap(cell, analyzer);\n    analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped());\n    analyzer.setLabelForCell(cell, thisObject->wrapped().url().string());\n    if (auto* child = thisObject->m_callback.get())\n        analyzer.analyzePropertyNameEdge(cell, child, vm.propertyNames->callback.impl());\n}\n```\n\nAPI (`HeapAnalyzer`):\n\n- `analyzeNode(cell)` — record a node\n- `analyzeEdge(from, to, RootMarkReason)` / `analyzePropertyNameEdge` / `analyzeVariableNameEdge` / `analyzeIndexEdge` — record a labelled edge\n- `setWrappedObjectForCell(cell, void*)` — link wrapper → native pointer\n- `setLabelForCell(cell, String)` — human-readable name in the snapshot\n- `setOpaqueRootReachabilityReasonForCell` — why a weakly-held wrapper survived\n\nIf your class shows up as an opaque blob in heap snapshots, implement `analyzeHeap`.\n\n## How to keep things alive (decision table)\n\n| Scenario                                                            | Mechanism                                                                                                                                            |\n| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |\n| JSCell field pointing to another JSCell                             | `WriteBarrier<T>` member + `visitor.append(m_field)` in `visitChildren`                                                                              |\n| Native state inside the wrapped C++ object holds JS values          | `visitAdditionalChildren` + register subspace as output-constraint                                                                                   |\n| C++/Rust local across allocation/call                               | Conservative scan (free) — add `EnsureStillAliveScope` / `value.ensure_still_alive()` if extracting interior pointers or seeing release-only crashes |\n| Native object holds its own JS wrapper (class has `thisValue`)      | **`JSRef`** — `upgrade()` when work starts, `downgrade()` when idle. **This is the default.**                                                        |\n| Native object owns an arbitrary JS value (callback, options object) | `bun_jsc::Strong` — drop in `finalize()`. Watch for cycles                                                                                           |\n| C++ non-GC object owns a JS value as a root                         | `JSC::Strong<T>`. **Danger:** cycle if the JS value can reach back → leak                                                                            |\n| Weak ref with resurrection predicate / finalize callback (C++)      | `JSC::Weak<T>` + `WeakHandleOwner`                                                                                                                   |\n| Group of wrappers share lifetime via a native graph                 | `visitor.addOpaqueRoot(ptr)` + `containsOpaqueRoot(ptr)`                                                                                             |\n| Temporarily forbid GC in a critical section                         | `DeferGC deferGC(vm)` — defers until scope exit. Never hold across user JS                                                                           |\n| Tell GC about off-heap memory you own                               | `reportExtraMemoryAllocated` on alloc **and** `reportExtraMemoryVisited` in `visitChildren`                                                          |\n| ~~Mark a value as root from C API~~                                 | ~~`gcProtect` / `JSValueProtect`~~ — **avoid**; use `bun_jsc::Strong` / `JSRef` instead                                                              |\n\n## Destruction & finalizers\n\n- `static constexpr bool needsDestruction = true` → C++ destructor runs when the cell is swept. Sweep is **lazy** (next allocation from that block, or `IncrementalSweeper`), so destruction is delayed arbitrarily. Do not rely on it for prompt resource release — expose explicit `close()`/`dispose()`.\n- In a `.bind.ts` class, `Drop` of the struct, or `finalize: true` → `fn finalize(&self)` of a `refCounted` one, runs from `destroy`. Same laziness applies.\n- `WeakHandleOwner::finalize` runs earlier (at weak-reap time) but the cell is already dead; only use it to clear caches.\n- Destructors run on the mutator thread but **other JS objects may already be swept** — do not dereference `WriteBarrier` fields in a destructor.\n\n## Debugging GC issues\n\n```bash\n# Force synchronous, frequent GC — turns rare races into immediate crashes\nBUN_JSC_collectContinuously=1 BUN_JSC_useConcurrentGC=0 bun-debug test.js\n\n# Zero free cells so UAF reads are obvious\nBUN_JSC_scribbleFreeCells=1\n\n# Validate the GC's own bookkeeping\nBUN_JSC_verifyGC=1 BUN_JSC_verboseVerifyGC=1\n\n# See what's being collected / heap growth\nBUN_JSC_logGC=2 BUN_JSC_showObjectStatistics=1\n\n# Force GC from JS\nBun.gc(true)      // sync full GC\nrequire('bun:jsc').heapStats()\n```\n\nIf a bug only reproduces with concurrent GC **on** → missing write barrier or `visitChildren` race.\nIf it only reproduces with `collectContinuously=1` → something isn't rooted across an allocation.\nIf memory grows but `heapStats().heapSize` doesn't → missing `reportExtraMemoryAllocated`.\nIf GC runs constantly with little garbage → missing `reportExtraMemoryVisited`.\n\n## Key source files\n\n- `vendor/WebKit/Source/JavaScriptCore/heap/Heap.cpp` — `collectImpl`, `addCoreConstraints` (root list)\n- `vendor/WebKit/Source/JavaScriptCore/heap/SlotVisitor.cpp` / `SlotVisitorInlines.h` — `drain()`, `append`, `addOpaqueRoot`, `reportExtraMemoryVisited`\n- `vendor/WebKit/Source/JavaScriptCore/heap/MarkedBlock.h`, `vendor/WebKit/Source/JavaScriptCore/heap/PreciseAllocation.h` — cell containers, `isLive`\n- `vendor/WebKit/Source/JavaScriptCore/heap/CellState.h`, `runtime/WriteBarrier.h`, `runtime/WriteBarrierInlines.h`\n- `vendor/WebKit/Source/JavaScriptCore/heap/ConservativeRoots.cpp`, `vendor/WebKit/Source/JavaScriptCore/heap/MachineStackMarker.cpp`\n- `vendor/WebKit/Source/JavaScriptCore/heap/Weak.h`, `vendor/WebKit/Source/JavaScriptCore/heap/WeakImpl.h`, `vendor/WebKit/Source/JavaScriptCore/heap/WeakBlock.h`, `vendor/WebKit/Source/JavaScriptCore/heap/WeakSet.h`, `vendor/WebKit/Source/JavaScriptCore/heap/WeakHandleOwner.h`\n- `vendor/WebKit/Source/JavaScriptCore/heap/HeapAnalyzer.h`, `vendor/WebKit/Source/JavaScriptCore/heap/HeapSnapshotBuilder.cpp`, Bun: `vendor/WebKit/Source/JavaScriptCore/heap/BunV8HeapSnapshotBuilder.cpp`\n- `vendor/WebKit/Source/JavaScriptCore/heap/DeferGC.h`, `vendor/WebKit/Source/JavaScriptCore/heap/Strong.h`, `vendor/WebKit/Source/JavaScriptCore/heap/HandleSet.h`\n- `runtime/JSCell.h` / `JSCellInlines.h` — header layout, `visitChildren` base\n- Bun: `src/jsc/bindings/BunGCOutputConstraint.cpp`, `Generated*.cpp` in the build's codegen directory (generated `visitChildren`)\n", "skills/rust-system-calls/SKILL.md": "---\nname: rust-system-calls\ndescription: Guides using bun_sys for system calls and file I/O in Rust. Use when implementing file operations, opening fds, or any syscall path instead of std::fs or libc.\n---\n\n# System Calls & File I/O in Rust\n\nUse `bun_sys` instead of `std::fs` or raw `libc` for cross-platform syscalls with proper error handling.\n\n## bun_sys::File (Preferred)\n\nFor most file operations, use the `bun_sys::File` wrapper. It owns the fd and closes on `Drop`.\n\n```rust\nuse bun_sys::{File, Fd, O};\n\nlet file = File::openat(Fd::cwd(), b\"path/to/file\", O::RDONLY, 0)?;\nlet mut buf = vec![0u8; 4096];\nlet n = file.read_all(&mut buf)?;     // loops until EOF or full\n// `file` closes on Drop.\n```\n\n### Complete Example\n\n```rust\nuse bun_sys::{File, Fd, O};\n\npub fn write_file(path: &[u8], data: &[u8]) -> Result<(), bun_sys::Error> {\n    let file = File::openat(Fd::cwd(), path, O::WRONLY | O::CREAT | O::TRUNC, 0o664)?;\n    file.write_all(data)?;\n    Ok(())\n}\n```\n\n## Why bun_sys?\n\n| Aspect      | bun_sys                            | std::fs / libc         |\n| ----------- | ---------------------------------- | ---------------------- |\n| Return Type | `Maybe<T>` with rich `Error`       | `io::Error` (lossy)    |\n| Windows     | Full support with libuv fallback   | Incomplete/POSIX-ish   |\n| Error Info  | errno, syscall tag, path, fd       | errno only             |\n| EINTR       | Automatic retry                    | Manual handling        |\n| Paths       | `&[u8]` (WTF-8 safe)               | `&Path` (UTF-8 lossy)  |\n\n## Error Handling with Maybe<T>\n\n`bun_sys` functions return `Maybe<T> = Result<T, bun_sys::Error>`. Propagate with `?`; convert to a JS exception via `bun_sys_jsc::ErrorJsc::to_js`:\n\n```rust\nuse bun_sys_jsc::ErrorJsc;\nuse bun_sys::{File, Fd, O};\n\nlet file = match File::openat(Fd::cwd(), path, O::RDONLY, 0) {\n    Ok(f) => f,\n    Err(err) => return Ok(err.to_js(global)?),\n};\n```\n\n`bun_sys::Error` carries `errno`, `syscall: Tag`, and `path: Box<[u8]>`. To branch on errno:\n\n```rust\nmatch bun_sys::unlink(path) {\n    Ok(()) => {}\n    Err(e) if e.errno() == bun_c::ENOENT => {} // already gone\n    Err(e) => return Err(e),\n}\n```\n\n## Key Types and Functions\n\n- `Fd` (`bun_core::Fd`) — cross-platform file descriptor. `Fd::cwd()`, `Fd::stdin()/stdout()/stderr()`, `fd.close()`.\n- `File::open(path: &ZStr, flags, mode)` / `File::openat(dir: Fd, path: &[u8], flags, mode)` / `File::make_open(...)` (creates parent dirs) / `File::create(dir, path, truncate)`\n- `file.read(buf)` / `read_all(buf)` / `read_to_end()` / `read_to_end_small()` / `write(buf)` / `write_all(buf)`\n- `bun_sys::open`, `read`, `write`, `pread`, `pwrite`, `stat`, `fstat`, `lstat`, `mkdir`, `unlink`, `rename`, `symlink`, `chmod` — free fns over `Fd`\n- `bun_sys::read_buf(fd, cursor)` / `file.read_all_buf(cursor)` / `pread_all_buf(cursor, offset)` — fill uninitialized memory through a `BorrowedCursor`; `bun_core::vec::append_with` lends one over the spare capacity of a `Vec`\n- Open flags: `bun_sys::O::RDONLY`, `O::WRONLY | O::CREAT | O::TRUNC`, etc.\n\n## Path Buffers\n\nBuild paths with `bun_paths::Path`. It is NUL-terminated and grows on the heap, which avoids 96 KB stack allocations on Windows:\n\n```rust\nuse bun_paths::Path;\n\nlet path = Path::from_parts(&[dir, name]);\nlet file = File::open(&path, O::RDONLY, 0)?;\n```\n\n## Common Mistakes\n\n- **Don't `.unwrap()`** a `bun_sys` result that user input or the OS can cause to fail at runtime — return the error.\n- **Don't use `std::fs::File`** — it loses the syscall tag and path needed for Node-compatible error objects.\n- **Don't allocate `PathBuffer` on the stack** in hot paths — use `path_buffer_pool::get()`.\n- **Don't forget `Drop`** alone closes a `File` — never `file.fd().close()` while the `File` is still live (double close).\n\nSee `src/CLAUDE.md` for the full `bun_core`/`bun_sys` reference.\n", "skills/slowest-tests/SKILL.md": "---\nname: slowest-tests\ndescription: Find the top-N slowest test files in CI from a recent BuildKite run, optionally posting the results to a Slack channel as a formatted table. Use when asked to find slow CI tests, \"what's making CI slow\", or to post a slow-test report to Slack.\n---\n\n# Slowest CI tests\n\nArgs: `[N] [#channel]` — both optional. `N` defaults to 500. If `#channel` is omitted, just print the table and stop.\n\n## 1. Gather the data\n\nRun the script. With no build number it auto-picks the most recent finished build from a merged PR.\n\n```bash\nbun run ci:slowest                 # top 500 from a recent merged-PR build → TSV on stdout\nbun run ci:slowest 47324 100       # specific build, top 100\nbun run ci:slowest --json > /tmp/slow.json\n```\n\nThe script (`scripts/ci-slowest-tests.ts`) does the heavy lifting:\n\n- Lists `test-bun` jobs from `bk build view <N>`, skipping `retried: true`.\n- Fetches each job's `raw_log_url` directly with `Authorization: Bearer $BUILDKITE_TOKEN`. **Do not use `bk job log` — it hangs indefinitely on some Windows/alpine jobs.**\n- Caches logs to `$TMPDIR/bun-ci-logs-<build>/` so re-runs are instant.\n- Parses `_bk;t=<ms> ... --- [N/TOTAL] <file>` group headers, normalising backslashes to `/` and stripping `[attempt #N]` retries.\n- Aggregates each file's duration as the **max across all platforms** (a file appears once per platform; shards within a platform are disjoint).\n- Drops `package.json` / non-JS entries — those are setup steps, not tests.\n\nIf the script can't find a build automatically (rare — it walks the last 10 merged PRs), pick one yourself: `gh pr list --state merged --limit 10 --json number,headRefName`, then `bk build list --branch <headRefName>` and pass the first build with a `finished_at`. Merged-PR builds usually report `state: failed` because of flaky tests — that's fine, the timing data is still valid.\n\n## 2. Post to Slack (only if a channel was given)\n\n**`slack_send_message` does NOT support markdown tables** — its markdown→blocks converter rejects `| a | b |` syntax with `invalid_blocks`. Don't use Canvases either; they render tables but the MCP proxy 502s above ~10 KB and the result is clunky.\n\nProcedure:\n\n1. Look up the channel ID with `slack_search_channels` (the user gives a name, you need the `C…` ID).\n2. Write the full N-row markdown table to `~/code/tmp/top<N>-slow-tests.md`, then upload it as a **secret gist**: `gh gist create <file> --desc \"Bun CI: top N slowest test files (build #<num>)\"`. (The Slack MCP has no file-upload tool; secret gist is the agreed fallback. Do **not** ask the user to attach anything manually.)\n3. Post the **main** message: header (build link + gist link, \"Rest in thread.\") followed by the **top 20** bullets. Row format:\n\n   ```\n   • 325s `test/js/bun/cron/in-process-cron.test.ts` 🐧 x64-baseline\n   • 96s  `test/js/bun/http/serve-body-leak.test.ts` 🐧 x64-asan\n   ```\n\n   - seconds: plain text, left-aligned, padded so the backticks line up\n   - filepath: code-font, **full path including `test/` prefix and extension** — do not strip anything\n   - platform: standard Unicode emoji only (🐧 linux, 🪟 windows, 🍎 macOS — never workspace-custom shortcodes) followed by the arch/variant **verbatim** from the job name (`x64-asan`, `aarch64`, `x64-baseline` — do not abbreviate)\n\n4. Reply in-thread (`thread_ts` = the main message) with rows 21–N in the same bullet format, packed into chunks under 4800 chars each (~70 rows per chunk). Post chunks sequentially so they stay ordered.\n", "skills/upgrade-boringssl/SKILL.md": "---\nname: upgrade-boringssl\ndescription: Upgrade Bun's BoringSSL fork (oven-sh/boringssl) to the latest upstream\n  google/boringssl\n---\n\nBun pins BoringSSL by **commit SHA** in `scripts/build/deps/boringssl.ts` (`BORINGSSL_COMMIT`). The build downloads a tarball from `oven-sh/boringssl` at that SHA — there is no submodule and `vendor/boringssl/` is git-ignored.\n\nThe fork carries a small patch set on top of upstream (see \"Preserved patches\" below). Upgrading means: merge `google/boringssl` into `oven-sh/boringssl@master`, push, then bump the SHA + regenerate source lists in Bun.\n\n## Steps\n\n### 1. Clone the fork and merge upstream\n\n```sh\ngit clone https://github.com/oven-sh/boringssl.git /tmp/boringssl\ncd /tmp/boringssl\ngit remote add upstream https://github.com/google/boringssl.git\ngit fetch upstream\ngit log --oneline $(git merge-base HEAD upstream/main)..HEAD   # our patches\ngit merge upstream/main\n```\n\nResolve conflicts **preserving the fork's additions**. Most conflicts are upstream's periodic `|...|` → `` `...` `` doc-comment restyle landing adjacent to a line we added — keep our line + upstream's comment style. For `include/openssl/nid.h`, keep upstream's new NIDs **and** ours (our NID numbers are from OpenSSL's range and don't collide with BoringSSL's sequential allocation).\n\n### 2. Verify the merged tree builds\n\n```sh\ncmake -B build -GNinja -DCMAKE_BUILD_TYPE=Release\nninja -C build crypto_test ssl_test decrepit_test\nbuild/crypto_test && build/ssl_test && build/decrepit_test\n```\n\nThis catches mis-resolved conflicts before they reach Bun's CI.\n\n### 3. Push to the fork\n\nThe default branch is **`master`** (not `main`).\n\n```sh\ngit push origin HEAD:master\nNEW_SHA=$(git rev-parse HEAD)\n```\n\n### 4. Bump Bun\n\nIn the bun repo:\n\n- `scripts/build/deps/boringssl.ts` — set `BORINGSSL_COMMIT` to `$NEW_SHA`.\n- `src/js/node/tls.ts` — three hand-maintained mirrors of BoringSSL tables must be re-derived from the new pin (a test pins the current set, but cannot see upstream additions on its own): `SUPPORTED_ECDH_GROUPS` ← `ssl/ssl_key_share.cc` `kNamedGroups` (every `name` and non-empty `alias`), `_VALID_CIPHERS_SET` ← `ssl/ssl_cipher.cc` `kCiphers`, `CIPHER_LIST_SELECTORS` ← `ssl/ssl_cipher.cc` `kCipherAliases`.\n- Regenerate the source lists (the file's header comment has the exact one-liner). Only `gen/sources.json` is authoritative — diff old vs new and apply the delta:\n\n  ```sh\n  rm -rf vendor/boringssl   # force re-fetch on next build\n  bun bd --target=clone-boringssl\n  bun -e 'const j=require(\"./vendor/boringssl/gen/sources.json\");\n          const f=l=>l.map(JSON.stringify).join(\", \");\n          for(const k of [\"bcm\",\"crypto\",\"ssl\",\"decrepit\"]) console.log(k,\"\\n\",f(j[k].srcs));\n          console.log(\"asm\\n\",f([...j.bcm.asm,...j.crypto.asm]));\n          console.log(\"nasm\\n\",f([...j.bcm.nasm,...j.crypto.nasm]))'\n  ```\n\n### 5. Build and test locally\n\n```sh\nrm -rf vendor/boringssl\nbun bd -p 'require(\"crypto\").createHash(\"sha3-256\").update(\"hi\").digest(\"hex\")'\nbun bd test test/js/node/crypto/ test/js/bun/crypto/\nbun bd test test/js/node/tls/ test/js/web/fetch/fetch.tls.test.ts\n```\n\n### 6. Open the Bun PR\n\n```sh\ngit checkout -b claude/boringssl-<upstream-short-sha>\ngit commit -am \"deps: upgrade BoringSSL to <upstream-short-sha>\"\ngit push -u origin HEAD\ngh pr create\n```\n\nThen `bun run ci:watch` and fix anything that turns up.\n\n## Preserved patches (what conflicts to expect)\n\n`git diff $(git merge-base HEAD upstream/main)..HEAD --stat` — currently ~55 files, ~2100 insertions:\n\n- **SHA-512/224** — `crypto/fipsmodule/sha/sha512.cc.inc`, `crypto/sha/sha512.cc`, `include/openssl/{sha2,nid,digest}.h`\n- **SHA3-224, and NIDs + name lookup for upstream's SHA3-256/384/512 `EVP_MD`s** — `crypto/evp/p_keccak.cc`, `crypto/digest/digest_extra.cc`, `crypto/fipsmodule/keccak/*`, `include/openssl/{digest,nid}.h`\n- **HMAC-SHA3** — `crypto/hmac/hmac_test*.{cc,txt}`\n- **BLAKE2b-512** — `crypto/blake2/blake2.cc`, `include/openssl/blake2.h`\n- **RIPEMD160 in `crypto/` (not `decrepit/`) + `EVP_ripemd160` lookup** — `crypto/ripemd/ripemd.cc` (moved), `crypto/digest/digest_extra.cc`, `include/openssl/digest.h`, `gen/sources.*`, `build.json`\n- **`EVP_PBE_validate_scrypt_params`** — `crypto/evp/scrypt.cc`, `include/openssl/evp.h`\n- **Electron `SSL_want` / `EVP_CIPHER_do_all_sorted`** — `ssl/ssl_lib.cc` (return `rwstate` directly), `ssl/ssl_test.cc` (drops the corresponding test block), `decrepit/evp/evp_do_all.cc`, `crypto/cipher/get_cipher.cc`, `include/openssl/cipher.h`\n- **MLDSA stack-frame pragma** — `crypto/fipsmodule/mldsa/mldsa.cc.inc`\n- **PKCS#1 v1.5 signature prefixes for the digests above** — `crypto/fipsmodule/rsa/rsa.cc.inc` (`kPKCS1SigPrefixes` rows for SHA-512/224, SHA-512/256, SHA3-\\* and RIPEMD-160), `crypto/rsa/rsa_test.cc`\n- **`BORINGSSL_REQUIRE_MEMORY_HOOKS` / `OPENSSL_system_*`** — `crypto/{mem.cc,internal.h,err/err.cc,thread_*.cc}`, `ssl/ssl_buffer.cc`\n- **`BORINGSSL_PEM_FAST_PUBLIC_BASE64`** — `crypto/pem/pem_lib.cc`, `include/openssl/pem.h`\n- **`X509_LAZY_CERT_SET`, `X509_V_FLAG_IGNORE_EXPIRED_TRUST_ANCHORS`** — `crypto/x509/{x509_lu,x509_vfy,x_name}.cc`, `include/openssl/x509.h`\n- **`X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE`** (upstream no longer reports it; Node does) — `check_lone_untrusted_leaf` in `crypto/x509/x509_vfy.cc`\n- **OpenSSL's verdicts in the path builder** (attribute-certificate CRLs, revocation of trust anchors, partial chains, `keyUsage`-only anchors, auto-chaining) — `crypto/x509/{x509_vfy,v3_purp}.cc`, `ssl/ssl_x509.cc`\n\nIf upstream upstreams any of these (check `git grep` on `upstream/main` before re-applying), drop the fork's copy.\n\n## Things that have broken before\n\n- **`SSL_CTX` / `SSL_ECH_KEYS` / `SSL_CREDENTIAL` made opaque** — Bun's Rust FFI (`src/boringssl_sys/boringssl.rs`) treats them as opaque already, so this is fine, but check `packages/bun-usockets/src/crypto/openssl.cpp` for any direct field access.\n- **`BIO_read`/`BIO_write` error-value narrowing** — can change `SSL_read` error paths over memory BIOs (`SSLWrapper` for TLS-over-duplex). If `node-tls-connect.test.ts` crashes in `flush_pending_events`, see `src/runtime/socket/UpgradedDuplex.rs::teardown` and `WindowsNamedPipe.rs`'s `WRAPPER_BUSY` for the re-entrant-drop guard.\n- **Per-handshake allocation churn (PQ key shares)** grows under ASAN quarantine; RSS-delta tests like `tls-connect-socket-churn.test.ts` may need their `isASAN` bound raised. The `sslCtxLiveCount` check is the real regression guard there — if that passes and LSAN is clean, raise the RSS bound.\n- **`asn1_string_st` / `GENERAL_NAME_st` layout** — Bun mirrors these in `src/boringssl_sys/boringssl.rs`; diff `include/openssl/{asn1,x509v3}.h` for field changes.\n- **Values Rust hardcodes** — upstream has renumbered an enum (`ssl_compliance_policy_t`) and taken a flag bit the fork used (`X509_V_FLAG_*`). Neither fails to link. Diff macro values (`clang -dM -E`) and enums between the old and new `include/openssl`.\n", "skills/upgrade-nodejs/SKILL.md": "---\nname: upgrade-nodejs\ndescription: Upgrading Bun's Self-Reported Node.js Version\n---\n\n# Upgrading Bun's Self-Reported Node.js Version\n\nThis guide explains how to upgrade the Node.js version that Bun reports for compatibility with Node.js packages and native addons.\n\n## Overview\n\nBun reports a Node.js version for compatibility with the Node.js ecosystem. This affects:\n\n- `process.version` output\n- Node-API (N-API) compatibility\n- Native addon ABI compatibility\n- V8 API compatibility for addons using V8 directly\n\n## Files That Always Need Updates\n\n### 1. The CI image spec\n\n- `scripts/build/ci-images/spec.ts` - Update `pins.nodejs.version`. The build system's `NODEJS_VERSION` imports it, and the CI images that change are rebaked by the next build. The macOS test machines get it the next time `scripts/darwin-ci` bakes them.\n\n### 2. The ABI version\n\n- `scripts/build/deps/nodejs-headers.ts`\n  - `NODEJS_ABI_VERSION` - The ABI version number (find using command below)\n\n### 3. Version Strings\n\n- `src/jsc/bindings/BunProcess.cpp`\n  - Update `Bun__versions_node` with the Node.js version\n  - Update `Bun__versions_v8` with the V8 version (find using command below)\n\n### 4. N-API Version\n\n- `src/runtime/napi/js_native_api_types.h`\n  - Update `NAPI_VERSION` define (check Node.js release notes; see `src/runtime/napi/README.md` for the header resync procedure)\n\n## Files That May Need Updates\n\nOnly check these if the build fails or tests crash after updating version numbers:\n\n- V8 compatibility files in `src/jsc/bindings/v8/` (if V8 API changed)\n- Test files (if Node.js requires newer C++ standard)\n\n## Quick Commands to Find Version Info\n\n```bash\n# Get latest Node.js version info\ncurl -s https://nodejs.org/dist/index.json | jq '.[0]'\n\n# Get V8 version for a specific Node.js version (replace v24.3.0)\ncurl -s https://nodejs.org/dist/v24.3.0/node-v24.3.0-headers.tar.gz | tar -xzO node-v24.3.0/include/node/node_version.h | grep V8_VERSION\n\n# Get ABI version for a specific Node.js version\ncurl -s https://nodejs.org/dist/v24.3.0/node-v24.3.0-headers.tar.gz | tar -xzO node-v24.3.0/include/node/node_version.h | grep NODE_MODULE_VERSION\n\n# Or use the ABI registry\ncurl -s https://raw.githubusercontent.com/nodejs/node/main/doc/abi_version_registry.json | jq '.NODE_MODULE_VERSION.\"<version>\"'\n```\n\n## Update Process\n\n1. **Gather version info** using the commands above\n2. **Update the required files** listed in the sections above\n3. **Build and test**:\n\n   ```bash\n   bun bd\n   bun bd -e \"console.log(process.version)\"\n   bun bd -e \"console.log(process.versions.v8)\"\n   bun bd test test/v8/v8.test.ts\n   bun bd test test/napi/napi.test.ts\n   ```\n\n4. **Check for V8 API changes** only if build fails or tests crash:\n   - Compare v8-function-callback.h between versions\n   - Check v8-internal.h for Isolate size changes\n   - Look for new required APIs in build errors\n\n## If Build Fails or Tests Crash\n\nThe V8 API rarely has breaking changes between minor Node.js versions. If you encounter issues:\n\n1. Check build errors for missing symbols or type mismatches\n2. Compare V8 headers between old and new Node.js versions\n3. Most issues can be resolved by implementing missing functions or adjusting structures\n\n## Testing Checklist\n\n- [ ] `process.version` returns correct version\n- [ ] `process.versions.v8` returns correct V8 version\n- [ ] `process.config.variables.node_module_version` returns correct ABI\n- [ ] V8 tests pass\n- [ ] N-API tests pass\n\n## Notes\n\n- Most upgrades only require updating version numbers\n- Major V8 version changes (rare) may require API updates\n- The V8 shim implements only APIs used by common native addons\n", "skills/upgrade-webkit/SKILL.md": "---\nname: upgrade-webkit\ndescription: Upgrade Bun's WebKit fork to the latest upstream version of WebKit\n---\n\nUpgrade Bun's WebKit fork (vendor/WebKit = oven-sh/WebKit) to the latest upstream WebKit.\n\nTwo modes — pick from ARGUMENTS:\n\n- **Direct (default)**: push the merge straight to oven-sh/WebKit main. Confirm with the user before pushing.\n- **Preview** (when ARGUMENTS contains `preview` or `pr`): never push to main. Open a PR on oven-sh/WebKit and use its auto-built preview release instead.\n\nTo do that:\n\n- cd vendor/WebKit (must be a real clone with an `upstream` remote pointing at WebKit/WebKit)\n- git fetch upstream\n- OLD_BASE=$(git merge-base origin/main upstream/main) — save this for the changelog\n- Preview mode: create a working branch (e.g. `bun/upgrade-to-<upstream-short-sha>`) instead of staying on main\n- git merge upstream/main\n- Fix the merge conflicts (preserve the fork's Bun-specific changes)\n- bun run jsc:build:debug — from the bun repo root, builds just JSC (and its `jsc` shell), in bun's own build graph. File lists come from the checkout, but `scripts/build/deps/webkit.ts` restates WebKit's generator commands, compiler flags and option values by hand, and nothing checks them. Read `git diff $OLD_BASE upstream/main -- Source/cmake Source/JavaScriptCore/CMakeLists.txt Source/WTF/wtf/CMakeLists.txt Source/bmalloc/CMakeLists.txt` for changed `add_custom_command`s (→ `gen()`), compiler flags (→ `webkitFlags()`) and `WEBKIT_OPTION_*` / `SET_AND_EXPOSE_TO_BUILD` (→ `rows`), and carry them over in the bun PR\n- While it compiles, in another task review the JSC commits between $OLD_BASE and upstream/main (Source/JavaScriptCore, Source/WTF, Source/bmalloc). Write up a summary in a file called \"webkit-changes.md\"\n- bun run build:local — full Bun build with the local WebKit (same build directory and objects as the JSC build above)\n- After it compiles, run some code to make sure things work: `bun run build:local -p '42'`\n- Publish the new WebKit:\n  - Direct: cd vendor/WebKit, commit, `git push origin main`. The push triggers a release tagged `autobuild-<full-sha>`.\n  - Preview: push the branch and open a PR on oven-sh/WebKit. CI publishes a prerelease tagged `autobuild-preview-pr-<PR#>-<first-8-chars-of-head-sha>`. (Auto-triggers only for authors with write access; otherwise `gh workflow run build-preview.yml --repo oven-sh/WebKit -f pr_number=<N>`.)\n- Wait until the release exists: `gh release view <tag> --repo oven-sh/WebKit`. It is created only after ALL platform builds succeed (takes a while). Bun's CI downloads prebuilts from it, so don't open the bun PR before it's up.\n- cd back to bun and update WEBKIT_VERSION in scripts/build/deps/webkit.ts:\n  - Direct: the new vendor/WebKit commit sha\n  - Preview: the full preview tag (`autobuild-preview-pr-...`)\n- bun run pin-webkit — writes the sha256 of the release's tarballs to scripts/build/deps/webkit.sha256. Commit it with WEBKIT_VERSION, every time that changes\n- git checkout -b claude/webkit-upgrade-<sha> (branch must start with `claude/` for CI)\n- commit + push (without adding the webkit-changes.md file)\n- create a PR titled \"Upgrade WebKit to <upstream-short-sha>\", paste webkit-changes.md into the description\n  - Preview mode: also note in the description that WEBKIT_VERSION points at a preview build and must be bumped to the merge-commit's `autobuild-<sha>` after the oven-sh/WebKit PR merges — do that bump before merging the bun PR\n- delete the webkit-changes.md file\n\nThings to check for a successful upgrade:\n\n- Did Source/JavaScriptCore/runtime/JSType.h change? The enum values must align with Bun's mirror in src/jsc/JSType.rs.\n- Do JavaScriptCore or WTF call ICU in another way (functions, arguments, number skeletons, pattern letters), or did icu/source.json change? src/icu has only what is called: see src/icu/README.md.\n- Were there any changes to the WebCore code generator? If there are C++ compilation errors, check for differences in the generated reference code in vendor/WebKit/Source/WebCore/bindings/scripts/test/JS/\n- If the merge touched the fork's .github/workflows, the release tarball names must still match prebuiltSuffix() in scripts/build/deps/webkit.ts\n", "skills/verify/SKILL.md": "---\nname: verify\ndescription: Verify a Bun runtime change by driving the debug binary end-to-end.\n---\n\n# Verify a Bun runtime change\n\nBuild and drive the debug binary directly — never `bun test`, never import-and-call.\n\n## Build\n\n```sh\nbun bd --version   # builds ./build/debug/bun-debug and prints its version\n```\n\n## Drive\n\nFor any JS-visible change, run the debug binary with `-e` and observe stdout:\n\n```sh\nbun bd -e '<repro>'   # builds, then runs; sets BUN_DEBUG_QUIET_LOGS for you\n```\n\nFor worker/subprocess-shaped changes, spawn a subprocess (still `-e`) so worker teardown / event-loop-idle paths are exercised. Cross-check against `node -e '<same repro>'` for Node-compat changes.\n\n## Gotchas\n\n- **A `src/js/**` edit can silently not reach the binary.** `bundle-modules`\n  regenerates `build/<cfg>/codegen/InternalModuleRegistryConstants.h`, but the C++\n  TU that embeds it is not always recompiled, so the build succeeds while the\n  binary still runs the OLD JS. Gate on the binary, not the build: ask the binary\n  you just built — `bun bd -e 'console.log(<Class>.toString().includes(\"<new-id>\"))'`\n  (or run `./build/<cfg>/bun` directly). Plain `bun` is the system Bun on $PATH and\n  never has your edit, so it answers about the wrong binary.\n  If false, `touch src/jsc/bindings/InternalModuleRegistry.cpp` and rebuild.\n- **Prefix every `bun bd` with `PATH=\"$HOME/.cargo/bin:$PATH\"`** — Homebrew's `rust`\n  formula shadows the pinned nightly, and `bun bd` dies with `the option 'Z' is only\n  accepted on the nightly compiler`. `bun bd` re-runs cargo on every invocation, so\n  this is needed for follow-up runs too, not just the first build.\n- `node:cluster` changes can't be driven with `-e`: `cluster.fork()` re-execs `argv[1]`, so workers need a real file on disk. Write a scratch script and run `./build/debug/bun-debug <file>`.\n- Only one `bun bd` per worktree at a time — a second one blocks on the build lock and looks like a runtime hang. Build once, then drive `./build/debug/bun-debug` directly under `timeout`.\n- `BUN_DEBUG_QUIET_LOGS=1` suppresses debug-build log spam.\n- Debug builds print `[cachefs]`/`[sys]` lines to stdout; filter them before diffing\n  output against `node`.\n- MessagePort's `.on/.off` are added by requiring `worker_threads` — plain `new MessageChannel()` ports only have `addEventListener` until then.\n- The debug+asan build is 10-100× slower than release; large-allocation stress tests can time out locally while passing in CI.\n- Locally, run only the test files you touched. Leave neighbouring files, whole directories and repeat-for-stability loops to CI.\n", "skills/writing-bundler-tests/SKILL.md": "---\nname: writing-bundler-tests\ndescription: Guides writing bundler tests using itBundled/expectBundled in test/bundler/. Use when creating or modifying bundler, transpiler, or code transformation tests.\n---\n\n# Writing Bundler Tests\n\nBundler tests use `itBundled()` from `test/bundler/expectBundled.ts` to test Bun's bundler.\n\n## Basic Usage\n\n```typescript\nimport { describe } from \"bun:test\";\nimport { itBundled, dedent } from \"./expectBundled\";\n\ndescribe(\"bundler\", () => {\n  itBundled(\"category/TestName\", {\n    files: {\n      \"index.js\": `console.log(\"hello\");`,\n    },\n    run: {\n      stdout: \"hello\",\n    },\n  });\n});\n```\n\nTest ID format: `category/TestName` (e.g., `banner/CommentBanner`, `minify/Empty`)\n\n## File Setup\n\n```typescript\n{\n  files: {\n    \"index.js\": `console.log(\"test\");`,\n    \"lib.ts\": `export const foo = 123;`,\n    \"nested/file.js\": `export default {};`,\n  },\n  entryPoints: [\"index.js\"],  // defaults to first file\n  runtimeFiles: {             // written AFTER bundling\n    \"extra.js\": `console.log(\"added later\");`,\n  },\n}\n```\n\n## Bundler Options\n\n```typescript\n{\n  outfile: \"/out.js\",\n  outdir: \"/out\",\n  format: \"esm\" | \"cjs\" | \"iife\",\n  target: \"bun\" | \"browser\" | \"node\",\n\n  // Minification\n  minifyWhitespace: true,\n  minifyIdentifiers: true,\n  minifySyntax: true,\n\n  // Code manipulation\n  banner: \"// copyright\",\n  footer: \"// end\",\n  define: { \"PROD\": \"true\" },\n  external: [\"lodash\"],\n\n  // Advanced\n  sourceMap: \"inline\" | \"external\",\n  splitting: true,\n  treeShaking: true,\n  drop: [\"console\"],\n}\n```\n\n## Runtime Verification\n\n```typescript\n{\n  run: {\n    stdout: \"expected output\",      // exact match\n    stdout: /regex/,                // pattern match\n    partialStdout: \"contains this\", // substring\n    stderr: \"error output\",\n    exitCode: 1,\n    env: { NODE_ENV: \"production\" },\n    runtime: \"bun\" | \"node\",\n\n    // Runtime errors\n    error: \"ReferenceError: x is not defined\",\n  },\n}\n```\n\n## Bundle Errors/Warnings\n\n```typescript\n{\n  bundleErrors: {\n    \"/file.js\": [\"error message 1\", \"error message 2\"],\n  },\n  bundleWarnings: {\n    \"/file.js\": [\"warning message\"],\n  },\n}\n```\n\n## Dead Code Elimination (DCE)\n\nAdd markers in source code:\n\n```javascript\n// KEEP - this should survive\nconst used = 1;\n\n// REMOVE - this should be eliminated\nconst unused = 2;\n```\n\n```typescript\n{\n  dce: true,\n  dceKeepMarkerCount: 5,  // expected KEEP markers\n}\n```\n\n## Capture Pattern\n\nVerify exact transpilation with `capture()`:\n\n```typescript\nitBundled(\"string/Folding\", {\n  files: {\n    \"index.ts\": `capture(\\`\\${1 + 1}\\`);`,\n  },\n  capture: ['\"2\"'], // expected captured value\n  minifySyntax: true,\n});\n```\n\n## Post-Bundle Assertions\n\n```typescript\n{\n  onAfterBundle(api) {\n    api.expectFile(\"out.js\").toContain(\"console.log\");\n    api.assertFileExists(\"out.js\");\n\n    const content = api.readFile(\"out.js\");\n    expect(content).toMatchSnapshot();\n\n    const values = api.captureFile(\"out.js\");\n    expect(values).toEqual([\"2\"]);\n  },\n}\n```\n\n## Common Patterns\n\n**Simple output verification:**\n\n```typescript\nitBundled(\"banner/Comment\", {\n  banner: \"// copyright\",\n  files: { \"a.js\": `console.log(\"Hello\")` },\n  onAfterBundle(api) {\n    api.expectFile(\"out.js\").toContain(\"// copyright\");\n  },\n});\n```\n\n**Multi-file CJS/ESM interop:**\n\n```typescript\nitBundled(\"cjs/ImportSyntax\", {\n  files: {\n    \"entry.js\": `import lib from './lib.cjs'; console.log(lib);`,\n    \"lib.cjs\": `exports.foo = 'bar';`,\n  },\n  run: { stdout: '{\"foo\":\"bar\"}' },\n});\n```\n\n**Error handling:**\n\n```typescript\nitBundled(\"edgecase/InvalidLoader\", {\n  files: { \"index.js\": `...` },\n  bundleErrors: {\n    \"index.js\": [\"Unsupported loader type\"],\n  },\n});\n```\n\n## Test Organization\n\n```text\ntest/bundler/\n├── bundler_banner.test.ts\n├── bundler_string.test.ts\n├── bundler_minify.test.ts\n├── bundler_cjs.test.ts\n├── bundler_edgecase.test.ts\n├── bundler_splitting.test.ts\n├── css/\n├── transpiler/\n└── expectBundled.ts\n```\n\n## Running Tests\n\n```bash\nbun bd test test/bundler/bundler_banner.test.ts\nBUN_BUNDLER_TEST_FILTER=\"banner/Comment\" bun bd test bundler_banner.test.ts\nBUN_BUNDLER_TEST_DEBUG=1 bun bd test bundler_minify.test.ts\n```\n\n## Key Points\n\n- Use `dedent` for readable multi-line code\n- File paths are relative (e.g., `/index.js`)\n- Use `capture()` to verify exact transpilation results\n- Use `.toMatchSnapshot()` for complex outputs\n- Pass array to `run` for multiple test scenarios\n", "skills/writing-dev-server-tests/SKILL.md": "---\nname: writing-dev-server-tests\ndescription: Guides writing HMR/Dev Server tests in test/bake/. Use when creating or modifying dev server, hot reloading, or bundling tests.\n---\n\n# Writing HMR/Dev Server Tests\n\nDev server tests validate hot-reloading robustness and reliability.\n\n## File Structure\n\n- `test/bake/bake-harness.ts` - shared utilities: `devTest`, `prodTest`, `devAndProductionTest`, `Dev` class, `Client` class\n- `test/bake/client-fixture.mjs` - subprocess for `Client` (page loading, IPC queries)\n- `test/bake/dev/*.test.ts` - dev server and hot reload tests\n- `test/bake/dev-and-prod.ts` - tests running on both dev and production mode\n\n## Test Categories\n\n- `bundle.test.ts` - DevServer-specific bundling bugs\n- `css.test.ts` - CSS bundling issues\n- `plugins.test.ts` - development mode plugins\n- `ecosystem.test.ts` - library compatibility (prefer concrete bugs over full package tests)\n- `esm.test.ts` - ESM features in development\n- `html.test.ts` - HTML file handling\n- `react-spa.test.ts` - React, react-refresh transform, server components\n- `sourcemap.test.ts` - source map correctness\n\n## devTest Basics\n\n```ts\nimport { devTest, emptyHtmlFile } from \"../bake-harness\";\n\ndevTest(\"html file is watched\", {\n  files: {\n    \"index.html\": emptyHtmlFile({\n      scripts: [\"/script.ts\"],\n      body: \"<h1>Hello</h1>\",\n    }),\n    \"script.ts\": `console.log(\"hello\");`,\n  },\n  async test(dev) {\n    await dev.fetch(\"/\").expect.toInclude(\"<h1>Hello</h1>\");\n    await dev.patch(\"index.html\", { find: \"Hello\", replace: \"World\" });\n    await dev.fetch(\"/\").expect.toInclude(\"<h1>World</h1>\");\n\n    await using c = await dev.client(\"/\");\n    await c.expectMessage(\"hello\");\n\n    await c.expectReload(async () => {\n      await dev.patch(\"index.html\", { find: \"World\", replace: \"Bar\" });\n    });\n    await c.expectMessage(\"hello\");\n  },\n});\n```\n\n## Key APIs\n\n- **`files`**: Initial filesystem state\n- **`dev.fetch()`**: HTTP requests\n- **`dev.client()`**: Opens browser instance\n- **`dev.write/patch/delete`**: Filesystem mutations (wait for hot-reload automatically)\n- **`c.expectMessage()`**: Assert console.log output\n- **`c.expectReload()`**: Wrap code that causes hard reload\n\n**Important**: Use `dev.write/patch/delete` instead of `node:fs` - they wait for hot-reload.\n\n## Testing Errors\n\n```ts\ndevTest(\"import then create\", {\n  files: {\n    \"index.html\": `<!DOCTYPE html><html><head></head><body><script type=\"module\" src=\"/script.ts\"></script></body></html>`,\n    \"script.ts\": `import data from \"./data\"; console.log(data);`,\n  },\n  async test(dev) {\n    const c = await dev.client(\"/\", {\n      errors: ['script.ts:1:18: error: Could not resolve: \"./data\"'],\n    });\n    await c.expectReload(async () => {\n      await dev.write(\"data.ts\", \"export default 'data';\");\n    });\n    await c.expectMessage(\"data\");\n  },\n});\n```\n\nSpecify expected errors with the `errors` option:\n\n```ts\nawait dev.delete(\"other.ts\", {\n  errors: ['index.ts:1:16: error: Could not resolve: \"./other\"'],\n});\n```\n"}}
