pax_global_header00006660000000000000000000000064140334032650014512gustar00rootroot0000000000000052 comment=c8994d7c70a5e1e74efe97e12394b9878f943dab mimic-fn-4.0.0/000077500000000000000000000000001403340326500132125ustar00rootroot00000000000000mimic-fn-4.0.0/.editorconfig000066400000000000000000000002571403340326500156730ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 mimic-fn-4.0.0/.gitattributes000066400000000000000000000000231403340326500161000ustar00rootroot00000000000000* text=auto eol=lf mimic-fn-4.0.0/.github/000077500000000000000000000000001403340326500145525ustar00rootroot00000000000000mimic-fn-4.0.0/.github/funding.yml000066400000000000000000000001621403340326500167260ustar00rootroot00000000000000github: sindresorhus open_collective: sindresorhus tidelift: npm/mimic-fn custom: https://sindresorhus.com/donate mimic-fn-4.0.0/.github/security.md000066400000000000000000000002631403340326500167440ustar00rootroot00000000000000# Security Policy To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. mimic-fn-4.0.0/.github/workflows/000077500000000000000000000000001403340326500166075ustar00rootroot00000000000000mimic-fn-4.0.0/.github/workflows/main.yml000066400000000000000000000006451403340326500202630ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: test: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: - 14 - 12 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test mimic-fn-4.0.0/.gitignore000066400000000000000000000000271403340326500152010ustar00rootroot00000000000000node_modules yarn.lock mimic-fn-4.0.0/.npmrc000066400000000000000000000000231403340326500143250ustar00rootroot00000000000000package-lock=false mimic-fn-4.0.0/index.d.ts000066400000000000000000000024511403340326500151150ustar00rootroot00000000000000export interface Options { /** Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error. @default false */ readonly ignoreNonConfigurable?: boolean; } /** Modifies the `to` function to mimic the `from` function. Returns the `to` function. `name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied. `to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment. @param to - Mimicking function. @param from - Function to mimic. @returns The modified `to` function. @example ``` import mimicFunction from 'mimic-fn'; function foo() {} foo.unicorn = '🦄'; function wrapper() { return foo(); } console.log(wrapper.name); //=> 'wrapper' mimicFunction(wrapper, foo); console.log(wrapper.name); //=> 'foo' console.log(wrapper.unicorn); //=> '🦄' ``` */ export default function mimicFunction< ArgumentsType extends unknown[], ReturnType, FunctionType extends (...arguments: ArgumentsType) => ReturnType >( to: (...arguments: ArgumentsType) => ReturnType, from: FunctionType, options?: Options, ): FunctionType; mimic-fn-4.0.0/index.js000066400000000000000000000055271403340326500146700ustar00rootroot00000000000000const copyProperty = (to, from, property, ignoreNonConfigurable) => { // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. // `Function#prototype` is non-writable and non-configurable so can never be modified. if (property === 'length' || property === 'prototype') { return; } // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here. if (property === 'arguments' || property === 'caller') { return; } const toDescriptor = Object.getOwnPropertyDescriptor(to, property); const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { return; } Object.defineProperty(to, property, fromDescriptor); }; // `Object.defineProperty()` throws if the property exists, is not configurable and either: // - one its descriptors is changed // - it is non-writable and its value is changed const canCopyProperty = function (toDescriptor, fromDescriptor) { return toDescriptor === undefined || toDescriptor.configurable || ( toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value) ); }; const changePrototype = (to, from) => { const fromPrototype = Object.getPrototypeOf(from); if (fromPrototype === Object.getPrototypeOf(to)) { return; } Object.setPrototypeOf(to, fromPrototype); }; const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. // We use `bind()` instead of a closure for the same reason. // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. const changeToString = (to, from, name) => { const withName = name === '' ? '' : `with ${name.trim()}() `; const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same` Object.defineProperty(newToString, 'name', toStringName); Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString}); }; export default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) { const {name} = to; for (const property of Reflect.ownKeys(from)) { copyProperty(to, from, property, ignoreNonConfigurable); } changePrototype(to, from); changeToString(to, from, name); return to; } mimic-fn-4.0.0/index.test-d.ts000066400000000000000000000006641403340326500160760ustar00rootroot00000000000000import {expectType, expectAssignable} from 'tsd'; import mimicFunction from './index.js'; function foo(string: string) { return false; } foo.unicorn = '🦄'; function wrapper(string: string) { return foo(string); } const mimickedFunction = mimicFunction(wrapper, foo); expectAssignable(mimickedFunction); expectType(mimickedFunction('bar')); expectType(mimickedFunction.unicorn); mimic-fn-4.0.0/license000066400000000000000000000021351403340326500145600ustar00rootroot00000000000000MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mimic-fn-4.0.0/media/000077500000000000000000000000001403340326500142715ustar00rootroot00000000000000mimic-fn-4.0.0/media/logo.svg000066400000000000000000000047561403340326500157660ustar00rootroot00000000000000mimic-fn-4.0.0/package.json000066400000000000000000000013611403340326500155010ustar00rootroot00000000000000{ "name": "mimic-fn", "version": "4.0.0", "description": "Make a function mimic another one", "license": "MIT", "repository": "sindresorhus/mimic-fn", "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./index.js", "engines": { "node": ">=12" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "function", "mimic", "imitate", "rename", "copy", "inherit", "properties", "name", "func", "fn", "set", "infer", "change" ], "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" } } mimic-fn-4.0.0/readme.md000066400000000000000000000040451403340326500147740ustar00rootroot00000000000000mimic-fn
> Make a function mimic another one Useful when you wrap a function in another function and like to preserve the original name and other properties. ## Install ``` $ npm install mimic-fn ``` ## Usage ```js import mimicFunction from 'mimic-fn'; function foo() {} foo.unicorn = '🦄'; function wrapper() { return foo(); } console.log(wrapper.name); //=> 'wrapper' mimicFunction(wrapper, foo); console.log(wrapper.name); //=> 'foo' console.log(wrapper.unicorn); //=> '🦄' console.log(String(wrapper)); //=> '/* Wrapped with wrapper() */\nfunction foo() {}' ``` ## API ### mimicFunction(to, from, options?) Modifies the `to` function to mimic the `from` function. Returns the `to` function. `name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied. `to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment. #### to Type: `Function` Mimicking function. #### from Type: `Function` Function to mimic. #### options Type: `object` ##### ignoreNonConfigurable Type: `boolean`\ Default: `false` Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error. ## Related - [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function - [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
mimic-fn-4.0.0/test.js000066400000000000000000000147321403340326500145360ustar00rootroot00000000000000import test from 'ava'; import mimicFunction from './index.js'; const foo = function (bar) { return bar; }; foo.unicorn = '🦄'; const symbol = Symbol('🦄'); foo[symbol] = '✨'; const parent = function () {}; parent.inheritedProp = true; Object.setPrototypeOf(foo, parent); test('should return the wrapped function', t => { const wrapper = function () {}; const returnValue = mimicFunction(wrapper, foo); t.is(returnValue, wrapper); }); test('should copy `name`', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.name, foo.name); }); test('should copy other properties', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.unicorn, foo.unicorn); }); test('should copy symbol properties', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper[symbol], foo[symbol]); }); test('should not copy `length`', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.length, 0); }); test('should keep descriptors', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); const {length: fooLength, toString: fooToString, ...fooProperties} = Object.getOwnPropertyDescriptors(foo); const {length: wrapperLength, toString: wrapperToString, ...wrapperProperties} = Object.getOwnPropertyDescriptors(wrapper); t.deepEqual(fooProperties, wrapperProperties); t.not(fooLength, wrapperLength); t.not(fooToString, wrapperToString); }); test('should copy inherited properties', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.inheritedProp, foo.inheritedProp); }); test('should not delete extra configurable properties', t => { const wrapper = function () {}; wrapper.extra = true; mimicFunction(wrapper, foo); t.true(wrapper.extra); }); test('should not copy prototypes', t => { const wrapper = function () {}; const prototype = {}; wrapper.prototype = prototype; mimicFunction(wrapper, foo); t.is(wrapper.prototype, prototype); }); test('should allow classes to be copied', t => { class wrapperClass {} class fooClass {} mimicFunction(wrapperClass, fooClass); t.is(wrapperClass.name, fooClass.name); t.not(wrapperClass.prototype, fooClass.prototype); }); test('should patch toString()', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.toString(), `/* Wrapped with wrapper() */\n${foo.toString()}`); }); test('should patch toString() with arrow functions', t => { const wrapper = function () {}; const arrowFn = value => value; mimicFunction(wrapper, arrowFn); t.is(wrapper.toString(), `/* Wrapped with wrapper() */\n${arrowFn.toString()}`); }); test('should patch toString() with bound functions', t => { const wrapper = function () {}; const boundFn = (() => {}).bind(); mimicFunction(wrapper, boundFn); t.is(wrapper.toString(), `/* Wrapped with wrapper() */\n${boundFn.toString()}`); }); test('should patch toString() with new Function()', t => { const wrapper = function () {}; // eslint-disable-next-line no-new-func const newFn = new Function(''); mimicFunction(wrapper, newFn); t.is(wrapper.toString(), `/* Wrapped with wrapper() */\n${newFn.toString()}`); }); test('should patch toString() several times', t => { const wrapper = function () {}; const wrapperTwo = function () {}; mimicFunction(wrapper, foo); mimicFunction(wrapperTwo, wrapper); t.is(wrapperTwo.toString(), `/* Wrapped with wrapperTwo() */\n/* Wrapped with wrapper() */\n${foo.toString()}`); }); test('should keep toString() non-enumerable', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); const {enumerable} = Object.getOwnPropertyDescriptor(wrapper, 'toString'); t.false(enumerable); }); test('should print original function with Function.prototype.toString.call()', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(Function.prototype.toString.call(wrapper), 'function () {}'); }); test('should work with String()', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(String(wrapper), `/* Wrapped with wrapper() */\n${foo.toString()}`); }); test('should not modify toString.name', t => { const wrapper = function () {}; mimicFunction(wrapper, foo); t.is(wrapper.toString.name, 'toString'); }); test('should work when toString() was patched by original function', t => { const wrapper = function () {}; const bar = function () {}; bar.toString = () => 'bar.toString()'; mimicFunction(wrapper, bar); t.is(wrapper.toString(), `/* Wrapped with wrapper() */\n${bar.toString()}`); }); // eslint-disable-next-line max-params const configurableTest = (t, shouldThrow, ignoreNonConfigurable, toDescriptor, fromDescriptor) => { const wrapper = function () {}; Object.defineProperty(wrapper, 'conf', {value: true, configurable: false, writable: true, enumerable: true, ...toDescriptor}); const bar = function () {}; Object.defineProperty(bar, 'conf', {value: true, configurable: false, writable: true, enumerable: true, ...fromDescriptor}); if (shouldThrow) { t.throws(() => { mimicFunction(wrapper, bar, {ignoreNonConfigurable}); }); } else { t.notThrows(() => { mimicFunction(wrapper, bar, {ignoreNonConfigurable}); }); } }; configurableTest.title = title => `should handle non-configurable properties: ${title}`; test('not throw with no changes', configurableTest, false, false, {}, {}); test('not throw with writable value change', configurableTest, false, false, {}, {value: false}); test('throw with non-writable value change', configurableTest, true, false, {writable: false}, {value: false, writable: false}); test('not throw with non-writable value change and ignoreNonConfigurable', configurableTest, false, true, {writable: false}, {value: false, writable: false}); test('throw with configurable change', configurableTest, true, false, {}, {configurable: true}); test('not throw with configurable change and ignoreNonConfigurable', configurableTest, false, true, {}, {configurable: true}); test('throw with writable change', configurableTest, true, false, {writable: false}, {writable: true}); test('not throw with writable change and ignoreNonConfigurable', configurableTest, false, true, {writable: false}, {writable: true}); test('throw with enumerable change', configurableTest, true, false, {}, {enumerable: false}); test('not throw with enumerable change and ignoreNonConfigurable', configurableTest, false, true, {}, {enumerable: false}); test('default ignoreNonConfigurable to false', configurableTest, true, undefined, {}, {enumerable: false});