New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

bun-types

Package Overview
Dependencies
Maintainers
3
Versions
842
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bun-types - npm Package Compare versions

Comparing version

to
1.1.44-canary.20250113T140648

docs/project/contributing.md

10

ambient.d.ts

@@ -10,1 +10,11 @@ declare module "*.txt" {

}
declare module "*.jsonc" {
var contents: any;
export = contents;
}
declare module "*/bun.lock" {
var contents: import("bun").BunLockFile;
export = contents;
}

2

docs/api/binary-data.md

@@ -238,3 +238,3 @@ This page is intended as an introduction to working with binary data in JavaScript. Bun implements a number of data types and utilities for working with binary data, most of which are Web-standard. Any Bun-specific APIs will be noted as such.

- [`BigInt64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array)
- Every eight (8) bytes are interpreted as an unsigned `BigInt`. Range -9223372036854775808 to 9223372036854775807 (though `BigInt` is capable of representing larger numbers).
- Every eight (8) bytes are interpreted as a signed `BigInt`. Range -9223372036854775808 to 9223372036854775807 (though `BigInt` is capable of representing larger numbers).

@@ -241,0 +241,0 @@ ---

@@ -198,3 +198,3 @@ Bun implements the WHATWG `fetch` standard, with some extensions to meet the needs of server-side JavaScript.

[fetch] > Connection: keep-alive
[fetch] > User-Agent: Bun/1.1.21
[fetch] > User-Agent: Bun/1.1.44-canary.20250113T140648
[fetch] > Accept: */*

@@ -201,0 +201,0 @@ [fetch] > Host: example.com

@@ -1,31 +0,334 @@

Bun provides a fast native implementation of the `HTMLRewriter` pattern developed by Cloudflare. It provides a convenient, `EventListener`-like API for traversing and transforming HTML documents.
HTMLRewriter lets you use CSS selectors to transform HTML documents. It works with `Request`, `Response`, as well as `string`. Bun's implementation is based on Cloudflare's [lol-html](https://github.com/cloudflare/lol-html).
## Usage
A common usecase is rewriting URLs in HTML content. Here's an example that rewrites image sources and link URLs to use a CDN domain:
```ts
const rewriter = new HTMLRewriter();
// Replace all images with a rickroll
const rewriter = new HTMLRewriter().on("img", {
element(img) {
// Famous rickroll video thumbnail
img.setAttribute(
"src",
"https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg",
);
rewriter.on("*", {
element(el) {
console.log(el.tagName); // "body" | "div" | ...
// Wrap the image in a link to the video
img.before(
'<a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">',
{ html: true },
);
img.after("</a>", { html: true });
// Add some fun alt text
img.setAttribute("alt", "Definitely not a rickroll");
},
});
```
To parse and/or transform the HTML:
```ts#rewriter.ts
rewriter.transform(
new Response(`
<!DOCTYPE html>
// An example HTML document
const html = `
<html>
<!-- comment -->
<head>
<title>My First HTML Page</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<img src="/cat.jpg">
<img src="dog.png">
<img src="https://example.com/bird.webp">
</body>
`));
</html>
`;
const result = rewriter.transform(html);
console.log(result);
```
View the full documentation on the [Cloudflare website](https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/).
This replaces all images with a thumbnail of Rick Astley and wraps each `<img>` in a link, producing a diff like this:
```html-diff
<html>
<body>
- <img src="/cat.jpg">
- <img src="dog.png">
- <img src="https://example.com/bird.webp">
+ <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
+ <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
+ </a>
+ <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
+ <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
+ </a>
+ <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
+ <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
+ </a>
</body>
</html>
```
Now every image on the page will be replaced with a thumbnail of Rick Astley, and clicking any image will lead to [a very famous video](https://www.youtube.com/watch?v=dQw4w9WgXcQ).
### Input types
HTMLRewriter can transform HTML from various sources. The input is automatically handled based on its type:
```ts
// From Response
rewriter.transform(new Response("<div>content</div>"));
// From string
rewriter.transform("<div>content</div>");
// From ArrayBuffer
rewriter.transform(new TextEncoder().encode("<div>content</div>").buffer);
// From Blob
rewriter.transform(new Blob(["<div>content</div>"]));
// From File
rewriter.transform(Bun.file("index.html"));
```
Note that Cloudflare Workers implementation of HTMLRewriter only supports `Response` objects.
### Element Handlers
The `on(selector, handlers)` method allows you to register handlers for HTML elements that match a CSS selector. The handlers are called for each matching element during parsing:
```ts
rewriter.on("div.content", {
// Handle elements
element(element) {
element.setAttribute("class", "new-content");
element.append("<p>New content</p>", { html: true });
},
// Handle text nodes
text(text) {
text.replace("new text");
},
// Handle comments
comments(comment) {
comment.remove();
},
});
```
The handlers can be asynchronous and return a Promise. Note that async operations will block the transformation until they complete:
```ts
rewriter.on("div", {
async element(element) {
await Bun.sleep(1000);
element.setInnerContent("<span>replace</span>", { html: true });
},
});
```
### CSS Selector Support
The `on()` method supports a wide range of CSS selectors:
```ts
// Tag selectors
rewriter.on("p", handler);
// Class selectors
rewriter.on("p.red", handler);
// ID selectors
rewriter.on("h1#header", handler);
// Attribute selectors
rewriter.on("p[data-test]", handler); // Has attribute
rewriter.on('p[data-test="one"]', handler); // Exact match
rewriter.on('p[data-test="one" i]', handler); // Case-insensitive
rewriter.on('p[data-test="one" s]', handler); // Case-sensitive
rewriter.on('p[data-test~="two"]', handler); // Word match
rewriter.on('p[data-test^="a"]', handler); // Starts with
rewriter.on('p[data-test$="1"]', handler); // Ends with
rewriter.on('p[data-test*="b"]', handler); // Contains
rewriter.on('p[data-test|="a"]', handler); // Dash-separated
// Combinators
rewriter.on("div span", handler); // Descendant
rewriter.on("div > span", handler); // Direct child
// Pseudo-classes
rewriter.on("p:nth-child(2)", handler);
rewriter.on("p:first-child", handler);
rewriter.on("p:nth-of-type(2)", handler);
rewriter.on("p:first-of-type", handler);
rewriter.on("p:not(:first-child)", handler);
// Universal selector
rewriter.on("*", handler);
```
### Element Operations
Elements provide various methods for manipulation. All modification methods return the element instance for chaining:
```ts
rewriter.on("div", {
element(el) {
// Attributes
el.setAttribute("class", "new-class").setAttribute("data-id", "123");
const classAttr = el.getAttribute("class"); // "new-class"
const hasId = el.hasAttribute("id"); // boolean
el.removeAttribute("class");
// Content manipulation
el.setInnerContent("New content"); // Escapes HTML by default
el.setInnerContent("<p>HTML content</p>", { html: true }); // Parses HTML
el.setInnerContent(""); // Clear content
// Position manipulation
el.before("Content before")
.after("Content after")
.prepend("First child")
.append("Last child");
// HTML content insertion
el.before("<span>before</span>", { html: true })
.after("<span>after</span>", { html: true })
.prepend("<span>first</span>", { html: true })
.append("<span>last</span>", { html: true });
// Removal
el.remove(); // Remove element and contents
el.removeAndKeepContent(); // Remove only the element tags
// Properties
console.log(el.tagName); // Lowercase tag name
console.log(el.namespaceURI); // Element's namespace URI
console.log(el.selfClosing); // Whether element is self-closing (e.g. <div />)
console.log(el.canHaveContent); // Whether element can contain content (false for void elements like <br>)
console.log(el.removed); // Whether element was removed
// Attributes iteration
for (const [name, value] of el.attributes) {
console.log(name, value);
}
// End tag handling
el.onEndTag(endTag => {
endTag.before("Before end tag");
endTag.after("After end tag");
endTag.remove(); // Remove the end tag
console.log(endTag.name); // Tag name in lowercase
});
},
});
```
### Text Operations
Text handlers provide methods for text manipulation. Text chunks represent portions of text content and provide information about their position in the text node:
```ts
rewriter.on("p", {
text(text) {
// Content
console.log(text.text); // Text content
console.log(text.lastInTextNode); // Whether this is the last chunk
console.log(text.removed); // Whether text was removed
// Manipulation
text.before("Before text").after("After text").replace("New text").remove();
// HTML content insertion
text
.before("<span>before</span>", { html: true })
.after("<span>after</span>", { html: true })
.replace("<span>replace</span>", { html: true });
},
});
```
### Comment Operations
Comment handlers allow comment manipulation with similar methods to text nodes:
```ts
rewriter.on("*", {
comments(comment) {
// Content
console.log(comment.text); // Comment text
comment.text = "New comment text"; // Set comment text
console.log(comment.removed); // Whether comment was removed
// Manipulation
comment
.before("Before comment")
.after("After comment")
.replace("New comment")
.remove();
// HTML content insertion
comment
.before("<span>before</span>", { html: true })
.after("<span>after</span>", { html: true })
.replace("<span>replace</span>", { html: true });
},
});
```
### Document Handlers
The `onDocument(handlers)` method allows you to handle document-level events. These handlers are called for events that occur at the document level rather than within specific elements:
```ts
rewriter.onDocument({
// Handle doctype
doctype(doctype) {
console.log(doctype.name); // "html"
console.log(doctype.publicId); // public identifier if present
console.log(doctype.systemId); // system identifier if present
},
// Handle text nodes
text(text) {
console.log(text.text);
},
// Handle comments
comments(comment) {
console.log(comment.text);
},
// Handle document end
end(end) {
end.append("<!-- Footer -->", { html: true });
},
});
```
### Response Handling
When transforming a Response:
- The status code, headers, and other response properties are preserved
- The body is transformed while maintaining streaming capabilities
- Content-encoding (like gzip) is handled automatically
- The original response body is marked as used after transformation
- Headers are cloned to the new response
## Error Handling
HTMLRewriter operations can throw errors in several cases:
- Invalid selector syntax in `on()` method
- Invalid HTML content in transformation methods
- Stream errors when processing Response bodies
- Memory allocation failures
- Invalid input types (e.g., passing Symbol)
- Body already used errors
Errors should be caught and handled appropriately:
```ts
try {
const result = rewriter.transform(input);
// Process result
} catch (error) {
console.error("HTMLRewriter error:", error);
}
```
## See also
You can also read the [Cloudflare documentation](https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/), which this API is intended to be compatible with.

@@ -113,3 +113,3 @@ Spawn child processes with `Bun.spawn` or `Bun.spawnSync`.

const text = await new Response(proc.stdout).text();
console.log(text); // => "1.1.7"
console.log(text); // => "1.1.44-canary.20250113T140648"
```

@@ -116,0 +116,0 @@

@@ -10,3 +10,3 @@ Use `bun publish` to publish a package to the npm registry.

## Output
bun publish v1.1.30 (ca7428e9)
bun publish v1.1.44-canary.20250113T140648 (ca7428e9)

@@ -13,0 +13,0 @@ packed 203B package.json

@@ -12,3 +12,3 @@ ---

◐ Installing dependencies...
bun install v1.x (16b4bf34)
bun install v$BUN_LATEST_VERSION (16b4bf34)
+ @nuxt/devtools@0.8.2

@@ -15,0 +15,0 @@ + nuxt@3.7.0

@@ -19,3 +19,3 @@ ---

"peerDependencies": {
+ "@types/bun": "^1.0.0"
+ "@types/bun": "^$BUN_LATEST_VERSION"
}

@@ -32,3 +32,3 @@ }

"peerDependencies": {
"@types/bun": "^1.0.0"
"@types/bun": "^$BUN_LATEST_VERSION"
},

@@ -35,0 +35,0 @@ "peerDependenciesMeta": {

@@ -100,3 +100,3 @@ ---

# Update a dependency to a specific version
$ bun update @types/bun@1.1.10
$ bun update @types/bun@$BUN_LATEST_VERSION

@@ -103,0 +103,0 @@ # Update all dependencies to the latest versions

@@ -24,3 +24,3 @@ ---

$ bun test
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -51,3 +51,3 @@ test.test.js:

$ bun test test3
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -90,3 +90,3 @@ test3.test.js:

$ bun test -t add
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -93,0 +93,0 @@ test.test.js:

@@ -21,3 +21,3 @@ ---

$ bun test test/snap
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -65,3 +65,3 @@ test/snap.test.ts:

$ bun test
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -83,3 +83,3 @@ test/snap.test.ts:

$ bun test --update-snapshots
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -86,0 +86,0 @@ test/snap.test.ts:

@@ -32,3 +32,3 @@ ---

$ bun test --update-snapshots
bun test v1.x (9c68abdb)
bun test v$BUN_LATEST_VERSION (9c68abdb)

@@ -35,0 +35,0 @@ test/snap.test.ts:

@@ -8,3 +8,3 @@ ---

```ts#index.ts
Bun.version; // => "0.6.15"
Bun.version; // => "$BUN_LATEST_VERSION"
```

@@ -11,0 +11,0 @@

@@ -17,3 +17,3 @@ Bun ships as a single executable with no dependencies that can be installed a few different ways.

# to install a specific version
$ curl -fsSL https://bun.sh/install | bash -s "bun-v1.0.0"
$ curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_LATEST_VERSION"
```

@@ -170,6 +170,6 @@

To install a specific version of Bun, you can pass the git tag of the version you want to install to the install script, such as `bun-v1.1.6` or `bun-v1.1.1`.
To install a specific version of Bun, you can pass the git tag of the version you want to install to the install script, such as `bun-v1.2.0` or `bun-v$BUN_LATEST_VERSION`.
```sh
$ curl -fsSL https://bun.sh/install | bash -s "bun-v1.1.6"
$ curl -fsSL https://bun.sh/install | bash -s "bun-v$BUN_LATEST_VERSION"
```

@@ -183,3 +183,3 @@

# PowerShell:
$ iex "& {$(irm https://bun.sh/install.ps1)} -Version 1.1.6"
$ iex "& {$(irm https://bun.sh/install.ps1)} -Version $BUN_LATEST_VERSION"
```

@@ -186,0 +186,0 @@

@@ -95,3 +95,3 @@ Let's write a simple HTTP server using the built-in `Bun.serve` API. First, create a fresh directory.

"devDependencies": {
"@types/bun": "^1.0.0"
"@types/bun": "latest"
}

@@ -98,0 +98,0 @@ }

@@ -127,7 +127,7 @@ ---

```sh
[fetch] $ curl --http1.1 "https://example.com/" -X POST -H "content-type: application/json" -H "Connection: keep-alive" -H "User-Agent: Bun/1.1.14" -H "Accept: */*" -H "Host: example.com" -H "Accept-Encoding: gzip, deflate, br" --compressed -H "Content-Length: 13" --data-raw "{\"foo\":\"bar\"}"
[fetch] $ curl --http1.1 "https://example.com/" -X POST -H "content-type: application/json" -H "Connection: keep-alive" -H "User-Agent: Bun/1.1.44-canary.20250113T140648" -H "Accept: */*" -H "Host: example.com" -H "Accept-Encoding: gzip, deflate, br" --compressed -H "Content-Length: 13" --data-raw "{\"foo\":\"bar\"}"
[fetch] > HTTP/1.1 POST https://example.com/
[fetch] > content-type: application/json
[fetch] > Connection: keep-alive
[fetch] > User-Agent: Bun/1.1.14
[fetch] > User-Agent: Bun/1.1.44-canary.20250113T140648
[fetch] > Accept: */*

@@ -174,3 +174,3 @@ [fetch] > Host: example.com

[fetch] > Connection: keep-alive
[fetch] > User-Agent: Bun/1.1.14
[fetch] > User-Agent: Bun/1.1.44-canary.20250113T140648
[fetch] > Accept: */*

@@ -177,0 +177,0 @@ [fetch] > Host: example.com

@@ -66,2 +66,9 @@ Bun supports two kinds of automatic reloading via CLI flags:

{% callout %}
The **`--no-clear-screen`** flag is useful in scenarios where you don’t want the terminal to clear, such as when running multiple `bun build --watch` commands simultaneously using tools like `concurrently`. Without this flag, the output of one instance could clear the output of others, potentially hiding errors from one instance beneath the output of another. The `--no-clear-screen` flag, similar to TypeScript’s `--preserveWatchOutput`, prevents this issue. It can be used in combination with `--watch`, for example: `bun build --watch --no-clear-screen`.
{% /callout %}
## `--hot` mode

@@ -68,0 +75,0 @@

@@ -184,3 +184,2 @@ Module resolution in JavaScript is a complex topic.

"bun": "./index.js",
"worker": "./index.js",
"node": "./index.js",

@@ -187,0 +186,0 @@ "require": "./index.js", // if importer is CommonJS

@@ -58,3 +58,3 @@ Bun's test runner plays well with existing component and DOM testing libraries, including React Testing Library and [`happy-dom`](https://github.com/capricorn86/happy-dom).

$ bun test
bun test v1.x
bun test v1.1.44-canary.20250113T140648

@@ -61,0 +61,0 @@ dom.test.ts:

@@ -16,8 +16,15 @@ declare namespace HTMLRewriterTypes {

interface Text {
/** The text content */
readonly text: string;
/** Whether this chunk is the last piece of text in a text node */
readonly lastInTextNode: boolean;
/** Whether this chunk was removed */
readonly removed: boolean;
/** Insert content before this chunk */
before(content: Content, options?: ContentOptions): Text;
/** Insert content after this chunk */
after(content: Content, options?: ContentOptions): Text;
/** Replace this chunk with new content */
replace(content: Content, options?: ContentOptions): Text;
/** Remove this chunk */
remove(): Text;

@@ -27,6 +34,11 @@ }

interface Doctype {
/** The doctype name (e.g. "html" for <!DOCTYPE html>) */
readonly name: string | null;
/** The doctype public identifier */
readonly publicId: string | null;
/** The doctype system identifier */
readonly systemId: string | null;
/** Whether this doctype was removed */
readonly removed: boolean;
/** Remove this doctype */
remove(): Doctype;

@@ -36,2 +48,3 @@ }

interface DocumentEnd {
/** Append content at the end of the document */
append(content: Content, options?: ContentOptions): DocumentEnd;

@@ -41,12 +54,20 @@ }

interface ContentOptions {
/** Whether to parse the content as HTML */
html?: boolean;
}
type Content = string;
interface Comment {
/** The comment text */
text: string;
/** Whether this comment was removed */
readonly removed: boolean;
/** Insert content before this comment */
before(content: Content, options?: ContentOptions): Comment;
/** Insert content after this comment */
after(content: Content, options?: ContentOptions): Comment;
/** Replace this comment with new content */
replace(content: Content, options?: ContentOptions): Comment;
/** Remove this comment */
remove(): Comment;

@@ -56,6 +77,9 @@ }

interface Element {
/** The tag name in lowercase (e.g. "div", "span") */
tagName: string;
/** Iterator for the element's attributes */
readonly attributes: IterableIterator<[string, string]>;
/** Whether this element was removed */
readonly removed: boolean;
/** Whether the element is explicitly self-closing, e.g. `<foo />` */
/** Whether the element is explicitly self-closing, e.g. <foo /> */
readonly selfClosing: boolean;

@@ -68,15 +92,29 @@ /**

readonly canHaveContent: boolean;
/** The element's namespace URI */
readonly namespaceURI: string;
/** Get an attribute value by name */
getAttribute(name: string): string | null;
/** Check if an attribute exists */
hasAttribute(name: string): boolean;
/** Set an attribute value */
setAttribute(name: string, value: string): Element;
/** Remove an attribute */
removeAttribute(name: string): Element;
/** Insert content before this element */
before(content: Content, options?: ContentOptions): Element;
/** Insert content after this element */
after(content: Content, options?: ContentOptions): Element;
/** Insert content at the start of this element */
prepend(content: Content, options?: ContentOptions): Element;
/** Insert content at the end of this element */
append(content: Content, options?: ContentOptions): Element;
/** Replace this element with new content */
replace(content: Content, options?: ContentOptions): Element;
/** Remove this element and its contents */
remove(): Element;
/** Remove this element but keep its contents */
removeAndKeepContent(): Element;
/** Set the inner content of this element */
setInnerContent(content: Content, options?: ContentOptions): Element;
/** Add a handler for the end tag of this element */
onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;

@@ -86,5 +124,9 @@ }

interface EndTag {
/** The tag name in lowercase */
name: string;
/** Insert content before this end tag */
before(content: Content, options?: ContentOptions): EndTag;
/** Insert content after this end tag */
after(content: Content, options?: ContentOptions): EndTag;
/** Remove this end tag */
remove(): EndTag;

@@ -118,2 +160,7 @@ }

constructor();
/**
* Add handlers for elements matching a CSS selector
* @param selector - A CSS selector (e.g. "div", "a[href]", ".class")
* @param handlers - Object containing handler functions for elements, comments, and text nodes
*/
on(

@@ -123,6 +170,13 @@ selector: string,

): HTMLRewriter;
/**
* Add handlers for document-level events
* @param handlers - Object containing handler functions for doctype, comments, text nodes and document end
*/
onDocument(
handlers: HTMLRewriterTypes.HTMLRewriterDocumentContentHandlers,
): HTMLRewriter;
/**
* Transform HTML content
* @param input - The HTML to transform

@@ -133,2 +187,3 @@ * @returns A new {@link Response} with the transformed HTML

/**
* Transform HTML content
* @param input - The HTML string to transform

@@ -139,2 +194,3 @@ * @returns A new {@link String} containing the transformed HTML

/**
* Transform HTML content
* @param input - The HTML to transform as a {@link ArrayBuffer}

@@ -141,0 +197,0 @@ * @returns A new {@link ArrayBuffer} with the transformed HTML

{
"version": "1.1.44-canary.20250112T140558",
"version": "1.1.44-canary.20250113T140648",
"name": "bun-types",

@@ -27,3 +27,3 @@ "license": "MIT",

"prebuild": "echo $(pwd)",
"copy-docs": "rm -rf docs && cp -r ../../docs/ ./docs",
"copy-docs": "rm -rf docs && cp -rL ../../docs/ ./docs && sed -i 's/\\$BUN_LATEST_VERSION/'\"${BUN_VERSION:-1.0.0}\"'/g' ./docs/**/*.md",
"build": "bun run copy-docs && bun scripts/build.ts && bun run fmt",

@@ -30,0 +30,0 @@ "test": "tsc",

Sorry, the diff of this file is too big to display