@contrast/patcher
Advanced monkey patching: registers hooks to run before, around, and after functions, methods, and class constructors.
Usage
@contrast/agentify composes the patcher onto core as core.patcher.
// patch a method in place; returns the object
core.patcher.patch(obj, 'method', {
name: 'lib.obj.method',
patchType: 'assess-dataflow-source',
pre(data) {},
around(next, data) { return next(); },
post(data) {},
});
// patch a function (or class constructor) directly; returns the patched function
const patched = core.patcher.patch(fn, { name: 'lib.fn', patchType: 'protect-input-analysis', post(data) {} });
Options
name(required): identifies the patched function, e.g.'http.Server.prototype.emit'.patchType(required): the category of instrumentation, e.g.assess-dataflow-sourceorprotect-input-analysis.pre(data): runs before the original.around(next, data): wraps the original. Callnext()to run it (or the nextaroundhook) and return its result.post(data): runs after the original.data.resultholds the return value, and assigning to it changes what the caller receives.
Hook data includes args, obj (the this value), orig (the original
function), hooked (the patched function), name, and funcKey.
Hooks are keyed by `${patchType}:${name}`. Patching the same function again
with the same key is ignored, so different features can hook one function by
using different patchType values.
unpatch(fn, name, patchType) removes one hook, unwrap(fn) returns the
original function, and isContrastHooked(fn) reports whether a function is
patched. Type definitions are in lib/index.d.ts.