🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@types/node

Package Overview
Dependencies
Maintainers
1
Versions
2350
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@types/node - npm Package Compare versions

Comparing version
26.0.1
to
26.1.0
+486
node/ffi.d.ts
declare module "node:ffi" {
import { NonSharedBuffer } from "node:buffer";
interface FunctionSignature {
return?: ReturnType | undefined;
arguments?: readonly ArgumentType[] | undefined;
}
interface FunctionDefinitions {
[symbol: string]: FunctionSignature;
}
type CallbackFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]> = (
...args: { [K in keyof P]: ArgumentTypeMap[DataTypeMap[P[K]]] }
) => ReturnTypeMap[DataTypeMap[R]];
interface WrappedFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]>
extends CallbackFunction<R, P>
{
readonly pointer: bigint;
}
type CallbackFunctionFromSignature<T extends FunctionSignature> = CallbackFunction<
ReturnTypeFromFunctionSignature<T>,
ArgumentTypesFromFunctionSignature<T>
>;
type WrappedFunctionFromSignature<T extends FunctionSignature> = WrappedFunction<
ReturnTypeFromFunctionSignature<T>,
ArgumentTypesFromFunctionSignature<T>
>;
type WrappedFunctionsFromDefinitions<T extends FunctionDefinitions> = {
[K in keyof T]: WrappedFunctionFromSignature<T[K]>;
};
type ReturnTypeFromFunctionSignature<T extends FunctionSignature> = "return" extends keyof T
? T extends { return: infer R extends ReturnType } ? R : any
: "void";
type ArgumentTypesFromFunctionSignature<T extends FunctionSignature> = "arguments" extends keyof T
? T extends { arguments: infer P extends readonly ArgumentType[] } ? P : any[]
: [];
interface DynamicLibraryResult<T extends FunctionDefinitions> extends Disposable {
lib: DynamicLibrary;
functions: WrappedFunctionsFromDefinitions<T>;
}
/**
* The native shared library suffix for the current platform:
*
* * `'dylib'` on macOS
* * `'so'` on Unix-like platforms
* * `'dll'` on Windows
*
* This can be used to build portable library paths:
*
* ```js
* const { suffix } = require('node:ffi');
*
* const path = `libsqlite3.${suffix}`;
* ```
* @since v26.1.0
*/
const suffix: string;
/**
* Loads a dynamic library and resolves the requested function definitions.
*
* On Windows passing `null` is not supported.
*
* When `definitions` is omitted, `functions` is returned as an empty object until
* symbols are resolved explicitly.
*
* The returned object also implements the explicit resource management protocol,
* so it can be used with the `using` declaration. Disposing the returned
* object closes the library handle.
*
* ```js
* import { dlopen } from 'node:ffi';
*
* {
* using handle = dlopen('./mylib.so', {
* add_i32: { arguments: ['i32', 'i32'], return: 'i32' },
* });
* console.log(handle.functions.add_i32(20, 22));
* } // handle.lib.close() is invoked automatically here.
* ```
*
* ```js
* import { dlopen } from 'node:ffi';
*
* const { lib, functions } = dlopen('./mylib.so', {
* add_i32: { arguments: ['i32', 'i32'], return: 'i32' },
* string_length: { arguments: ['pointer'], return: 'u64' },
* });
*
* console.log(functions.add_i32(20, 22));
* ```
* @since v26.1.0
* @param path Path to a dynamic library, or `null` to resolve symbols
* from the current process image.
* @param definitions Symbol definitions to resolve immediately.
*/
function dlopen<const T extends FunctionDefinitions = {}>(
path: string | null,
definitions?: T,
): DynamicLibraryResult<T>;
/**
* Closes a dynamic library.
*
* This is equivalent to calling `handle.close()`.
* @since v26.1.0
*/
function dlclose(handle: DynamicLibrary): void;
/**
* Resolves a symbol address from a loaded library.
*
* This is equivalent to calling `handle.getSymbol(symbol)`.
* @since v26.1.0
*/
function dlsym(handle: DynamicLibrary, symbol: string): bigint;
/**
* @since v26.1.0
*/
class DynamicLibrary {
/**
* Loads the dynamic library without resolving any functions eagerly.
*
* On Windows passing `null` is not supported.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
* ```
* @param path Path to a dynamic library, or `null` to resolve symbols
* from the current process image.
*/
constructor(path: string | null);
/**
* The path used to load the library.
*/
readonly path: string;
/**
* An object containing previously resolved symbol addresses as `bigint` values.
*/
readonly symbols: { [symbol: string]: bigint };
/**
* Closes the library handle.
*
* `DynamicLibrary` implements the explicit resource management protocol, so a
* library instance can be managed with the `using` declaration. Leaving the
* enclosing scope invokes `library.close()` automatically.
*
* ```js
* import { DynamicLibrary } from 'node:ffi';
*
* {
* using lib = new DynamicLibrary('./mylib.so');
* // Use `lib` here; `lib.close()` is called when the block exits.
* }
* ```
*
* Calling `library.close()` (or disposing the library) more than once is a no-op.
*
* After a library has been closed:
*
* * Resolved function wrappers become invalid.
* * Further symbol and function resolution throws.
* * Registered callbacks are invalidated.
*
* Closing a library does not make previously exported callback pointers safe to
* reuse. Node.js does not track or revoke callback pointers that have already
* been handed to native code.
*
* If native code still holds a callback pointer after `library.close()` or after
* `library.unregisterCallback(pointer)`, invoking that pointer has undefined
* behavior, is not allowed, and is dangerous: it can crash the process, produce
* incorrect output, or corrupt memory. Native code must stop using callback
* addresses before the library is closed or before the callback is unregistered.
*
* Calling `library.close()` from one of the library's active callbacks is
* unsupported and dangerous. The callback must return before the library is
* closed.
*/
close(): void;
/**
* Calls `library.close()`. This allows `DynamicLibrary` instances to be used with
* the `using` declaration for automatic cleanup when the enclosing scope
* exits. It is a no-op on a library that has already been closed.
* @since v26.1.0
*/
[Symbol.dispose](): void;
/**
* Resolves a symbol and returns a callable JavaScript wrapper.
*
* The returned function has a `.pointer` property containing the native function
* address as a `bigint`.
*
* If the same symbol has already been resolved, requesting it again with a
* different signature throws.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
* const add = lib.getFunction('add_i32', {
* arguments: ['i32', 'i32'],
* return: 'i32',
* });
*
* console.log(add(20, 22));
* console.log(add.pointer);
* ```
*/
getFunction<const T extends FunctionSignature>(name: string, signature: T): WrappedFunctionFromSignature<T>;
/**
* When `definitions` is provided, resolves each named symbol and returns an
* object containing callable wrappers.
*
* When `definitions` is omitted, returns wrappers for all functions that have
* already been resolved on the library.
*/
getFunctions(): { [symbol: string]: WrappedFunction };
getFunctions<const T extends FunctionDefinitions>(definitions: T): WrappedFunctionsFromDefinitions<T>;
/**
* Resolves a symbol and returns its native address as a `bigint`.
*/
getSymbol(name: string): bigint;
/**
* Returns an object containing all previously resolved symbol addresses.
*/
getSymbols(): Record<string, bigint>;
/**
* Creates a native callback pointer backed by a JavaScript function.
*
* When `signature` is omitted, the callback uses a default `void ()` signature.
*
* The return value is the callback pointer address as a `bigint`. It can be
* passed to native functions expecting a callback pointer.
*
* ```js
* const { DynamicLibrary } = require('node:ffi');
*
* const lib = new DynamicLibrary('./mylib.so');
*
* const callback = lib.registerCallback(
* { arguments: ['i32'], return: 'i32' },
* (value) => value * 2,
* );
* ```
*
* Callbacks are subject to the following restrictions:
*
* * They must be invoked on the same system thread where they were created.
* * They must not throw exceptions.
* * They must not return promises.
* * They must return a value compatible with the declared return type.
* * They must not call `library.close()` on their owning library while running.
* * They must not unregister themselves while running.
*
* Closing the owning library or unregistering the currently executing callback
* from inside the callback is unsupported and dangerous. Doing so may crash the
* process, produce incorrect output, or corrupt memory.
*/
registerCallback(callback: () => void): bigint;
registerCallback<const T extends FunctionSignature>(
signature: T,
callback: CallbackFunctionFromSignature<T>,
): bigint;
/**
* Releases a callback previously created with `library.registerCallback()`.
*
* Calling `library.unregisterCallback(pointer)` for a callback that is currently
* executing is unsupported and dangerous. The callback must return before it is
* unregistered.
*
* After `library.unregisterCallback(pointer)` returns, invoking that callback
* pointer from native code has undefined behavior, is not allowed, and is
* dangerous: it can crash the process, produce incorrect output, or corrupt
* memory.
*/
unregisterCallback(pointer: bigint): void;
/**
* Keeps the callback strongly referenced by JavaScript.
*/
refCallback(pointer: bigint): void;
/**
* Allows the callback to become weakly referenced by JavaScript.
*
* If the callback function is later garbage collected, subsequent native
* invocations become a no-op. Non-void return values are zero-initialized before
* returning to native code.
*/
unrefCallback(pointer: bigint): void;
}
function getInt8(pointer: bigint, offset?: number): number;
function getUint8(pointer: bigint, offset?: number): number;
function getInt16(pointer: bigint, offset?: number): number;
function getUint16(pointer: bigint, offset?: number): number;
function getInt32(pointer: bigint, offset?: number): number;
function getUint32(pointer: bigint, offset?: number): number;
function getInt64(pointer: bigint, offset?: number): bigint;
function getUint64(pointer: bigint, offset?: number): bigint;
function getFloat32(pointer: bigint, offset?: number): number;
function getFloat64(pointer: bigint, offset?: number): number;
function setInt8(pointer: bigint, offset: number, value: number): void;
function setUint8(pointer: bigint, offset: number, value: number): void;
function setInt16(pointer: bigint, offset: number, value: number): void;
function setUint16(pointer: bigint, offset: number, value: number): void;
function setInt32(pointer: bigint, offset: number, value: number): void;
function setUint32(pointer: bigint, offset: number, value: number): void;
function setInt64(pointer: bigint, offset: number, value: number | bigint): void;
function setUint64(pointer: bigint, offset: number, value: number | bigint): void;
function setFloat32(pointer: bigint, offset: number, value: number): void;
function setFloat64(pointer: bigint, offset: number, value: number): void;
/**
* Reads a NUL-terminated UTF-8 string from native memory.
*
* If `pointer` is `0n`, `null` is returned.
*
* This function does not validate that `pointer` refers to readable memory or
* that the pointed-to data is terminated with `\0`. Passing an invalid pointer,
* a pointer to freed memory, or a pointer to bytes without a terminating NUL can
* read unrelated memory, crash the process, or produce truncated or garbled
* output.
* @since v26.1.0
*/
function toString(pointer: bigint): string | null;
/**
* Creates a `Buffer` from native memory.
*
* When `copy` is `true`, the returned `Buffer` owns its own copied memory.
* When `copy` is `false`, the returned `Buffer` references the original native
* memory directly.
*
* Using `copy: false` is a zero-copy escape hatch. The returned `Buffer` is a
* writable view onto foreign memory, so writes in JavaScript update the original
* native memory directly. The caller must guarantee that:
*
* * `pointer` remains valid for the entire lifetime of the returned `Buffer`.
* * `length` stays within the allocated native region.
* * no native code frees or repurposes that memory while JavaScript still uses
* the `Buffer`.
* * Memory protection is observed. For example, read-only memory pages must not
* be written to.
*
* If these guarantees are not met, reading or writing the `Buffer` can corrupt
* memory or crash the process.
* @since v26.1.0
* @param copy When `false`, creates a zero-copy view. **Default:** `true`.
*/
function toBuffer(pointer: bigint, length: number, copy?: boolean): NonSharedBuffer;
/**
* Creates an `ArrayBuffer` from native memory.
*
* When `copy` is `true`, the returned `ArrayBuffer` contains copied bytes.
* When `copy` is `false`, the returned `ArrayBuffer` references the original
* native memory directly.
*
* The same lifetime and bounds requirements described for
* `ffi.toBuffer(pointer, length, copy)` apply
* here. With `copy: false`, the
* returned `ArrayBuffer` is a zero-copy view of foreign memory and is only safe
* while that memory remains allocated, unchanged in layout, and valid for the
* entire exposed range.
* @since v26.1.0
* @param copy When `false`, creates a zero-copy view. **Default:** `true`.
*/
function toArrayBuffer(pointer: bigint, length: number, copy?: boolean): ArrayBuffer;
/**
* Copies a JavaScript string into native memory and appends a trailing NUL
* terminator.
*
* `length` must be large enough to hold the full encoded string plus the trailing
* NUL terminator. For UTF-16 and UCS-2 encodings, the trailing terminator uses
* two zero bytes.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
*
* `string` must be a JavaScript string. `encoding` must be a string.
* @since v26.1.0
* @param encoding **Default:** `'utf8'`.
*/
function exportString(string: string, pointer: bigint, length: number, encoding?: BufferEncoding): void;
/**
* Copies bytes from a `Buffer` into native memory.
*
* `length` must be at least `buffer.length`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
*
* `buffer` must be a Node.js `Buffer`.
* @since v26.1.0
*/
function exportBuffer(buffer: Buffer, pointer: bigint, length: number): void;
/**
* Copies bytes from an `ArrayBuffer` into native memory.
*
* `length` must be at least `arrayBuffer.byteLength`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
* @since v26.1.0
*/
function exportArrayBuffer(arrayBuffer: ArrayBuffer, pointer: bigint, length: number): void;
/**
* Copies bytes from an `ArrayBufferView` into native memory.
*
* `length` must be at least `arrayBufferView.byteLength`.
*
* `pointer` must refer to writable native memory with at least `length` bytes of
* available storage. This function does not allocate memory on its own.
* @since v26.1.0
*/
function exportArrayBufferView(arrayBufferView: NodeJS.ArrayBufferView, pointer: bigint, length: number): void;
/**
* Returns the raw memory address of JavaScript-managed byte storage.
*
* This is unsafe and dangerous. The returned pointer can become invalid if the
* underlying memory is detached, resized, transferred, or otherwise invalidated.
* Using stale pointers can cause memory corruption or process crashes.
* @since v26.1.0
*/
function getRawPointer(source: ArrayBuffer | NodeJS.ArrayBufferView): bigint;
type ReturnType = { [K in keyof DataTypeMap]: K }[keyof DataTypeMap];
type ArgumentType = Exclude<ReturnType, "void">;
interface DataTypeMap {
void: "void";
char: "number";
bool: "number";
i8: "number";
int8: "number";
u8: "number";
uint8: "number";
i16: "number";
int16: "number";
u16: "number";
uint16: "number";
i32: "number";
int32: "number";
u32: "number";
uint32: "number";
i64: "bigint";
int64: "bigint";
u64: "bigint";
uint64: "bigint";
float: "number";
f32: "number";
double: "number";
f64: "number";
pointer: "pointer";
ptr: "pointer";
function: "pointer";
buffer: "pointer";
arraybuffer: "pointer";
string: "pointer";
str: "pointer";
}
interface ArgumentTypeMap {
"number": number;
"bigint": bigint;
"pointer": bigint | string | ArrayBuffer | NodeJS.ArrayBufferView | null;
}
interface ReturnTypeMap {
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
"void": void;
"number": number;
"bigint": bigint;
"pointer": bigint | null;
}
enum types {
VOID = "void",
POINTER = "pointer",
BUFFER = "buffer",
ARRAY_BUFFER = "arraybuffer",
FUNCTION = "function",
BOOL = "bool",
CHAR = "char",
STRING = "string",
FLOAT = "float",
DOUBLE = "double",
INT_8 = "int8",
UINT_8 = "uint8",
INT_16 = "int16",
UINT_16 = "uint16",
INT_32 = "int32",
UINT_32 = "uint32",
INT_64 = "int64",
UINT_64 = "uint64",
FLOAT_32 = "float32",
FLOAT_64 = "float64",
}
}
+237
-3

