The tapable package exposes many Hook classes, which can be used to create hooks for plugins.
const {
AsyncParallelBailHook,
AsyncParallelHook,
AsyncSeriesBailHook,
AsyncSeriesHook,
AsyncSeriesWaterfallHook,
SyncBailHook,
SyncHook,
SyncLoopHook,
SyncWaterfallHook
} = require("tapable");
npm install --save tapable
All Hook constructors take one optional argument, which is a list of argument names as strings.
const hook = new SyncHook(["arg1", "arg2", "arg3"]);
The best practice is to expose all hooks of a class in a hooks property:
class Car {
constructor() {
this.hooks = {
accelerate: new SyncHook(["newSpeed"]),
brake: new SyncHook(),
calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"])
};
}
/* ... */
}
Other people can now use these hooks:
const myCar = new Car();
// Use the tap method to add a consumer (plugin)
myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on());
It's required to pass a name to identify the plugin/reason.
You may receive arguments:
myCar.hooks.accelerate.tap("LoggerPlugin", (newSpeed) =>
console.log(`Accelerating to ${newSpeed}`)
);
For sync hooks, tap is the only valid method to add a plugin. Async hooks also support async plugins:
myCar.hooks.calculateRoutes.tapPromise(
"GoogleMapsPlugin",
(source, target, routesList) =>
// return a promise
google.maps.findRoute(source, target).then((route) => {
routesList.add(route);
})
);
myCar.hooks.calculateRoutes.tapAsync(
"BingMapsPlugin",
(source, target, routesList, callback) => {
bing.findRoute(source, target, (err, route) => {
if (err) return callback(err);
routesList.add(route);
// call the callback
callback();
});
}
);
// You can still use sync plugins
myCar.hooks.calculateRoutes.tap(
"CachedRoutesPlugin",
(source, target, routesList) => {
const cachedRoute = cache.get(source, target);
if (cachedRoute) routesList.add(cachedRoute);
}
);
The class declaring these hooks needs to call them:
class Car {
/**
* You won't get returned value from SyncHook or AsyncParallelHook,
* to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively
*/
setSpeed(newSpeed) {
// following call returns undefined even when you returned values
this.hooks.accelerate.call(newSpeed);
}
useNavigationSystemPromise(source, target) {
const routesList = new List();
return this.hooks.calculateRoutes
.promise(source, target, routesList)
.then((res) =>
// res is undefined for AsyncParallelHook
routesList.getRoutes()
);
}
useNavigationSystemAsync(source, target, callback) {
const routesList = new List();
this.hooks.calculateRoutes.callAsync(source, target, routesList, (err) => {
if (err) return callback(err);
callback(null, routesList.getRoutes());
});
}
}
The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on:
This ensures fastest possible execution. See Code generation for more details on the runtime compilation.
A plugin registers a callback on a hook using one of the tap* methods. The hook type determines which of these are valid (see Hook classes):
hook.tap(nameOrOptions, fn) — register a synchronous callback.hook.tapAsync(nameOrOptions, fn) — register a callback-based async callback. The last argument passed to fn is a node-style callback (err, result).hook.tapPromise(nameOrOptions, fn) — register a promise-returning async callback. If fn returns something that is not thenable, the hook throws.The first argument can be either a string (the plugin name) or an options object that also allows influencing the order in which taps run:
hook.tap(
{
name: "MyPlugin",
stage: -10, // lower stages run earlier, default is 0
before: "OtherPlugin" // run before a named tap (string or string[])
},
(...args) => {
/* ... */
}
);
| Option | Type | Description |
|---|---|---|
name |
string |
Required. Identifies the tap for debugging, interceptors, and the before option. |
stage |
number |
Defaults to 0. Taps with a lower stage run before taps with a higher stage. Taps with the same stage run in registration order. |
before |
string | string[] |
The tap is inserted before the named tap(s). Unknown names are ignored. Combined with stage, before wins for the taps it targets; other taps are still ordered by stage. |
The name is also used by some ecosystems (like webpack) for profiling and error messages. Within a single tap registration, later interceptors' register hooks may still replace the tap object (see Interception).
hook.withOptions(options)withOptions returns a facade around the hook whose tap* methods automatically merge options into every registration. It is useful for libraries that want to pre-configure a stage or before for all the taps they add:
const lateHook = myCar.hooks.accelerate.withOptions({ stage: 10 });
lateHook.tap("LogAfterOthers", (speed) => console.log("final speed", speed));
// equivalent to: myCar.hooks.accelerate.tap({ name: "LogAfterOthers", stage: 10 }, ...)
The returned object does not expose the call* methods, so it is safe to hand out to plugins.
A runnable example showing how withOptions influences tap ordering:
const { SyncHook } = require("tapable");
const hook = new SyncHook(["value"]);
hook.tap("Default", (v) => console.log("default", v));
// Pre-configure stage: 10 so all taps registered through `late` run last.
const late = hook.withOptions({ stage: 10 });
late.tap("RunLast", (v) => console.log("last", v));
// Pre-configure stage: -10 so these taps run first. Each facade can also
// be further narrowed via `withOptions`.
const early = hook.withOptions({ stage: -10 });
early.tap("RunFirst", (v) => console.log("first", v));
hook.call(1);
// first 1
// default 1
// last 1
Per-tap options override values from withOptions. For example, late.tap({ name: "Override", stage: 0 }, fn) ignores the facade's stage: 10 and registers fn at stage 0.
Each hook can be tapped with one or several functions. How they are executed depends on the hook type:
Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row.
Waterfall. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function.
Bail. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones.
Loop. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined.
Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes:
Sync. A sync hook can only be tapped with synchronous functions (using myHook.tap()).
AsyncSeries. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using myHook.tap(), myHook.tapAsync() and myHook.tapPromise()). They call each async method in a row.
AsyncParallel. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using myHook.tap(), myHook.tapAsync() and myHook.tapPromise()). However, they run each async method in parallel.
The hook type is reflected in its class name. E.g., AsyncSeriesWaterfallHook allows asynchronous functions and runs them in series, passing each function’s return value into the next function.
The table below summarizes the 9 built-in hook classes. For each class:
tapX variants that may be used to register a handler.call (or passed to the callAsync callback / resolved from the promise call).| Class | Tap methods | Call methods | Result | Returned value from tap |
|---|---|---|---|---|
SyncHook |
tap |
call |
undefined |
ignored |
SyncBailHook |
tap |
call |
first non-undefined value, or undefined |
short-circuits the hook |
SyncWaterfallHook |
tap |
call |
final value (first argument after the last tap) | passed as first argument to the next tap |
SyncLoopHook |
tap |
call |
undefined |
non-undefined restarts the loop from the first tap |
AsyncParallelHook |
tap, tapAsync, tapPromise |
callAsync, promise |
undefined |
ignored |
AsyncParallelBailHook |
tap, tapAsync, tapPromise |
callAsync, promise |
first non-undefined value, or undefined |
short-circuits the hook |
AsyncSeriesHook |
tap, tapAsync, tapPromise |
callAsync, promise |
undefined |
ignored |
AsyncSeriesBailHook |
tap, tapAsync, tapPromise |
callAsync, promise |
first non-undefined value, or undefined |
short-circuits the hook |
AsyncSeriesLoopHook |
tap, tapAsync, tapPromise |
callAsync, promise |
undefined |
non-undefined restarts the loop from the first tap |
AsyncSeriesWaterfallHook |
tap, tapAsync, tapPromise |
callAsync, promise |
final value (first argument after the last tap) | passed as first argument to the next tap |
Detailed behavior of each class:
A basic synchronous hook. Every tapped function is called in registration order with the arguments passed to call. Return values from tapped functions are ignored and call returns undefined.
tapcalltapAsync and tapPromise throw an error.const hook = new SyncHook(["name"]);
hook.tap("A", (name) => console.log(`hello ${name}`));
hook.tap("B", (name) => console.log(`hi ${name}`));
hook.call("world");
// hello world
// hi world
A synchronous hook that allows exiting early. Every tapped function is called in order until one returns a non-undefined value; that value becomes the result of call and the remaining taps are skipped. If all taps return undefined, call returns undefined.
tapcallconst hook = new SyncBailHook(["value"]);
hook.tap("Negative", (v) => (v < 0 ? "negative" : undefined));
hook.tap("Zero", (v) => (v === 0 ? "zero" : undefined));
hook.tap("Positive", (v) => "positive");
hook.call(-1); // "negative" (later taps skipped)
hook.call(5); // "positive"
A synchronous hook that threads a value through its tapped functions. The first argument passed to call is forwarded to the first tap. If a tap returns a non-undefined value it replaces that argument for the next tap; otherwise the previous value is kept. call returns the value after the last tap has run. Additional arguments (if any) are passed through unchanged.
tapcallconst hook = new SyncWaterfallHook(["value"]);
hook.tap("Double", (v) => v * 2);
hook.tap("PlusOne", (v) => v + 1);
hook.call(3); // 7 -> (3 * 2) + 1
A synchronous hook that keeps re-running its taps until all of them return undefined for a full pass. Whenever a tap returns a non-undefined value the hook restarts from the first tap. call returns undefined.
tapcallconst hook = new SyncLoopHook(["state"]);
let retries = 3;
hook.tap("Retry", () => {
if (retries-- > 0) return true; // non-undefined restarts the loop
});
hook.tap("Log", () => console.log("pass"));
hook.call({});
// pass (runs once all taps return undefined)
An asynchronous hook that runs all of its tapped functions in parallel. It completes when every tap has signalled completion (sync return, callback, or pr
$ claude mcp add tapable \
-- python -m otcore.mcp_server <graph>