corehook-utility
v1.0.2
Published
This is a slicing programming tool class based on front-end objects or functions
Readme
CoreHook - Advanced Proxy Hooks Utility
Overview
CoreHook is a powerful TypeScript utility that enables intercepting operations on objects and functions using JavaScript's Proxy API. It allows developers to inject custom logic before or after:
- Property access (
get) - Property assignment (
set) - Property deletion (
deleteProperty) - Function invocation (
apply)
Key features:
- 🛡️ Memory-safe implementation using WeakMap
- ⚡ Lightweight and performant
- 🔍 Support for both objects and functions
- 🧩 Modular hook registration
- 🧹 Automatic garbage collection
- 🔧 Full TypeScript support
Installation
npm install corehook-utilityimport { CoreHook } from 'corehook-utility';API Reference
registerGetHook()
Registers hooks for property access operations.
static registerGetHook<T extends object>(
target: T,
callbackList: Array<(target: T, key: string | symbol) => void>,
before: boolean = true
): TParameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| target | object | Yes | - | Target object to monitor |
| callbackList | Function[] | Yes | - | Array of callback functions |
| before | boolean | No | true | Trigger before operation |
Returns:
Proxy object with get hooks applied
registerSetHook()
Registers hooks for property assignment operations.
static registerSetHook<T extends object>(
target: T,
callbackList: Array<(target: T, key: string | symbol, value: any) => void>,
before: boolean = true
): TParameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| target | object | Yes | - | Target object to monitor |
| callbackList | Function[] | Yes | - | Array of callback functions |
| before | boolean | No | true | Trigger before operation |
Returns:
Proxy object with set hooks applied
registerDeleteHook()
Registers hooks for property deletion operations.
static registerDeleteHook<T extends object>(
target: T,
callbackList: Array<(target: T, key: string | symbol) => void>,
before: boolean = true
): TParameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| target | object | Yes | - | Target object to monitor |
| callbackList | Function[] | Yes | - | Array of callback functions |
| before | boolean | No | true | Trigger before operation |
Returns:
Proxy object with delete hooks applied
registerApplyHook()
Registers hooks for function invocation operations.
static registerApplyHook<T extends Function>(
target: T,
callbackList: Array<(target: T, thisArg: any, args: any[]) => void>,
before: boolean = true
): TParameters:
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| target | Function | Yes | - | Target function to monitor |
| callbackList | Function[] | Yes | - | Array of callback functions |
| before | boolean | No | true | Trigger before operation |
Returns:
Proxy function with apply hooks applied
clearTargetHooks()
Removes all hooks associated with a target.
static clearTargetHooks(target: object | Function): voidParameters:
| Parameter | Type | Description |
|-----------|------|-------------|
| target | object | Function | Target to clear hooks from |
getTargetHooks()
Retrieves all hooks registered for a target.
static getTargetHooks(
target: object | Function
): Map<string, Function[]> | undefinedReturns:
Map of hook types and their callbacks, or undefined if no hooks exist
Usage Examples
1. Property Access Logging
const user = { name: 'Alice', age: 30 };
const monitoredUser = CoreHook.registerGetHook(user, [
(target, key) => console.log(`Accessed property: ${String(key)}`)
], true);
console.log(monitoredUser.name);
// Output: Accessed property: name
// Alice2. Input Validation
const config = { apiKey: '' };
const validatedConfig = CoreHook.registerSetHook(config, [
(target, key, value) => {
if (key === 'apiKey' && value.length < 10) {
throw new Error('API key must be at least 10 characters');
}
}
], true);
validatedConfig.apiKey = '1234567890'; // Success
validatedConfig.apiKey = 'short'; // Throws error3. Function Performance Monitoring
function processData(data: string) {
return data.toUpperCase();
}
const timedFunction = CoreHook.registerApplyHook(processData, [
(target, thisArg, args) => console.time('processData'),
(target, thisArg, args) => console.timeEnd('processData')
], false);
timedFunction('test');
// Output: processData: 0.102ms4. Automatic Resource Cleanup
const resource = { connection: null };
const managedResource = CoreHook.registerDeleteHook(resource, [
(target, key) => {
if (key === 'connection' && target.connection) {
console.log('Closing connection...');
target.connection.close();
}
}
], true);
managedResource.connection = { close: () => console.log('Closed') };
delete managedResource.connection;
// Output: Closing connection...
// ClosedBest Practices
1. Lifecycle Management
class SecureService {
private data: any = {};
private dataProxy: any;
constructor() {
this.dataProxy = CoreHook.registerSetHook(this.data, [
this.validateData.bind(this)
], true);
}
private validateData(target: any, key: string, value: any) {
// Validation logic
}
cleanup() {
CoreHook.clearTargetHooks(this.data);
}
}2. Performance Monitoring
function withPerfMonitoring<T extends Function>(fn: T): T {
return CoreHook.registerApplyHook(fn, [
(target, thisArg, args) => console.time(target.name),
(target, thisArg, args) => console.timeEnd(target.name)
], false);
}
const monitoredFn = withPerfMonitoring(myFunction);3. Debugging Utilities
function debugHooks(target: object | Function) {
const hooks = CoreHook.getTargetHooks(target);
if (hooks) {
console.log(`Target has ${hooks.size} hook types:`);
for (const [type, callbacks] of hooks) {
console.log(`- ${type}: ${callbacks.length} callbacks`);
}
}
}4. Asynchronous Operations
CoreHook.registerApplyHook(asyncFunction, [
async (target, thisArg, args) => {
await preProcess();
console.log('Pre-processing complete');
}
], true);Important Notes
Proxy Chains
Multiple registrations on the same target create proxy chains. UsegetRawTarget()to access the original object.Symbol Properties
Symbol keys are preserved in their original form during hook notifications.Error Handling
Hook errors are caught and logged but don't interrupt main execution:Hook execution error: [Error message]Memory Management
Unused targets are automatically garbage collected via WeakMap.Function Identifiers
Anonymous functions are assigned unique identifiers using Symbols.Performance Considerations
For high-frequency operations, minimize hook complexity and:- Use
before: falsefor non-critical operations - Avoid deep object inspection in hooks
- Use
clearTargetHooks()when hooks are no longer needed
- Use
Type Safety
The API maintains strict TypeScript typing throughout operations.