@@ -106,2 +106,32 @@ declare module "node:diagnostics_channel" {

/**
* Creates a {@link BoundedChannel} wrapper for the given channels. If a name is
* given, the corresponding channels will be created in the form of
* `tracing:${name}:${eventType}` where `eventType` is `start` or `end`.
*
* A `BoundedChannel` is a simplified version of {@link TracingChannel} that only
* traces synchronous operations. It only has `start` and `end` events, without
* `asyncStart`, `asyncEnd`, or `error` events, making it suitable for tracing
* operations that don't involve asynchronous continuations or error handling.
*
* ```js
* import { boundedChannel, channel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* // or...
*
* const wc2 = boundedChannel({
* start: channel('tracing:my-operation:start'),
* end: channel('tracing:my-operation:end'),
* });
* ```
* @since v26.1.0
* @experimental
* @param nameOrChannels Channel name or
* object containing all the [BoundedChannel Channels](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#boundedchannel-channels)
*/
function boundedChannel<ContextType extends object = object, StoreType = ContextType>(
nameOrChannels: string | BoundedChannelCollection<ContextType, StoreType>,
): BoundedChannel<ContextType, StoreType>;
/**
* The class `Channel` represents an individual named channel within the data

@@ -116,2 +146,3 @@ * pipeline. It is used to track subscribers and to publish messages when there

class Channel<ContextType = any, StoreType = ContextType> {
private constructor();
readonly name: string | symbol;

@@ -137,3 +168,2 @@ /**

readonly hasSubscribers: boolean;
private constructor(name: string | symbol);
/**

@@ -283,3 +313,44 @@ * Publish a message to any subscribers to the channel. This will trigger

): Result;
/**
* Creates a disposable scope that binds the given data to any AsyncLocalStorage
* instances bound to the channel and publishes it to subscribers. The scope
* automatically restores the previous storage contexts when disposed.
*
* This method enables the use of JavaScript's explicit resource management
* (`using` syntax with `Symbol.dispose`) to manage store contexts without
* closure wrapping.
*
* ```js
* import { channel } from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
* const ch = channel('my-channel');
*
* ch.bindStore(store, (message) => {
* return { ...message, timestamp: Date.now() };
* });
*
* {
* using scope = ch.withStoreScope({ request: 'data' });
* // Store is entered, data is published
* console.log(store.getStore()); // { request: 'data', timestamp: ... }
* }
* // Store is automatically restored on scope exit
* ```
* @since v26.1.0
* @experimental
*/
withStoreScope(data: ContextType): RunStoresScope;
}
/**
* The class `RunStoresScope` represents a disposable scope created by
* `channel.withStoreScope(data)`. It manages the lifecycle of store
* contexts and ensures they are properly restored when the scope exits.
*
* The scope must be used with the `using` syntax to ensure proper disposal.
* @since v26.1.0
* @experimental
*/
interface RunStoresScope extends Disposable {}
interface TracingChannelSubscribers<ContextType extends object> {

@@ -362,3 +433,3 @@ start: (message: ContextType) => void;

*/
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
subscribe(subscribers: NodeJS.PartialOptions<TracingChannelSubscribers<ContextType>>): void;
/**

@@ -397,3 +468,3 @@ * Helper to unsubscribe a collection of functions from the corresponding channels.

*/
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
unsubscribe(subscribers: NodeJS.PartialOptions<TracingChannelSubscribers<ContextType>>): void;
/**

@@ -563,2 +634,165 @@ * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.

}
interface BoundedChannelSubscribers<ContextType extends object> {
start: (message: ContextType) => void;
end: (message: ContextType) => void;
}
interface BoundedChannelCollection<ContextType extends object = object, StoreType = ContextType> {
start: Channel<ContextType, StoreType>;
end: Channel<ContextType, StoreType>;
}
/**
* The class `BoundedChannel` is a simplified version of {@link TracingChannel} that
* only traces synchronous operations. It consists of two channels (`start` and
* `end`) instead of five, omitting the `asyncStart`, `asyncEnd`, and `error`
* events. This makes it suitable for tracing operations that don't involve
* asynchronous continuations or error handling.
*
* Like `TracingChannel`, it is recommended to create and reuse a single
* `BoundedChannel` at the top-level of the file rather than creating them
* dynamically.
* @since v26.1.0
* @experimental
*/
interface BoundedChannel<ContextType extends object = object, StoreType = ContextType>
extends BoundedChannelCollection<ContextType, StoreType>
{
/**
* Check if any of the `start` or `end` channels have subscribers.
*
* ```js
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* if (wc.hasSubscribers) {
* // There are subscribers, perform traced operation
* }
* ```
* @since v26.1.0
*/
readonly hasSubscribers: boolean;
/**
* Subscribe to the bounded channel events. This is equivalent to calling
* [`channel.subscribe(onMessage)`][] on each channel individually.
*
* ```mjs
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* wc.subscribe({
* start(message) {
* // Handle start
* },
* end(message) {
* // Handle end
* },
* });
* ```
* @since v26.1.0
* @param handlers Set of channel subscribers
*/
subscribe(handlers: NodeJS.PartialOptions<BoundedChannelSubscribers<ContextType>>): void;
/**
* Unsubscribe from the bounded channel events. This is equivalent to calling
* [`channel.unsubscribe(onMessage)`][] on each channel individually.
*
* ```js
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* const handlers = {
* start(message) {},
* end(message) {},
* };
*
* wc.subscribe(handlers);
* wc.unsubscribe(handlers);
* ```
* @since v26.1.0
* @param handlers Set of channel subscribers
* @returns `true` if all handlers were successfully unsubscribed,
* `false` otherwise.
*/
unsubscribe(handlers: NodeJS.PartialOptions<BoundedChannelSubscribers<ContextType>>): boolean;
/**
* Trace a synchronous function call. This will produce a `start` event and `end`
* event around the execution. This runs the given function using
* [`channel.runStores(context, ...)`][] on the `start` channel which ensures all
* events have any bound stores set to match this trace context.
*
* ```js
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* const result = wc.run({ operationId: '123' }, () => {
* // Perform operation
* return 42;
* });
* ```
* @since v26.1.0
* @param context Shared object to correlate events through
* @param fn Function to wrap a trace around
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @returns The return value of the given function
*/
run<ThisArg = any, Args extends any[] = any[], Result = any>(
fn: (this: ThisArg, ...args: Args) => Result,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): Result;
/**
* Create a disposable scope for tracing a synchronous operation using JavaScript's
* explicit resource management (`using` syntax). The scope automatically publishes
* `start` and `end` events, enters bound stores, and handles cleanup when disposed.
*
* ```js
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* const context = { operationId: '123' };
* {
* using scope = wc.withScope(context);
* // Stores are entered, start event is published
*
* // Perform work and set result on context
* context.result = 42;
* }
* // End event is published, stores are restored automatically
* ```
* @since v26.1.0
* @param context Shared object to correlate events through
* @returns Disposable scope object
*/
withScope(context: ContextType): BoundedChannelScope;
}
/**
* The class `BoundedChannelScope` represents a disposable scope created by
* `boundedChannel.withScope(context)`. It manages the lifecycle of a traced
* operation, automatically publishing events and managing store contexts.
*
* The scope must be used with the `using` syntax to ensure proper disposal.
*
* ```js
* import { boundedChannel } from 'node:diagnostics_channel';
*
* const wc = boundedChannel('my-operation');
*
* const context = {};
* {
* using scope = wc.withScope(context);
* // Start event is published, stores are entered
* context.result = performOperation();
* // End event is automatically published at end of block
* }
* ```
* @since v26.1.0
* @experimental
*/
interface BoundedChannelScope extends Disposable {}
}

