index.d.cts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { AsyncLocalStorage } from 'node:async_hooks';
  2. interface UseContext<T> {
  3. /**
  4. * Get the current context. Throws if no context is set.
  5. */
  6. use: () => T;
  7. /**
  8. * Get the current context. Returns `null` when no context is set.
  9. */
  10. tryUse: () => T | null;
  11. /**
  12. * Set the context as Singleton Pattern.
  13. */
  14. set: (instance?: T, replace?: boolean) => void;
  15. /**
  16. * Clear current context.
  17. */
  18. unset: () => void;
  19. /**
  20. * Exclude a synchronous function with the provided context.
  21. */
  22. call: <R>(instance: T, callback: () => R) => R;
  23. /**
  24. * Exclude an asynchronous function with the provided context.
  25. * Requires installing the transform plugin to work properly.
  26. */
  27. callAsync: <R>(instance: T, callback: () => R | Promise<R>) => Promise<R>;
  28. }
  29. interface ContextOptions {
  30. asyncContext?: boolean;
  31. AsyncLocalStorage?: typeof AsyncLocalStorage;
  32. }
  33. declare function createContext<T = any>(opts?: ContextOptions): UseContext<T>;
  34. interface ContextNamespace {
  35. get: <T>(key: string, opts?: ContextOptions) => UseContext<T>;
  36. }
  37. declare function createNamespace<T = any>(defaultOpts?: ContextOptions): {
  38. get(key: string, opts?: ContextOptions): UseContext<T>;
  39. };
  40. declare const defaultNamespace: ContextNamespace;
  41. declare const getContext: <T>(key: string, opts?: ContextOptions) => UseContext<T>;
  42. declare const useContext: <T>(key: string, opts?: ContextOptions) => () => T;
  43. type AsyncFunction<T> = () => Promise<T>;
  44. declare function executeAsync<T>(function_: AsyncFunction<T>): [Promise<T>, () => void];
  45. declare function withAsyncContext<T = any>(function_: AsyncFunction<T>, transformed?: boolean): AsyncFunction<T>;
  46. export { type ContextNamespace, type ContextOptions, type UseContext, createContext, createNamespace, defaultNamespace, executeAsync, getContext, useContext, withAsyncContext };