
Security News
Happy Birthday, Shai-Hulud
It has been one year since Shai-Hulud made its first appearance on npm.
A blazing fast deep object copier
import copy from 'fast-copy';
import { deepEqual } from 'fast-equals';
const object = {
array: [123, { deep: 'value' }],
map: new Map([
['foo', {}],
[{ bar: 'baz' }, 'quz'],
]),
};
const copiedObject = copy(object);
console.log(copiedObject === object); // false
console.log(deepEqual(copiedObject, object)); // true
copyDeeply copy the object passed.
import copy from 'fast-copy';
const copied = copy({ foo: 'bar' });
copyStrictDeeply copy the object passed, but with additional strictness when replicating the original object:
import { copyStrict } from 'fast-copy';
const object = { foo: 'bar' };
object.nonEnumerable = Object.defineProperty(object, 'bar', {
enumerable: false,
value: 'baz',
});
const copied = copy(object);
NOTE: This method is significantly slower than copy, so it is recommended to only use this when you have specific use-cases that require it.
createCopierCreate a custom copier based on the type-specific methods passed. This is useful if you want to squeeze out maximum performance, or perform something other than a standard deep copy.
import { createCopier } from 'fast-copy';
const copyShallow = createCopier({
array: (array) => [...array],
map: (map) => new Map(map.entries()),
object: (object) => ({ ...object }),
set: (set) => new Set(set.values()),
});
Each internal copier method has the following contract:
type InternalCopier<Value> = (value: Value, state: State) => Value;
interface State {
Constructor: any;
cache: WeakMap;
copier: InternalCopier<any>;
depth: number;
prototype: any;
}
Any method overriding the defaults must maintain this contract.
array => ArrayarrayBuffer=> ArrayBuffer, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, Uint64Arrayblob => BlobdataView => DataViewdate => Dateerror => Error, AggregateError, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIErrormap => Mapobject => Object, or any custom constructorregExp => RegExpset => SetmaxDepthThe maximum number of nested objects traversed before a MaxDepthExceededError is thrown. Defaults to 1000.
Because copying is recursive, a value nested more deeply than the JavaScript engine's call stack allows will exhaust the stack. The default limit sits below that threshold, so deeply-nested values fail with a descriptive, catchable error instead of a raw RangeError:
import copy, { MaxDepthExceededError } from 'fast-copy';
try {
copy(untrustedPayload);
} catch (error) {
if (error instanceof MaxDepthExceededError) {
// `error.maxDepth` is the limit that was exceeded
}
}
MaxDepthExceededError extends RangeError, so existing handling of the native stack-exhaustion error continues to work. In legacy environments without Object.setPrototypeOf, instanceof MaxDepthExceededError cannot be supported; check error.name === 'MaxDepthExceededError' or error instanceof RangeError instead.
The limit is configured when the copier is created, so copy and copyStrict always use the default. If you copy values that are legitimately nested more deeply, create a copier with the limit you need and use it in their place; pass Infinity to remove the limit entirely, in which case sufficiently-deep values will again throw a native RangeError.
import { createCopier, createStrictCopier } from 'fast-copy';
export const copy = createCopier({ maxDepth: 5000 });
export const copyStrict = createStrictCopier({ maxDepth: 5000 });
The default of 1000 assumes the stack available to a standard Node.js or browser main thread. Environments configured with a smaller stack can exhaust it sooner, so lower the limit to suit the environment if you copy deeply-nested values in one. The failure when the limit is set too high for the environment is the same native RangeError thrown prior to this option existing, so too high a limit is never worse than having none.
NOTE: The depth counts nested objects only. Primitives and values already present in the cache (circular references) do not contribute to it.
cacheIf you want to maintain circular reference handling, then you'll need the methods to handle cache population for future lookups:
function shallowlyCloneArray<Value extends any[]>(
value: Value,
state: State
): Value {
const clone = [...value];
state.cache.set(value, clone);
return clone;
}
copiercopier is provided for recursive calls with deeply-nested objects.
function deeplyCloneArray<Value extends any[]>(
value: Value,
state: State
): Value {
const clone = [];
state.cache.set(value, clone);
value.forEach((item) => state.copier(item, state));
return clone;
}
Note above I am using forEach instead of a simple map. This is because it is highly recommended to store the clone in cache eagerly when deeply copying, so that nested circular references are handled correctly.
Constructor / prototypeBoth Constructor and prototype properties are only populated with complex objects that are not standard objects or arrays. This is mainly useful for custom subclasses of these globals, or maintaining custom prototypes of objects.
function deeplyCloneSubclassArray<Value extends CustomArray>(
value: Value,
state: State
): Value {
const clone = new state.Constructor();
state.cache.set(value, clone);
value.forEach((item) => clone.push(item));
return clone;
}
function deeplyCloneCustomObject<Value extends CustomObject>(
value: Value,
state: State
): Value {
const clone = Object.create(state.prototype);
state.cache.set(value, clone);
Object.entries(value).forEach(([k, v]) => (clone[k] = v));
return clone;
}
createStrictCopierCreate a custom copier based on the type-specific methods passed, but defaulting to the same functions normally used for copyStrict. This is useful if you want to squeeze out better performance while maintaining strict requirements, or perform something other than a strict deep copy.
const createStrictClone = (value, clone) =>
Object.getOwnPropertyNames(value).reduce(
(clone, property) =>
Object.defineProperty(
clone,
property,
Object.getOwnPropertyDescriptor(value, property) || {
configurable: true,
enumerable: true,
value: clone[property],
writable: true,
}
),
clone
);
const copyStrictShallow = createStrictCopier({
array: (array) => createStrictClone(array, []),
map: (map) => createStrictClone(map, new Map(map.entries())),
object: (object) => createStrictClone(object, {}),
set: (set) => createStrictClone(set, new Set(set.values())),
});
NOTE: This method creates a copier that is significantly slower than copy, as well as likely a copier created by createCopier, so it is recommended to only use this when you have specific use-cases that require it.
The following object types are deeply cloned when they are either properties on the object passed, or the object itself:
ArrayArrayBufferBoolean primitive wrappers (e.g., new Boolean(true))BlobBufferDataViewDateFloat32ArrayFloat64ArrayInt8ArrayInt16ArrayInt32ArrayMapNumber primitive wrappers (e.g., new Number(123))ObjectRegExpSetString primitive wrappers (e.g., new String('foo'))Uint8ArrayUint8ClampedArrayUint16ArrayUint32ArrayReact componentsThe following object types are copied directly, as they are either primitives, cannot be cloned, or the common use-case implementation does not expect cloning:
AsyncFunctionBoolean primitivesErrorFunctionGeneratorFunctionNumber primitivesNullPromiseString primitivesSymbolUndefinedWeakMapWeakSetCircular objects are supported out of the box. By default, a cache based on WeakSet is used, but if WeakSet is not available then a fallback is used. The benchmarks quoted below are based on use of WeakSet.
Inherently, what is considered a valid copy is subjective because of different requirements and use-cases. For this library, some decisions were explicitly made for the default copiers of specific object types, and those decisions are detailed below. If your use-cases require different handling, you can always create your own custom copier with createCopier or createStrictCopier.
*Error objectWhile it would be relatively trivial to copy over the message and stack to a new object of the same Error subclass, it is a common practice to "override" the message or stack, and copies would not retain this mutation. As such, the original reference is copied.
Starting in ES2015, native globals can be subclassed like any custom class. When copying, we explicitly reuse the constructor of the original object. However, the expectation is that these subclasses would have the same constructur signature as their native base class. This is a common community practice, but there is the possibility of inaccuracy if the contract differs.
Generator objects are specific types of iterators, but appear like standard objects that just have a few methods (next, throw, return). These methods are bound to the internal state of the generator, which cannot be copied effectively. Normally this would be treated like other "uncopiable" objects and simply pass the reference through, however the "validation" of whether it is a generator object or a standard object is not guaranteed (duck-typing) and there is a runtime cost associated with. Therefore, the simplest path of treating it like a standard object (copying methods to a new object) was taken.
Small number of properties, all values are primitives
| Operations / second | |
|---|---|
| fast-copy | 5,880,312 |
| lodash.cloneDeep | 2,706,261 |
| clone | 2,207,231 |
| deepclone | 1,274,810 |
| fast-clone | 1,239,952 |
| ramda | 1,146,152 |
| fast-copy (strict) | 852,382 |
Large number of properties, values are a combination of primitives and complex objects
| Operations / second | |
|---|---|
| fast-copy | 162,858 |
| ramda | 142,104 |
| deepclone | 133,607 |
| fast-clone | 101,143 |
| clone | 70,872 |
| fast-copy (strict) | 62,961 |
| lodash.cloneDeep | 62,060 |
Very large number of properties with high amount of nesting, mainly objects and arrays
| Operations / second | |
|---|---|
| fast-copy | 303 |
| fast-clone | 245 |
| deepclone | 151 |
| lodash.cloneDeep | 150 |
| clone | 93 |
| fast-copy (strict) | 90 |
| ramda | 42 |
Objects that deeply reference themselves
| Operations / second | |
|---|---|
| fast-copy | 2,420,466 |
| deepclone | 1,386,896 |
| ramda | 1,024,108 |
| lodash.cloneDeep | 989,796 |
| clone | 987,721 |
| fast-copy (strict) | 617,602 |
| fast-clone | 0 (not supported) |
Custom constructors, React components, etc
| Operations / second | |
|---|---|
| fast-copy | 152,792 |
| clone | 74,347 |
| fast-clone | 66,576 |
| lodash.cloneDeep | 64,760 |
| ramda | 53,542 |
| deepclone | 28,823 |
| fast-copy (strict) | 21,362 |
Standard practice, clone the repo and yarn (or npm i) to get the dependencies. The following npm scripts are available:
build:esm, build:cjs, build:umd, and build:min scriptsrimraf on the dist folderclean and build scriptssrc folder (also runs on dev script)lint script, but with auto-fixerlint, test:coverage, and dist scriptsprepublishOnly and release with new versionprepublishOnly and release with new beta versionprepublishOnly and simulate a new releasedevtest foldertest with code coverage calculation via nyctest but keep persistent watchertsc on the codebaseLodash's clonedeep method provides deep cloning functionality. It is part of the larger Lodash library, which is a general utility library. Compared to fast-copy, lodash.clonedeep may be slower but is part of a well-established utility library with a wide range of functions.
The clone package offers deep cloning of objects and arrays. It is less focused on performance compared to fast-copy and does not handle some of the more complex data types that fast-copy can.
Deep-copy is another package that provides deep cloning capabilities. It is similar to fast-copy in its purpose but may not have the same performance optimizations.
The rfdc (Really Fast Deep Clone) package is a competitor to fast-copy, focusing on performance for deep cloning. It claims to be faster than other deep cloning libraries for certain use cases and is a good alternative to consider when performance is critical.
FAQs
A blazing fast deep object copier
The npm package fast-copy receives a total of 11,808,320 weekly downloads. As such, fast-copy popularity was classified as popular.
We found that fast-copy demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Security News
It has been one year since Shai-Hulud made its first appearance on npm.

Research
/Security News
Operators behind PolinRider used a compromised GitHub account to plant malware in four development versions of a Packagist package with 700,000+ downloads.

Security News
GitHub Actions now supports cache-mode, a least-privilege control on the Actions cache aimed at the cache poisoning technique behind recent compromises.