@@ -565,0 +799,0 @@ declare module "diagnostics_channel" {

+1
-1

@@ -37,3 +37,3 @@ declare module "node:dns" {

/**
* When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted
* When `verbatim`, the resolved addresses are returned unsorted. When `ipv4first`, the resolved addresses are sorted
* by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6

@@ -40,0 +40,0 @@ * addresses before IPv4 addresses. Default value is configurable using

@@ -1442,2 +1442,5 @@ declare module "node:fs/promises" {

/**
* When `followSymlinks` is enabled, detected symbolic link cycles are not
* traversed recursively.
*
* ```js

@@ -1444,0 +1447,0 @@ * import { glob } from 'node:fs/promises';

@@ -69,2 +69,3 @@ /**

/// <reference path="events.d.ts" />
/// <reference path="ffi.d.ts" />
/// <reference path="fs.d.ts" />

@@ -71,0 +72,0 @@ /// <reference path="fs/promises.d.ts" />

{
"name": "@types/node",
"version": "26.0.1",
"version": "26.1.0",
"description": "TypeScript definitions for node",

@@ -153,4 +153,4 @@ "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",

"peerDependencies": {},
"typesPublisherContentHash": "a354aaa75dcea5eab474337cc3c7f8ab35ebed8c28d8cdb987dc31049b0fc0c6",
"typesPublisherContentHash": "bac6fe2369bbd2e0f2cf6643373e8c398ed66b886a72749c8d1fb0b9b60031ab",
"typeScriptVersion": "5.6"
}

@@ -126,2 +126,9 @@ declare module "node:quic" {

}
interface SNIEntry {
keys: KeyObject | readonly KeyObject[];
certs: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray<ArrayBuffer | NodeJS.ArrayBufferView>;
ca?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray<ArrayBuffer | NodeJS.ArrayBufferView> | undefined;
crl?: ArrayBuffer | NodeJS.ArrayBufferView | ReadonlyArray<ArrayBuffer | NodeJS.ArrayBufferView> | undefined;
verifyPrivateKey?: boolean | undefined;
}
/**

@@ -137,8 +144,21 @@ * @since v23.8.0

/**
* The ALPN protocol identifier.
* @since v23.8.0
* The ALPN (Application-Layer Protocol Negotiation) identifier(s).
*
* For **client** sessions, this is a single string specifying the protocol
* the client wants to use (e.g. `'h3'`).
*
* For **server** sessions, this is an array of protocol names in preference
* order that the server supports (e.g. `['h3', 'h3-29']`). During the TLS
* handshake, the server selects the first protocol from its list that the
* client also supports.
*
* The negotiated ALPN determines which Application implementation is used
* for the session. `'h3'` and `'h3-*'` variants select the HTTP/3
* application; all other values select the default application.
* @since v26.1.0
*/
alpn?: string | undefined;
alpn?: string | readonly string[] | undefined;
/**
* The CA certificates to use for sessions.
* The CA certificates to use for client sessions. For server sessions, CA
* certificates are specified per-identity in the `sessionOptions.sni` map.
* @since v23.8.0

@@ -156,3 +176,4 @@ */

/**
* The TLS certificates to use for sessions.
* The TLS certificates to use for client sessions. For server sessions,
* certificates are specified per-identity in the `sessionOptions.sni` map.
* @since v23.8.0

@@ -167,3 +188,4 @@ */

/**
* The CRL to use for sessions.
* The CRL to use for client sessions. For server sessions, CRLs are specified
* per-identity in the `sessionOptions.sni` map.
* @since v23.8.0

@@ -183,3 +205,4 @@ */

/**
* The TLS crypto keys to use for sessions.
* The TLS crypto keys to use for client sessions. For server sessions,
* keys are specified per-identity in the `sessionOptions.sni` map.
* @since v23.8.0

@@ -232,7 +255,34 @@ */

/**
* The peer server name to target.
* @since v23.8.0
* The peer server name to target (SNI). Defaults to `'localhost'`.
* @since v26.1.0
*/
sni?: string | undefined;
servername?: string | undefined;
/**
* An object mapping host names to TLS identity options for Server Name
* Indication (SNI) support. This is required for server sessions. The
* special key `'*'` specifies the default/fallback identity used when
* no other host name matches. Each entry may contain:
*
* ```js
* const endpoint = await listen(callback, {
* sni: {
* '*': { keys: [defaultKey], certs: [defaultCert] },
* 'api.example.com': { keys: [apiKey], certs: [apiCert] },
* 'www.example.com': { keys: [wwwKey], certs: [wwwCert], ca: [customCA] },
* },
* });
* ```
*
* Shared TLS options (such as `ciphers`, `groups`, `keylog`, and `verifyClient`)
* are specified at the top level of the session options and apply to all
* identities. Each SNI entry overrides only the per-identity certificate
* fields.
*
* The SNI map can be replaced at runtime using `endpoint.setSNIContexts()`,
* which atomically swaps the map for new sessions while existing sessions
* continue to use their original identity.
* @since v26.1.0
*/
sni?: Record<string, SNIEntry> | undefined;
/**
* True to enable TLS tracing output.

@@ -258,3 +308,5 @@ * @since v23.8.0

/**
* True to require private key verification.
* True to require private key verification for client sessions. For server
* sessions, this option is specified per-identity in the
* `sessionOptions.sni` map.
* @since v23.8.0

@@ -416,2 +468,5 @@ */

}
interface SetSNIContextsOptions {
replace?: boolean | undefined;
}
/**

@@ -480,2 +535,28 @@ * A `QuicEndpoint` encapsulates the local UDP-port binding for QUIC. It can be

/**
* True if the endpoint is actively listening for incoming connections. Read only.
* @since v26.1.0
*/
readonly listening: boolean;
/**
* Replaces or updates the SNI TLS contexts for this endpoint. This allows
* changing the TLS identity (key/certificate) used for specific host names
* without restarting the endpoint. Existing sessions are unaffected — only
* new sessions will use the updated contexts.
*
* ```js
* endpoint.setSNIContexts({
* 'api.example.com': { keys: [newApiKey], certs: [newApiCert] },
* });
*
* // Replace the entire SNI map
* endpoint.setSNIContexts({
* 'api.example.com': { keys: [newApiKey], certs: [newApiCert] },
* }, { replace: true });
* ```
* @since v26.1.0
* @param entries An object mapping host names to TLS identity options.
* Each entry must include `keys` and `certs`.
*/
setSNIContexts(entries: Record<string, SNIEntry>, options?: SetSNIContextsOptions): void;
/**
* The statistics collected for an active session. Read only.

@@ -482,0 +563,0 @@ * @since v23.8.0

@@ -11,3 +11,3 @@ # Installation

### Additional Details
* Last updated: Wed, 24 Jun 2026 20:32:59 GMT
* Last updated: Wed, 01 Jul 2026 11:03:38 GMT
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)

@@ -14,0 +14,0 @@

@@ -161,2 +161,9 @@ declare module "node:sqlite" {

}
interface DeserializeOptions {
/**
* Name of the database to deserialize into.
* @default 'main'
*/
dbName?: string | undefined;
}
interface FunctionOptions {

@@ -450,2 +457,50 @@ /**

/**
* Serializes the database into a binary representation, returned as a
* `Uint8Array`. This is useful for saving, cloning, or transferring an in-memory
* database. This method is a wrapper around [`sqlite3_serialize()`](https://sqlite.org/c3ref/serialize.html).
*
* ```js
* import { DatabaseSync } from 'node:sqlite';
*
* const db = new DatabaseSync(':memory:');
* db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
* db.exec("INSERT INTO t VALUES (1, 'hello')");
* const buffer = db.serialize();
* console.log(buffer.length); // Prints the byte length of the database
* ```
* @since v26.1.0
* @param dbName Name of the database to serialize. This can be `'main'`
* (the default primary database) or any other database that has been added with
* [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). **Default:** `'main'`.
* @returns A binary representation of the database.
*/
serialize(dbName?: string): NodeJS.NonSharedUint8Array;
/**
* Loads a serialized database into this connection, replacing the current
* database. The deserialized database is writable. Existing prepared statements
* are finalized before deserialization is attempted, even if the operation
* subsequently fails. This method is a wrapper around
* [`sqlite3_deserialize()`](https://sqlite.org/c3ref/deserialize.html).
*
* ```js
* import { DatabaseSync } from 'node:sqlite';
*
* const original = new DatabaseSync(':memory:');
* original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)');
* original.exec("INSERT INTO t VALUES (1, 'hello')");
* const buffer = original.serialize();
* original.close();
*
* const clone = new DatabaseSync(':memory:');
* clone.deserialize(buffer);
* console.log(clone.prepare('SELECT value FROM t').get());
* // Prints: { value: 'hello' }
* ```
* @since v26.1.0
* @param buffer A binary representation of a database, such as the
* output of `database.serialize()`.
* @param options Optional configuration for the deserialization.
*/
deserialize(buffer: Uint8Array, options?: DeserializeOptions): void;
/**
* Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper

@@ -452,0 +507,0 @@ * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html).

declare module "node:stream/iter" {
import { Abortable } from "node:events";
import { Readable, Writable } from "node:stream";
// Symbols and custom typedefs

@@ -265,2 +267,150 @@ const broadcastProtocol: unique symbol;

}
/**
* Converts a classic Readable stream (or duck-typed equivalent) into a
* stream/iter async iterable source that can be passed to `from()`,
* `pull()`, `text()`, etc.
*
* If the object implements the `toAsyncStreamable` protocol (as
* `stream.Readable` does), that protocol is used. Otherwise, the function
* duck-types on `read()` and `on()` (EventEmitter) and wraps the stream with
* a batched async iterator.
*
* The result is cached per instance -- calling `fromReadable()` twice with the
* same stream returns the same iterable.
*
* For object-mode or encoded Readable streams, chunks are automatically
* normalized to `Uint8Array`.
*
* ```js
* import { Readable } from 'node:stream';
* import { fromReadable, text } from 'node:stream/iter';
*
* const readable = new Readable({
* read() { this.push('hello world'); this.push(null); },
* });
*
* const result = await text(fromReadable(readable));
* console.log(result); // 'hello world'
* ```
* @since v26.1.0
* @experimental
* @param readable A classic Readable stream or any object
* with `read()` and `on()` methods.
* @returns A stream/iter async iterable source.
*/
function fromReadable(readable: NodeJS.ReadableStream): ByteReadableStream;
interface FromWritableOptions {
backpressure?: BackpressurePolicy | undefined;
}
/**
* Creates a stream/iter Writer adapter from a classic Writable stream (or
* duck-typed equivalent). The adapter can be passed to `pipeTo()` as a
* destination.
*
* Since all writes on a classic Writable are fundamentally asynchronous,
* the synchronous Writer methods (`writeSync`, `writevSync`, `endSync`) always
* return `false` or `-1`, deferring to the async path. The per-write
* `options.signal` parameter from the Writer interface is also ignored.
*
* The result is cached per instance -- calling `fromWritable()` twice with the
* same stream returns the same Writer.
*
* For duck-typed streams that do not expose `writableHighWaterMark`,
* `writableLength`, or similar properties, sensible defaults are used.
* Object-mode writables (if detectable) are rejected since the Writer
* interface is bytes-only.
*
* ```js
* import { Writable } from 'node:stream';
* import { from, fromWritable, pipeTo } from 'node:stream/iter';
*
* const writable = new Writable({
* write(chunk, encoding, cb) { console.log(chunk.toString()); cb(); },
* });
*
* await pipeTo(from('hello world'),
* fromWritable(writable, { backpressure: 'block' }));
* ```
* @since v26.1.0
* @experimental
* @param writable A classic Writable stream or any object
* with `write()` and `on()` methods.
* @returns A stream/iter Writer adapter.
*/
function fromWritable(writable: NodeJS.WritableStream, options?: FromWritableOptions): Writer;
interface ToReadableOptions extends Abortable {
highWaterMark?: number | undefined;
}
/**
* Creates a byte-mode `stream.Readable` from an `AsyncIterable<Uint8Array[]>`
* (the native batch format used by the stream/iter API). Each `Uint8Array` in a
* yielded batch is pushed as a separate chunk into the Readable.
*
* ```js
* import { createWriteStream } from 'node:fs';
* import { from, pull, toReadable } from 'node:stream/iter';
* import { compressGzip } from 'node:zlib/iter';
*
* const source = pull(from('hello world'), compressGzip());
* const readable = toReadable(source);
*
* readable.pipe(createWriteStream('output.gz'));
* ```
* @since v26.1.0
* @experimental
* @param source An `AsyncIterable<Uint8Array[]>` source, such as
* the return value of `pull()` or `from()`.
*/
function toReadable(source: Source, options?: ToReadableOptions): Readable;
interface ToReadableSyncOptions {
highWaterMark?: number | undefined;
}
/**
* Creates a byte-mode `stream.Readable` from a synchronous
* `Iterable<Uint8Array[]>`. The `_read()` method pulls from the iterator
* synchronously, so data is available immediately via `readable.read()`.
*
* ```js
* import { fromSync, toReadableSync } from 'node:stream/iter';
*
* const source = fromSync('hello world');
* const readable = toReadableSync(source);
*
* console.log(readable.read().toString()); // 'hello world'
* ```
* @since v26.1.0
* @experimental
* @param source An `Iterable<Uint8Array[]>` source, such as the
* return value of `pullSync()` or `fromSync()`.
*/
function toReadableSync(source: SyncSource, options?: ToReadableSyncOptions): Readable;
/**
* Creates a classic `stream.Writable` backed by a stream/iter Writer.
*
* Each `_write()` / `_writev()` call attempts the Writer's synchronous method
* first (`writeSync` / `writevSync`), falling back to the async method if the
* sync path returns `false` or throws. Similarly, `_final()` tries `endSync()`
* before `end()`. When the sync path succeeds, the callback is deferred via
* `queueMicrotask` to preserve the async resolution contract.
*
* The Writable's `highWaterMark` is set to `Number.MAX_SAFE_INTEGER` to
* effectively disable its internal buffering, allowing the underlying Writer
* to manage backpressure directly.
*
* ```js
* import { push, toWritable } from 'node:stream/iter';
*
* const { writer, readable } = push();
* const writable = toWritable(writer);
*
* writable.write('hello');
* writable.end();
* ```
* @since v26.1.0
* @experimental
* @param writer A stream/iter Writer. Only the `write()` method is
* required; `end()`, `fail()`, `writeSync()`, `writevSync()`, `endSync()`,
* and `writev()` are optional.
*/
function toWritable(writer: PartialWriter): Writable;
namespace Stream {

@@ -267,0 +417,0 @@ export {

@@ -71,2 +71,3 @@ /**

/// <reference path="../events.d.ts" />
/// <reference path="../ffi.d.ts" />
/// <reference path="../fs.d.ts" />

@@ -73,0 +74,0 @@ /// <reference path="../fs/promises.d.ts" />

@@ -71,2 +71,3 @@ /**

/// <reference path="../events.d.ts" />
/// <reference path="../ffi.d.ts" />
/// <reference path="../fs.d.ts" />

@@ -73,0 +74,0 @@ /// <reference path="../fs/promises.d.ts" />

@@ -416,2 +416,17 @@ declare module "node:v8" {

/**
* @since v26.1.0
*/
interface SyncHeapProfileHandle {
/**
* Stopping collecting the profile and return the profile data.
* @since v26.1.0
*/
stop(): string;
/**
* Stopping collecting the profile and the profile will be discarded.
* @since v26.1.0
*/
[Symbol.dispose](): void;
}
/**
* @since v24.8.0

@@ -448,2 +463,13 @@ */

}
interface CPUProfileOptions {
/**
* Requested sampling interval in milliseconds. **Default:** `0`.
*/
sampleInterval?: number | undefined;
/**
* Maximum number of samples to keep before older
* entries are discarded. **Default:** `4294967295`.
*/
maxBufferSize?: number | undefined;
}
/**

@@ -454,3 +480,3 @@ * Starting a CPU profile then return a `SyncCPUProfileHandle` object.

* ```js
* const handle = v8.startCpuProfile();
* const handle = v8.startCpuProfile({ sampleInterval: 1, maxBufferSize: 10_000 });
* const profile = handle.stop();

@@ -461,4 +487,60 @@ * console.log(profile);

*/
function startCpuProfile(): SyncCPUProfileHandle;
function startCpuProfile(options?: CPUProfileOptions): SyncCPUProfileHandle;
interface HeapProfileOptions {
/**
* The average sampling interval in bytes.
* **Default:** `524288` (512 KiB).
*/
sampleInterval?: number | undefined;
/**
* The maximum stack depth for samples.
* **Default:** `16`.
*/
stackDepth?: number | undefined;
/**
* Force garbage collection before taking the profile.
* **Default:** `false`.
*/
forceGC?: boolean | undefined;
/**
* Include objects collected
* by major GC. **Default:** `false`.
*/
includeObjectsCollectedByMajorGC?: boolean | undefined;
/**
* Include objects collected
* by minor GC. **Default:** `false`.
*/
includeObjectsCollectedByMinorGC?: boolean | undefined;
}
/**
* Starting a heap profile then return a `SyncHeapProfileHandle` object.
* This API supports `using` syntax.
*
* ```js
* import v8 from 'node:v8';
*
* const handle = v8.startHeapProfile();
* const profile = handle.stop();
* console.log(profile);
* ```
*
* With custom parameters:
*
* ```js
* import v8 from 'node:v8';
*
* const handle = v8.startHeapProfile({
* sampleInterval: 1024,
* stackDepth: 8,
* forceGC: true,
* includeObjectsCollectedByMajorGC: true,
* });
* const profile = handle.stop();
* console.log(profile);
* ```
* @since v26.1.0
*/
function startHeapProfile(options?: HeapProfileOptions): SyncHeapProfileHandle;
/**
* V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.

@@ -465,0 +547,0 @@ * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;

@@ -13,3 +13,3 @@ declare module "node:worker_threads" {

import { URL } from "node:url";
import { CPUProfileHandle, HeapInfo, HeapProfileHandle } from "node:v8";
import { CPUProfileHandle, CPUProfileOptions, HeapInfo, HeapProfileHandle, HeapProfileOptions } from "node:v8";
import { Context } from "node:vm";

@@ -263,3 +263,3 @@ import { MessageEvent } from "undici-types";

* worker.on('online', async () => {
* const handle = await worker.startCpuProfile();
* const handle = await worker.startCpuProfile({ sampleInterval: 1 });
* const profile = await handle.stop();

@@ -288,3 +288,3 @@ * console.log(profile);

*/
startCpuProfile(): Promise<CPUProfileHandle>;
startCpuProfile(options?: CPUProfileOptions): Promise<CPUProfileHandle>;
/**

@@ -295,6 +295,6 @@ * Starting a Heap profile then return a Promise that fulfills with an error

* ```js
* const { Worker } = require('node:worker_threads');
* import { Worker } from 'node:worker_threads';
*
* const worker = new Worker(`
* const { parentPort } = require('worker_threads');
* const { parentPort } = require('node:worker_threads');
* parentPort.on('message', () => {});

@@ -314,3 +314,3 @@ * `, { eval: true });

* ```js
* const { Worker } = require('node:worker_threads');
* import { Worker } from 'node:worker_threads';
*

@@ -327,4 +327,5 @@ * const w = new Worker(`

* ```
* @since v24.9.0
*/
startHeapProfile(): Promise<HeapProfileHandle>;
startHeapProfile(options?: HeapProfileOptions): Promise<HeapProfileHandle>;
/**

@@ -331,0 +332,0 @@ * Calls `worker.terminate()` when the dispose scope is exited.

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

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

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

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

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

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

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

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