Docs/tag relevant docs (#18544)

This commit is contained in:
Alistair Smith
2025-03-27 23:49:15 +00:00
committed by GitHub
parent 70ddfb55e6
commit f5836c2013
6 changed files with 353 additions and 225 deletions

View File

@@ -537,9 +537,11 @@ declare module "bun" {
/**
* Find the path to an executable, similar to typing which in your terminal. Reads the `PATH` environment variable unless overridden with `options.PATH`.
*
* @param {string} command The name of the executable or script
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd When given a relative path, use this path to join it.
* @category Utilities
*
* @param command The name of the executable or script
* @param options.PATH Overrides the PATH environment variable
* @param options.cwd When given a relative path, use this path to join it.
*/
function which(command: string, options?: { PATH?: string; cwd?: string }): string | null;
@@ -945,19 +947,24 @@ declare module "bun" {
blob(): Blob;
}
/**
* The Bun shell
*
* @category Process Management
*/
const $: Shell;
interface TOML {
const TOML: {
/**
* Parse a TOML string into a JavaScript object.
*
* @param {string} command The name of the executable or script
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd Limits the search to a particular directory in which to searc
* @category Utilities
*
* @param input The TOML string to parse
* @returns A JavaScript object
*/
parse(input: string): object;
}
const TOML: TOML;
};
/**
* Synchronously resolve a `moduleId` as though it were imported from `parent`
@@ -980,6 +987,8 @@ declare module "bun" {
*
* If `destination` exists, it must be a regular file or symlink to a file. If `destination`'s directory does not exist, it will be created by default.
*
* @category File System
*
* @param destination The file or file path to write to
* @param input The data to copy into `destination`.
* @returns A promise that resolves with the number of bytes written.
@@ -1271,6 +1280,8 @@ declare module "bun" {
/**
* Escape the following characters in a string:
*
* @category Security
*
* - `"` becomes `"""`
* - `&` becomes `"&"`
* - `'` becomes `"'"`
@@ -1291,6 +1302,8 @@ declare module "bun" {
* @param path The path to convert.
* @returns A {@link URL} with the file:// scheme.
*
* @category File System
*
* @example
* ```js
* const url = Bun.pathToFileURL("/foo/bar.txt");
@@ -1313,9 +1326,13 @@ declare module "bun" {
/**
* Convert a {@link URL} to a filesystem path.
*
* @param url The URL to convert.
* @returns A filesystem path.
* @throws If the URL is not a URL.
*
* @category File System
*
* @example
* ```js
* const path = Bun.fileURLToPath(new URL("file:///foo/bar.txt"));
@@ -1523,6 +1540,8 @@ declare module "bun" {
* - `size` will not be valid until the contents of the file are read at least once.
* - `type` is auto-set based on the file extension when possible
*
* @category File System
*
* @example
* ```js
* const file = Bun.file("./hello.json");
@@ -1558,7 +1577,7 @@ declare module "bun" {
*
* Similar to [`TypedArray.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). Does not copy the file, open the file, or modify the file.
*
* If `begin` > 0, {@link Bun.write()} will be slower on macOS
* If `begin` > 0, {@link Bun.write}() will be slower on macOS
*
* @param begin - start offset in bytes
* @param contentType - MIME type for the new BunFile
@@ -2040,10 +2059,32 @@ declare module "bun" {
verify(token: string, options?: CSRFVerifyOptions): boolean;
}
/**
* SQL client
*
* @category Database
*/
var sql: SQL;
/**
* SQL client for PostgreSQL
*
* @category Database
*/
var postgres: SQL;
/**
* The SQL constructor
*
* @category Database
*/
var SQL: SQL;
/**
* Generate and verify CSRF tokens
*
* @category Security
*/
var CSRF: CSRF;
/**
@@ -2510,6 +2551,15 @@ declare module "bun" {
throw?: boolean;
}
/**
* Hash and verify passwords using argon2 or bcrypt
*
* These are fast APIs that can run in a worker thread if used asynchronously.
*
* @see [Bun.password API docs](https://bun.sh/guides/util/hash-a-password)
*
* @category Security
*/
namespace Password {
type AlgorithmLabel = "bcrypt" | "argon2id" | "argon2d" | "argon2i";
@@ -2540,6 +2590,10 @@ declare module "bun" {
* Password hashing functions are necessarily slow, and this object will
* automatically run in a worker thread.
*
* @see [Bun.password API docs](https://bun.sh/guides/util/hash-a-password)
*
* @category Security
*
* The underlying implementation of these functions are provided by the Zig
* Standard Library. Thanks to @jedisct1 and other Zig contributors for their
* work on this.
@@ -2724,6 +2778,11 @@ declare module "bun" {
): string;
};
/**
* A build artifact represents a file that was generated by the bundler @see {@link Bun.build}
*
* @category Bundler
*/
interface BuildArtifact extends Blob {
path: string;
loader: Loader;
@@ -2732,6 +2791,11 @@ declare module "bun" {
sourcemap: BuildArtifact | null;
}
/**
* The output of a build
*
* @category Bundler
*/
interface BuildOutput {
outputs: BuildArtifact[];
success: boolean;
@@ -2745,220 +2809,222 @@ declare module "bun" {
* @returns {Promise<BuildOutput>} Promise that resolves to build output containing generated artifacts and build status
* @throws {AggregateError} When build fails and config.throw is true (default in Bun 1.2+)
*
* @category Bundler
*
* @example Basic usage - Bundle a single entrypoint and check results
```ts
const result = await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist'
});
if (!result.success) {
console.error('Build failed:', result.logs);
process.exit(1);
}
```
*
* @example Set up multiple entrypoints with code splitting enabled
```ts
await Bun.build({
entrypoints: ['./src/app.tsx', './src/admin.tsx'],
outdir: './dist',
splitting: true,
sourcemap: "external"
});
```
*
* @example Configure minification and optimization settings
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
minify: {
whitespace: true,
identifiers: true,
syntax: true
},
drop: ['console', 'debugger']
});
```
*
* @example Set up custom loaders and mark packages as external
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
loader: {
'.png': 'dataurl',
'.svg': 'file',
'.txt': 'text',
'.json': 'json'
},
external: ['react', 'react-dom']
});
```
*
* @example Configure environment variable handling with different modes
```ts
// Inline all environment variables
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
env: 'inline'
});
// Only include specific env vars
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
env: 'PUBLIC_*'
});
```
*
* @example Set up custom naming patterns for all output types
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
naming: {
entry: '[dir]/[name]-[hash].[ext]',
chunk: 'chunks/[name]-[hash].[ext]',
asset: 'assets/[name]-[hash].[ext]'
}
});
```
@example Work with build artifacts in different formats
```ts
const result = await Bun.build({
entrypoints: ['./src/index.tsx']
});
for (const artifact of result.outputs) {
const text = await artifact.text();
const buffer = await artifact.arrayBuffer();
const bytes = await artifact.bytes();
new Response(artifact);
await Bun.write(artifact.path, artifact);
}
```
@example Implement comprehensive error handling with position info
```ts
try {
const result = await Bun.build({
entrypoints: ['./src/index.tsx'],
});
} catch (e) {
const error = e as AggregateError;
console.error('Build failed:');
for (const msg of error.errors) {
if ('position' in msg) {
console.error(
`${msg.message} at ${msg.position?.file}:${msg.position?.line}:${msg.position?.column}`
);
} else {
console.error(msg.message);
}
}
}
```
@example Set up Node.js target with specific configurations
```ts
await Bun.build({
entrypoints: ['./src/server.ts'],
outdir: './dist',
target: 'node',
format: 'cjs',
sourcemap: 'external',
minify: false,
packages: 'external'
});
```
*
* @example Configure experimental CSS bundling with multiple themes
```ts
await Bun.build({
entrypoints: [
'./src/styles.css',
'./src/themes/dark.css',
'./src/themes/light.css'
],
outdir: './dist/css',
});
```
@example Define compile-time constants and version information
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
define: {
'process.env.NODE_ENV': JSON.stringify('production'),
'CONSTANTS.VERSION': JSON.stringify('1.0.0'),
'CONSTANTS.BUILD_TIME': JSON.stringify(new Date().toISOString())
}
});
```
@example Create a custom plugin for handling special file types
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
plugins: [
{
name: 'my-plugin',
setup(build) {
build.onLoad({ filter: /\.custom$/ }, async (args) => {
const content = await Bun.file(args.path).text();
return {
contents: `export default ${JSON.stringify(content)}`,
loader: 'js'
};
});
}
}
]
});
```
@example Enable bytecode generation for faster startup
```ts
await Bun.build({
entrypoints: ['./src/server.ts'],
outdir: './dist',
target: 'bun',
format: 'cjs',
bytecode: true
});
```
@example Add custom banner and footer to output files
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
banner: '"use client";\n// Built with Bun',
footer: '// Generated on ' + new Date().toISOString()
});
```
@example Configure CDN public path for asset loading
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
publicPath: 'https://cdn.example.com/assets/',
loader: {
'.png': 'file',
'.svg': 'file'
}
});
```
@example Set up package export conditions for different environments
```ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
conditions: ['production', 'browser', 'module'],
packages: 'external'
});
```
*/
* ```ts
* const result = await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist'
* });
*
* if (!result.success) {
* console.error('Build failed:', result.logs);
* process.exit(1);
* }
* ```
* *
* * @example Set up multiple entrypoints with code splitting enabled
* ```ts
* await Bun.build({
* entrypoints: ['./src/app.tsx', './src/admin.tsx'],
* outdir: './dist',
* splitting: true,
* sourcemap: "external"
* });
* ```
* *
* * @example Configure minification and optimization settings
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* minify: {
* whitespace: true,
* identifiers: true,
* syntax: true
* },
* drop: ['console', 'debugger']
* });
* ```
* *
* * @example Set up custom loaders and mark packages as external
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* loader: {
* '.png': 'dataurl',
* '.svg': 'file',
* '.txt': 'text',
* '.json': 'json'
* },
* external: ['react', 'react-dom']
* });
* ```
* *
* * @example Configure environment variable handling with different modes
* ```ts
* // Inline all environment variables
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* env: 'inline'
* });
* // Only include specific env vars
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* env: 'PUBLIC_*'
* });
* ```
* *
* * @example Set up custom naming patterns for all output types
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* naming: {
* entry: '[dir]/[name]-[hash].[ext]',
* chunk: 'chunks/[name]-[hash].[ext]',
* asset: 'assets/[name]-[hash].[ext]'
* }
* });
* ```
* @example Work with build artifacts in different formats
* ```ts
* const result = await Bun.build({
* entrypoints: ['./src/index.tsx']
* });
* for (const artifact of result.outputs) {
* const text = await artifact.text();
* const buffer = await artifact.arrayBuffer();
* const bytes = await artifact.bytes();
* new Response(artifact);
* await Bun.write(artifact.path, artifact);
* }
* ```
* @example Implement comprehensive error handling with position info
* ```ts
* try {
* const result = await Bun.build({
* entrypoints: ['./src/index.tsx'],
* });
* } catch (e) {
* const error = e as AggregateError;
* console.error('Build failed:');
* for (const msg of error.errors) {
* if ('position' in msg) {
* console.error(
* `${msg.message} at ${msg.position?.file}:${msg.position?.line}:${msg.position?.column}`
* );
* } else {
* console.error(msg.message);
* }
* }
* }
* ```
* @example Set up Node.js target with specific configurations
* ```ts
* await Bun.build({
* entrypoints: ['./src/server.ts'],
* outdir: './dist',
* target: 'node',
* format: 'cjs',
* sourcemap: 'external',
* minify: false,
* packages: 'external'
* });
* ```
* *
* * @example Configure experimental CSS bundling with multiple themes
* ```ts
* await Bun.build({
* entrypoints: [
* './src/styles.css',
* './src/themes/dark.css',
* './src/themes/light.css'
* ],
* outdir: './dist/css',
* });
* ```
* @example Define compile-time constants and version information
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* define: {
* 'process.env.NODE_ENV': JSON.stringify('production'),
* 'CONSTANTS.VERSION': JSON.stringify('1.0.0'),
* 'CONSTANTS.BUILD_TIME': JSON.stringify(new Date().toISOString())
* }
* });
* ```
* @example Create a custom plugin for handling special file types
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* plugins: [
* {
* name: 'my-plugin',
* setup(build) {
* build.onLoad({ filter: /\.custom$/ }, async (args) => {
* const content = await Bun.file(args.path).text();
* return {
* contents: `export default ${JSON.stringify(content)}`,
* loader: 'js'
* };
* });
* }
* }
* ]
* });
* ```
* @example Enable bytecode generation for faster startup
* ```ts
* await Bun.build({
* entrypoints: ['./src/server.ts'],
* outdir: './dist',
* target: 'bun',
* format: 'cjs',
* bytecode: true
* });
* ```
* @example Add custom banner and footer to output files
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* banner: '"use client";\n// Built with Bun',
* footer: '// Generated on ' + new Date().toISOString()
* });
* ```
* @example Configure CDN public path for asset loading
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* publicPath: 'https://cdn.example.com/assets/',
* loader: {
* '.png': 'file',
* '.svg': 'file'
* }
* });
* ```
* @example Set up package export conditions for different environments
* ```ts
* await Bun.build({
* entrypoints: ['./src/index.tsx'],
* outdir: './dist',
* conditions: ['production', 'browser', 'module'],
* packages: 'external'
* });
* ```
*/
function build(config: BuildConfig): Promise<BuildOutput>;
/**
* A status that represents the outcome of a sent message.
@@ -2996,6 +3062,8 @@ declare module "bun" {
/**
* A fast WebSocket designed for servers.
*
* @category HTTP & Networking
*
* Features:
* - **Message compression** - Messages can be compressed
* - **Backpressure** - If the client is not ready to receive data, the server will tell you.
@@ -3264,6 +3332,8 @@ declare module "bun" {
/**
* Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve}
*
* @category HTTP & Networking
*
* @example
* ```ts
* import { websocket, serve } from "bun";
@@ -3971,6 +4041,8 @@ declare module "bun" {
*
* To start the server, see {@link serve}
*
* @category HTTP & Networking
*
* For performance, Bun pre-allocates most of the data for 2048 concurrent requests.
* That means starting a new server allocates about 500 KB of memory. Try to
* avoid starting and stopping the server often (unless it's a new instance of bun).
@@ -4270,6 +4342,8 @@ declare module "bun" {
*
* @param options - Server configuration options
*
* @category HTTP & Networking
*
* @example Basic Usage
* ```ts
* Bun.serve({
@@ -4600,6 +4674,11 @@ declare module "bun" {
type StringLike = string | { toString(): string };
/**
* Valid inputs for {@link color}
*
* @category Utilities
*/
type ColorInput =
| { r: number; g: number; b: number; a?: number }
| [number, number, number]
@@ -4614,6 +4693,9 @@ declare module "bun" {
/**
* Converts formats of colors
*
* @category Utilities
*
* @param input A value that could possibly be a color
* @param outputFormat An optional output format
*/
@@ -5033,6 +5115,8 @@ declare module "bun" {
* Resolve a `Promise` after milliseconds. This is like
* {@link setTimeout} except it returns a `Promise`.
*
* @category Utilities
*
* @param ms milliseconds to delay resolving the promise. This is a minimum
* number. It may take longer. If a {@link Date} is passed, it will sleep until the
* {@link Date} is reached.
@@ -5075,6 +5159,8 @@ declare module "bun" {
/**
* Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions)
*
* @category Utilities
*
* @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster
* @param hashInto optional `Uint8Array` to write the hash to. 32 bytes minimum.
*
@@ -5094,6 +5180,8 @@ declare module "bun" {
/**
* Hash `input` using [SHA-2 512/256](https://en.wikipedia.org/wiki/SHA-2#Comparison_of_SHA_functions)
*
* @category Utilities
*
* @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` will be faster
* @param encoding `DigestEncoding` to return the hash in
*
@@ -5471,6 +5559,11 @@ declare module "bun" {
readonly __ffi_function_callable: typeof import("bun:ffi").FFIFunctionCallableSymbol;
};
/**
* The builder object passed to `Bun.plugin`
*
* @category Bundler
*/
interface PluginBuilder {
/**
* Register a callback which will be invoked when bundling starts. When
@@ -5571,6 +5664,11 @@ declare module "bun" {
module(specifier: string, callback: () => OnLoadResult | Promise<OnLoadResult>): this;
}
/**
* A Bun plugin. Used for extending Bun's behavior at runtime, or with {@link Bun.build}
*
* @category Bundler
*/
interface BunPlugin {
/**
* Human-readable name of the plugin
@@ -5587,9 +5685,10 @@ declare module "bun" {
*
* If unspecified, it is assumed that the plugin is compatible with all targets.
*
* This field is not read by {@link Bun.plugin}
* This field is not read by {@link Bun.plugin}, only {@link Bun.build} and `bun build`
*/
target?: Target;
/**
* A function that will be called when the plugin is loaded.
*
@@ -6736,6 +6835,8 @@ declare module "bun" {
/**
* Spawn a new process
*
* @category Process Management
*
* ```js
* const subprocess = Bun.spawn({
* cmd: ["echo", "hello"],
@@ -6800,6 +6901,8 @@ declare module "bun" {
/**
* Spawn a new process
*
* @category Process Management
*
* ```js
* const {stdout} = Bun.spawnSync({
* cmd: ["echo", "hello"],

View File

@@ -13,6 +13,8 @@
* that convert JavaScript types to C types and back. Internally,
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*
* @category FFI
*/
declare module "bun:ffi" {
enum FFIType {
@@ -600,6 +602,8 @@ declare module "bun:ffi" {
* that convert JavaScript types to C types and back. Internally,
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*
* @category FFI
*/
function dlopen<Fns extends Record<string, FFIFunction>>(
name: string | import("bun").BunFile | URL,
@@ -1018,6 +1022,8 @@ declare module "bun:ffi" {
* // Do something with rawPtr
* }
* ```
*
* @category FFI
*/
function ptr(view: NodeJS.TypedArray | ArrayBufferLike | DataView, byteOffset?: number): Pointer;
@@ -1042,8 +1048,9 @@ declare module "bun:ffi" {
* thing to do safely. Passing an invalid pointer can crash the program and
* reading beyond the bounds of the pointer will crash the program or cause
* undefined behavior. Use with care!
*
* @category FFI
*/
class CString extends String {
/**
* Get a string from a UTF-8 encoded C string

View File

@@ -147,6 +147,8 @@ declare namespace HTMLRewriterTypes {
* });
* rewriter.transform(await fetch("https://remix.run"));
* ```
*
* @category HTML Manipulation
*/
declare class HTMLRewriter {
constructor();

View File

@@ -340,6 +340,8 @@ declare module "bun" {
/**
* Represents a file in an S3-compatible storage service.
* Extends the Blob interface for compatibility with web APIs.
*
* @category Cloud Storage
*/
interface S3File extends Blob {
/**
@@ -635,6 +637,8 @@ declare module "bun" {
* await bucket.write("data.json", JSON.stringify({hello: "world"}));
* const url = bucket.presign("file.pdf");
* await bucket.unlink("old.txt");
*
* @category Cloud Storage
*/
class S3Client {
prototype: S3Client;
@@ -820,6 +824,8 @@ declare module "bun" {
* A default instance of S3Client
*
* Pulls credentials from environment variables. Use `new Bun.S3Client()` if you need to explicitly set credentials.
*
* @category Cloud Storage
*/
var s3: S3Client;
}

View File

@@ -58,6 +58,8 @@ declare module "bun:sqlite" {
* ```ts
* const db = new Database("mydb.sqlite", {readonly: true});
* ```
*
* @category Database
*/
constructor(
filename?: string,
@@ -567,6 +569,8 @@ declare module "bun:sqlite" {
*
* This is returned by {@link Database.prepare} and {@link Database.query}.
*
* @category Database
*
* @example
* ```ts
* const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?");

View File

@@ -16,6 +16,8 @@
declare module "bun:test" {
/**
* -- Mocks --
*
* @category Testing
*/
export type Mock<T extends (...args: any[]) => any> = JestMock.Mock<T>;
@@ -168,6 +170,8 @@ declare module "bun:test" {
*
* @param label the label for the tests
* @param fn the function that defines the tests
*
* @category Testing
*/
export interface Describe {
(fn: () => void): void;
@@ -352,6 +356,8 @@ declare module "bun:test" {
* @param label the label for the test
* @param fn the test function
* @param options the test timeout or options
*
* @category Testing
*/
export interface Test {
(