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

@dirtytalk/structural

v0.2.0

Published

Path-based dirty-tracking instantiation of @dirtytalk/engine, for state containers and structural data.

Readme

@dirtytalk/structural

Path-based dirty-tracking instantiation of @dirtytalk/engine, for state containers and structural data.

Why this exists

Both state containers and UI renderers ask the same question after a mutation: what changed, who cares, and when do we tell them? For structural data (objects and arrays whose consumers read named paths through them) the answer here is a set of interned path IDs.

A consumer says which paths it reads (consume + setPaths, usually fed by trackRender). Each mutation diffs the old and new state along the watched paths only, skipping subtrees whose reference is unchanged. One flush per scheduler tick calls the consumers it woke with the set of changed path ids. The cost of a change follows what consumers read and how many of them it wakes, not the size of the state or one walk per consumer.

What's in the box

  • StructuralStore<S>: a ready-to-use container with public set, patch and update. The quick way to use the package without subclassing.
  • StructuralContainer<S>: the abstract base class. Holds state, indexes consumers by the paths they watch, and provides the protected mutators emit, patch and update for subclasses to build methods on.
  • Consumer: the handle container.consume(cb) returns: setPaths(paths), dispose().
  • PathInterner: string-to-ID interning. One per container class by default, one per store.
  • PathSet: a Set<PathId> or the ALL_PATHS sentinel, with PathSetSpace, the Space<PathSet> the container hands to the engine's DirtyChannel.
  • trackRender: Proxy-based path recorder. Wraps state, records every field access as an interned PathId, and returns the access set alongside the proxied value. Optionally accepts a ProxyCache to reuse proxies across renders, see Cross-render proxy reuse below.
  • ProxyCache: opt-in, caller-owned cache that lets trackRender skip re-allocating a Proxy for array items (or any nested value) that didn't change between renders.
  • getAt: reads a value at a dotted path string.
  • React adapter at @dirtytalk/structural/react: useStructural(container), built on useSyncExternalStore.
  • @dirtytalk/structural/testing: setTrackTrace, a hook that observes tracking decisions.

Install

pnpm add @dirtytalk/structural @dirtytalk/engine

@dirtytalk/engine is a runtime dependency. Both packages are versioned together in this monorepo; installing structural without engine would produce a missing peer at runtime.

Quick example: core (no React)

import { SyncScheduler } from '@dirtytalk/engine';
import { StructuralStore } from '@dirtytalk/structural';

const store = new StructuralStore(
  { count: 0, label: 'counter' },
  { scheduler: new SyncScheduler() },
);

const unsubscribe = store.subscribe((dirty) => {
  console.log('state:', store.state, 'dirty:', dirty);
});

store.patch({ count: 1 });
// => state: { count: 1, label: 'counter' }  dirty: Set { <root id> }

unsubscribe();

subscribe(cb) listens to every change. To wake only when specific paths change, register a consumer and tell it what it reads:

const consumer = store.consume(() => console.log('count changed'));
consumer.setPaths(new Set([store.interner.intern('count')]));

store.patch({ label: 'renamed' }); // does not wake the consumer
store.patch({ count: 2 }); // wakes it
consumer.dispose();

dirty holds the ids of the changed paths among those any consumer watches. When no watched path changed it holds only the root id (interner.rootId(), which lookup decodes to ''). In the first example nothing watches a specific path, so the callback receives the root id alone.

To keep mutation inside the class, subclass StructuralContainer and expose methods that call the protected emit, patch and update:

import { StructuralContainer } from '@dirtytalk/structural';

class Counter extends StructuralContainer<{ count: number }> {
  constructor() {
    super({ count: 0 });
  }

  increment() {
    this.patch({ count: this.state.count + 1 });
  }
}

Quick example: React

import { useStructural } from '@dirtytalk/structural/react';

const counter = new Counter();

function CounterDisplay() {
  const [state, container] = useStructural(counter);

  // Only the paths read inside this render are recorded.
  // Reading state.count watches "count". A patch to another key will not
  // re-render this component.
  return <button onClick={() => container.increment()}>{state.count}</button>;
}

On each render, useStructural wraps state in a recording Proxy and, after commit, passes the accessed paths to its consumer with setPaths. If props or context change what fields are read, the watched paths update on the next commit. No selector declaration is required.

API surface: public exports

| Export | Role | | --------------------------------- | --------------------------------------------------------------------- | | StructuralStore<S> | Concrete container with public set, patch, update | | StructuralContainer<S> | Base class: state, consumers, protected emit/patch/update | | Consumer | { paths, setPaths(paths), dispose() }, from container.consume(cb) | | PathInterner | Interning: intern(path): PathId, lookup(id): string, size | | PathSet | Set<PathId> \| typeof ALL_PATHS | | PathSetSpace | Space<PathSet> implementation for the engine | | ALL_PATHS | Interest value: wake on every change | | pathSetUnion | Pure union of two PathSet values | | pathSetEquals | Equality check for two PathSet values | | trackRender | (state, interner, proxyCache?) => { value, paths, disarm } | | ProxyCache | Opt-in cache: reuses proxies across trackRender calls | | raw, untracked | (v) => v: unwrap a tracked proxy to its raw target | | getAt | (obj, dottedPath) => unknown | | useStructural (react subpath) | (container) => [state, container] | | setTrackTrace (testing) | (hook \| null) => void: observe tracking decisions |

