Socket
Book a DemoInstallSign in
Socket

ctx-hook

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ctx-hook

A TypeScript library for property hooking within functions.

0.3.0
latest
Source
npmnpm
Version published
Weekly downloads
3
50%
Maintainers
1
Weekly downloads
 
Created
Source

ctx-hook

npm

Overview

ctx-hook is a TypeScript library that uses Node.js's asynchronous context tracking to enable property hooking that activates only within the asynchronous contexts of wrapper functions created by its API.

Example

import { useGlobalCtxHook, useCtxHook } from 'ctx-hook'

// Create a context hook for `global.Date` to travel to 1 day ago.
const { wrap, dispose } = useGlobalCtxHook('Date', Date0 => {
  const getTravelledNow = () => Date0.now() - 864e5
  const getTravelledDate = () => new Date0(getTravelledNow())
  const Date1 = new Proxy(Date0, {
    construct(_, args) {
      if (! args.length) return getTravelledDate()
      return new Date0(...args as [])
    },
    apply() {
      return getTravelledDate().toString()
    },
    get(_, prop: keyof DateConstructor) {
      if (prop === 'now') return getTravelledNow
      return Date0[prop]
    }
  })
  return Date1
})

// Define a function that outputs the current time twice.
const fn = async () => {
  console.log(Date.now())
  await new Promise(resolve => setTimeout(resolve, 0))
  console.log(Date.now())
}

// Wrap the function so that all access (sync or async) to `Date` will be hooked.
const fnTravelled = wrap(fn)

fnTravelled()

// Dispose the context hook to restore the original `Date`.
dispose()

FAQs

Package last updated on 11 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.