npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

class-changes-tracker

v2.0.1

Published

A lightweight TypeScript utility to track property changes in objects using snapshots, with configurable depth and custom type handling.

Readme

Class Changes Tracker

NPM Version License: MIT Tests codecov

A lightweight TypeScript utility to track property changes in objects using snapshots, with configurable depth and custom type handling.

Table of Contents

Features

  • Snapshot-Based Tracking: Monitors changes on specific object properties against deep snapshots.
  • Configurable Depth: Control the level of detail in change reports using maxDepth.
  • Custom Type Handling: Define types (treatAsValue) that should be compared by value (e.g., ObjectId, Date, custom classes) instead of deep comparison.
  • Detailed Change Reports: Provides clear TChange[] reports including path, old value, and new value.
  • Memory Efficient: Uses WeakRef to avoid memory leaks by allowing tracked objects to be garbage collected.
  • TypeScript Native: Written entirely in TypeScript with included type definitions.

Installation

npm install class-changes-tracker

or

yarn add class-changes-tracker

Usage

Basic Tracking

import { ClassChangesTracker, type TChange } from 'class-changes-tracker';

// --- Setup ---
interface IAddress {
  street: string;
  city: string;
}
interface IUser {
  id: number;
  name: string;
  address: IAddress;
  tags: string[];
}

const tracker = new ClassChangesTracker();

const user: IUser = {
  id: 1,
  name: 'John Doe',
  address: { street: '123 Main St', city: 'Anytown' },
  tags: ['a', 'b'],
};

// 1. Start tracking properties
tracker.startTrack(user, 'name');
tracker.startTrack(user, 'address'); // Uses default maxDepth = 3
tracker.startTrack(user, 'tags');

// 2. Make some changes
user.name = 'Jane Doe';
user.address.city = 'New City';
user.tags.push('c'); // Structural change (length differs)

// 3. Check for changes (without updating the baseline snapshot)
let changes: TChange[] = tracker.peekChanges();
console.log('Initial Changes:', changes);
/*
Output includes:
[
  { path: 'name', oldValue: 'John Doe', newValue: 'Jane Doe' },
  { path: 'address.city', oldValue: 'Anytown', newValue: 'New City' },
  // Structural changes are reported at the parent level
  { path: 'tags', oldValue: [ 'a', 'b' ], newValue: [ 'a', 'b', 'c' ] }
]
*/

// 4. Update the baseline snapshots to the current state
tracker.updateSnapshots();

// 5. Make more changes
user.name = 'Jane Smith';
user.address.street = '456 Side St';

// 6. Check for changes again
changes = tracker.peekChanges();
console.log('Changes after snapshot update:', changes);
/*
Output includes:
[
  // Compares against the updated snapshot ('Jane Doe')
  { path: 'name', oldValue: 'Jane Doe', newValue: 'Jane Smith' },
  { path: 'address.street', oldValue: '123 Main St', newValue: '456 Side St' }
]
*/

// 7. Update snapshots again if needed for future checks
tracker.updateSnapshots();

Using maxDepth

Control how deep the tracker looks for changes within an object. Changes below maxDepth are aggregated at the maxDepth level.

import { ClassChangesTracker, type TChange } from 'class-changes-tracker';

const depthTracker = new ClassChangesTracker();
const deepUser = { data: { level1: { level2: { level3: 'value' } } } };

// Start tracking 'data' with maxDepth = 2
depthTracker.startTrack(deepUser, 'data', 2);

// Modify a property at depth 3 (level1 -> level2 -> level3)
deepUser.data.level1.level2.level3 = 'new value';

const changes: TChange[] = depthTracker.peekChanges();
console.log('Depth Changes:', changes);
/*
Output:
[
  // Change is reported at the maxDepth level (path: 'data.level1.level2')
  {
    path: 'data.level1.level2',
    oldValue: { level3: 'value' },
    newValue: { level3: 'new value' }
  }
]
*/

Handling Custom Types with treatAsValue

Prevent the tracker from recursing into specific object types (like class instances) and compare them by value instead.

import { ClassChangesTracker, type TChange } from 'class-changes-tracker';

// Example custom class
class CustomId {
  constructor(public id: string) {}
  equals(other: any): boolean { // Optional: helps lodash.isEqual
    return other instanceof CustomId && other.id === this.id;
  }
}

// Configure tracker to treat CustomId as an atomic value
const customTypeTracker = new ClassChangesTracker({
  treatAsValue: (value) => value instanceof CustomId,
});

const userWithCustomId = {
  id: 2,
  customId: new CustomId('id-001'),
};

customTypeTracker.startTrack(userWithCustomId, 'customId');

// Replace the CustomId instance entirely
userWithCustomId.customId = new CustomId('id-002');

const changes: TChange[] = customTypeTracker.peekChanges();
console.log('Custom Type Changes:', changes);
/*
Output:
[
  // Change reported directly on 'customId', not its internal 'id' property,
  // because CustomId is treated as a value.
  {
    path: 'customId',
    oldValue: CustomId { id: 'id-001' },
    newValue: CustomId { id: 'id-002' }
  }
]
*/

Stopping Tracking

You can stop tracking individual properties or all properties managed by a tracker instance.

import { ClassChangesTracker } from 'class-changes-tracker';

const tracker = new ClassChangesTracker();
const user = { name: 'Temp User', id: 99 };

tracker.startTrack(user, 'name');
tracker.startTrack(user, 'id');

// Stop tracking only 'name'
tracker.stopTrack(user, 'name');
user.name = 'Final Name'; // This change won't be detected by peekChanges()

// Stop tracking everything
tracker.stopAllTracks();
user.id = 100; // This change won't be detected either

const changes = tracker.peekChanges();
console.log('Changes after stopping:', changes); // Output: []

API Reference

new ClassChangesTracker(options?)

Creates a new ClassChangesTracker instance.

  • options (optional): object
    • treatAsValue: (value: any) => boolean (optional) - A predicate function. If it returns true for a given value, the tracker will compare that value using lodash.isEqual instead of recursing into its properties. Defaults to only treating primitives and Date instances this way.

startTrack(obj, property, maxDepth?)

Starts tracking a specific property on an object. Stores a deep snapshot of the property's current value. If tracking is already active for the same object and property, it restarts with the new maxDepth and a fresh snapshot.

  • obj: object - The object whose property should be tracked.
  • property: string | symbol | number - The name (key) of the property to track.
  • maxDepth: number (optional) - The maximum depth for detailed change detection within this property. Defaults to 3.
  • Returns: any - The original value of the property being tracked.

peekChanges()

Compares the current values of all tracked properties against their stored snapshots. Does not update the snapshots.

  • Returns: TChange[] - An array of detected changes. An empty array [] means no changes were found relative to the last snapshot.
    • TChange: { path: string; oldValue?: any; newValue?: any; }

updateSnapshots()

Updates the internal snapshots for all tracked properties to match their current values in the tracked objects. This establishes a new baseline for future peekChanges() calls.

  • Returns: void

stopTrack(obj, property)

Stops tracking changes for a specific property on a specific object.

  • obj: object - The object whose property should no longer be tracked.
  • property: string | symbol | number - The name (key) of the property to stop tracking.
  • Returns: void

stopAllTracks()

Stops tracking changes for all properties currently being monitored by this ClassChangesTracker instance. Clears all stored snapshots and tracking information.

  • Returns: void

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests. See the Contributing Guide (if you create one) for more details.

License

Distributed under the MIT License. See LICENSE file for more information.