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 🙏

© 2025 – Pkg Stats / Ryan Hefner

key-hierarchy

v3.0.9

Published

A tiny TypeScript library for managing key hierarchies. The perfect companion for TanStack Query.

Readme

Features

  • Centralized key management for TanStack Query
  • Collision-free by design
  • Declarative and intuitive API
  • Type-safe static and dynamic keys
  • Tiny at less than 1 kB gzip

Installation

# pnpm
$ pnpm add key-hierarchy

# yarn
$ yarn add key-hierarchy

# npm
$ npm install key-hierarchy

Usage

This library provides a declarative API for defining key hierarchies. Key hierarchies can contain both static and dynamic segments, with dynamic segments being defined through dynamic and its generic parameter.

This approach and API ensure type-safety and collision-free key management. With this centralized declaration of keys, no key collisions can occur, and all keys are guaranteed to be unique. As such, it is ideal for managing TanStack Query queryKeys in large applications with multiple developers.

import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    getAll: true,
    create: true,
    byId: dynamic<number>().extend({
      get: true,
      update: true,
      delete: true,
    }),
  },
  posts: {
    byUserId: dynamic<number>(),
  },
}))

// Static keys
const getAllUsersKey = keys.users.getAll // readonly ['users', 'getAll']

// Dynamic keys with continued hierarchy
const updateUserKey = keys.users.byId(42).update // readonly ['users', ['byId', number], 'update']

// Partial keys with `__key`
const userByIdKey = keys.users.byId(42).__key // readonly ['users', ['byId', number]]

// Dynamic keys as terminal segment
const postsByUserIdKey = keys.posts.byUserId(42) // readonly ['posts', ['byUserId', number]]

Modularization

Should key hierarchy definitions grow too big to manage them within a single file, defineKeyHierarchyModule can be used to create modular key hierarchies. Defining modules this way retains type inference and ensures that keys are still unique when accessed from the root hierarchy.

// user-keys.ts
import { defineKeyHierarchyModule } from 'key-hierarchy'

export const userKeyModule = defineKeyHierarchyModule((dynamic) => ({
  getAll: true,
  create: true,
  byId: dynamic<number>().extend({
    get: true,
    update: true,
    delete: true,
  })
}))

// post-keys.ts
import { defineKeyHierarchyModule } from 'key-hierarchy'

export const postKeyModule = defineKeyHierarchyModule((dynamic) => ({
  byIdUserId: dynamic<number>()
}))

// keys.ts
import { defineKeyHierarchy } from 'key-hierarchy'

export const keys = defineKeyHierarchy({
  users: userKeyModule,
  posts: postKeyModule,
  config: true
})

Options

The following options can be configured through the optional second parameter of defineKeyHierarchy. All options are optional with default values as described below.

freeze: boolean

Defaults to false.

If set to true, the generated keys will be frozen, preventing any modifications. This ensures immutability at runtime in your key hierarchy.

  • The return type of defineKeyHierarchy already prevents modification in TypeScript, even with freeze: false.
  • Object.freeze() will be called on the generated keys and all nested objects or arrays.
  • structuredClone will be used to create a deep copy of any key arguments before freezing them to ensure the original arguments remain unchanged.
import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy((dynamic) => ({
  posts: {
    create: true,
    byUser: dynamic<{ id: number }>()
  },
}), { freeze: true })

// Throws with `freeze: true`
keys.posts.create.push('newSegment') 

// Prevents modifications with `freeze: true`
keys.posts.create = ['newSegment']

// Prevents modification of arguments
const postsByUserKey = keys.posts.byUser({ id: 42 }) // readonly ['posts', ['byUser', DeepReadonly<{ id: number }>]]
// Throws with `freeze: true`
postsByUserKey[1][1].id = 7

method: 'proxy' | 'precompute'

Defaults to 'proxy'.

By default, the key hierarchy is created dynamically with Proxy objects. If this is not suitable, the method: 'precompute' option can be used to generate the keys at build time instead of runtime. This can improve performance in scenarios where the key hierarchy is large or complex, at the cost of a more extensive upfront computation.

TanStack Query Integration

This library works seamlessly with TanStack Query. Below are examples for React and Vue.

@tanstack/react-query

import { useQuery } from '@tanstack/react-query'
import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    byId: dynamic<number>().extend({
      get: true
    })
  }
}))

export function useUserByIdQuery(userId: number) {
  return useQuery({
    queryKey: keys.users.byId(userId).get,
    queryFn: () => fetchUserById(userId)
  })
}

@tanstack/vue-query

Important: When using defineKeyHierarchy with @tanstack/vue-query, the freeze option may not be true if query key arguments are reactive.

import { useQuery } from '@tanstack/vue-query'
import { defineKeyHierarchy } from 'key-hierarchy'
import { MaybeRefOrGetter, toValue } from 'vue'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    byId: dynamic<MaybeRefOrGetter<number>>().extend({
      get: true
    })
  }
}))

export function useUserByIdQuery(userId: MaybeRefOrGetter<number>) {
  return useQuery({
    queryKey: keys.users.byId(userId).get,
    queryFn: () => fetchUserById(toValue(userId))
  })
}

Development

# install dependencies
$ pnpm install

# build for production
$ pnpm build

# lint project files
$ pnpm lint

# run tests
$ pnpm test

License

MIT - Copyright © Jan Müller