Container members: state, interner, consume(cb), subscribe(cb), flush(), consumers(), consumerCount (includes subscribe listeners) and dispose().

Options: scheduler, interner, equality (keyed by exact dotted path; a key containing . or \ is written escaped), and onError (receives errors thrown by consumer callbacks).

Mutation semantics

  • emit(next) replaces the state. A no-op when Object.is(state, next).
  • patch(partial) is emit(deepMerge(state, partial)). Plain-object branches merge recursively. Arrays, class instances, Map, Set, Date and primitives replace the slot. A patch cannot remove a key: undefined is stored as a value. Use emit or update to remove one.
  • update(fn) is emit(fn(state)).
  • With no consumers a mutation only replaces the state: no diff, no flush.

Tracking hazards

trackRender returns a recording proxy; values read off it are themselves proxies. Two situations need raw() to unwrap them:

  1. Identity === callbacks. Comparing a value read from the proxy against a raw object reference (directly, or via an identity-search like Array.prototype.includes) fails because the value is wrapped. Compare raw(value) === rawRef.
  2. Derived-array / escaped proxy. A proxy (or a sub-proxy inside a derived array such as a .filter result) that escapes the render frame keeps recording into a stale paths set and breaks reference identity against the underlying state. Call raw() on anything stored or handed to code that expects the raw object.

Supported state

Tracking assumes plain data: plain objects and arrays with string keys and ordinary enumerable, writable properties. Frozen state (for example immer output) is tracked like mutable state. Non-plain values (Map, Date, class instances) are leaves compared by reference. Not tracked: symbol keys, descriptor-only changes (same value, different flags), an own key starting to shadow an inherited one with an equal value, own properties shadowing array methods, and non-enumerable properties, which patch drops without a mark.

Cross-render proxy reuse (ProxyCache)

By default, trackRender allocates a brand-new Proxy for every object it touches, every single call. For a component that maps over a large array (items.map(item => <Row key={item.id} .../>)), that means a full re-render pays O(array length) proxy allocations even when almost every item is the exact same object reference as last render, e.g. reordering two rows in a 1000-row list still allocates ~1000 proxies for a change that only touched 2. ProxyCache, passed as trackRender's optional third argument, fixes this: a (target, prefix) pair unchanged since the caller's last trackRender call reuses the same Proxy object instead of allocating a new one.

import { trackRender, ProxyCache } from '@dirtytalk/structural';

// Scoped per call-site, e.g. one per component instance, created once and
// reused across that component's renders (a React `useRef(new ProxyCache())`
// is the typical home for it).
const proxyCache = new ProxyCache();

function renderList(state: { items: Item[] }) {
  const { value, paths, disarm } = trackRender(state, interner, proxyCache);
  // ...read value.items, etc...
  disarm();
}

Key properties:

  • Keyed by (target, prefix), not target alone. The same object read at two different paths in one render (aliasing) still gets two independent proxies, exactly as the no-cache behavior guarantees. Only a genuine repeat read at the same path across calls is reused. This is also why reordering an item to a brand-new index it has never occupied before still allocates a fresh proxy for it: the (target, prefix) pair is new, so there's nothing to reuse. The win is proportional to how many items keep their index across a render, which is exactly the common case (a two-item swap in a 1000-item list reuses 998 proxies and allocates 2).
  • Scope one ProxyCache per call-site, never globally or per-container. An entry holds exactly one live "session" (the render's paths/armed state) at a time; sharing a cache across two independently-timed callers would let one caller's render silently repoint an entry the other caller is still reading from. If a consumer tracks more than one independent thing per render (e.g. a primary state plus a separate dependency), give each its own ProxyCache.
  • No explicit eviction needed. The cache is WeakMap-keyed by the target object, so entries for objects no longer referenced anywhere else are collected normally.
  • disarm(), raw()/untracked(), and removal all keep working unchanged. A reused proxy still unwraps to the same raw target via raw() regardless of how many renders old it is, and disarm() still freezes exactly the entries touched by the render that called it.

What it is not

  • No auto-tracked computed values. There is no computed(() => a + b) with a hidden dependency graph. Build derived values above this layer.
  • No effect system with cleanups. subscribe returns an unsubscribe function and a Consumer has dispose(); those are the cleanup primitives.
  • No scheduler opinions. The scheduler is injected through the container options. The engine provides SyncScheduler, ManualScheduler, MicrotaskScheduler, and RAFScheduler; choose what fits your context. This package does not force one.
  • No mutation primitive. All updates go through emit, patch, or update: immutable replacement only. In-place mutation of state bypasses change tracking silently. On a StructuralContainer those three are protected, so callers go through the methods a subclass exposes; StructuralStore exposes set, patch and update publicly.
  • No virtual DOM. The React adapter triggers re-renders via useSyncExternalStore; the actual reconciliation is React's job.

License

MIT, see LICENSE.