MwithStoreScope
Bun

method

diagnostics_channel.Channel.withStoreScope

data: ContextType

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.

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

Referenced types

interface 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.