@prexjs/wrappy
v1.0.3
Published
Lightweight TypeScript utility that wraps functions while preserving their own properties and callback decorations.
Readme
@prexjs/wrappy
A lightweight TypeScript utility that wraps functions while preserving their own properties and callback decorations.
@prexjs/wrappy wraps functions without losing their own enumerable properties and ensures callback decorations survive wrapping when a wrapper function returns a different callback.
Features
- Wrap functions without losing their own enumerable properties.
- Preserve callback properties when a wrapper returns a different callback function.
- Support TypeScript generics for function signatures and return types.
- Provide both named and default exports.
- Lightweight implementation with no runtime dependencies.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/wrappy
# pnpm
pnpm add @prexjs/wrappy
# Yarn
yarn add @prexjs/wrappy
# Bun
bun add @prexjs/wrappyQuick start
import { wrappy } from '@prexjs/wrappy';
function original(value: string): string {
return `Hello, ${value}!`;
}
const wrapped = wrappy(original);
console.log(wrapped('World')); // 'Hello, World!'Both default and named imports are supported:
import wrappy, { wrappy as namedWrappy } from '@prexjs/wrappy';Examples
Preserve function properties
Properties attached to the original function are copied to the wrapper:
import { wrappy } from '@prexjs/wrappy';
function callback() {
// Callback logic
}
Object.assign(callback, {
label: 'request-callback',
customFlag: true,
});
function wrapper(fn: typeof callback) {
return fn;
}
const wrapped = wrappy(wrapper);
console.log((wrapped as typeof wrapper & { label?: string }).label);
// 'request-callback'The wrapper copies enumerable own string-keyed properties from the original function using Object.keys().
Preserve callback properties
When the wrapped function returns a different function, enumerable own properties from the final argument are copied to the returned function:
import { wrappy } from '@prexjs/wrappy';
type Callback = (() => void) & {
label?: string;
};
function wrapper(callback: Callback) {
const decorated = (() => {
callback();
}) as Callback;
return decorated;
}
const callback = Object.assign(() => {
console.log('Callback executed');
}, {
label: 'completion',
});
const wrapped = wrappy(wrapper);
const result = wrapped(callback);
console.log(result.label); // 'completion'This behavior ensures that metadata or custom tags attached to callbacks remain intact even after the callback is transformed by a wrapper.
Compatibility
@prexjs/wrappy is designed for JavaScript and TypeScript projects. It is distributed with ES Modules (.mjs), CommonJS (.cjs), and TypeScript declarations. It runs in any modern JavaScript runtime without platform-specific dependencies.
License
This project is licensed under the MIT License. See LICENSE for the full license text.
Related projects
- prex.js — prex.js monorepo and ecosystem.
