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

@micusion/freshl

v0.1.0

Published

Client-side cache with smart invalidation: policies, human-readable tags, dependency cascades, events and subscribers. Zero dependencies.

Readme

freshl

License: Apache 2.0 Tests Dependencies Size TypeScript

Клиентский кэш с умной инвалидацией. Чистый JavaScript, ноль зависимостей, Apache 2.0.

Read this in English.

freshl закрывает три сложных вопроса клиентского кэширования:

  1. Политика кэширования — TTL, stale-while-revalidate, stale-if-error, LRU-вытеснение.
  2. Инвалидация — по ключам, человеко-читаемым тегам (users, orders), доменным событиям (user:updated) и каскадам по зависимостям (feed зависит от users → умирает вместе с ним).
  3. Подписчики — кто и когда получает свежие данные: на ключ, тег, событие или глобальный поток инвалидаций.
import { createFreshl } from 'freshl';

const cache = createFreshl({
  defaultPolicy: { ttl: 60_000, swr: 300_000 }, // свежий 1 мин, потом SWR 5 мин
  maxEntries: 500,                              // LRU
});

// ручной режим
cache.set('user:1', user, { tags: ['users'] });
cache.get('user:1');

// режим с fetcher (SWR + дедупликация запросов)
const user = await cache.fetch('user:1', () => api.getUser(1), {
  tags: ['users'],
  policy: { ttl: 30_000, staleIfError: 600_000 },
});

// инвалидируем ровно то, что изменилось
cache.bindEvent('user:updated', {
  resolve: (payload) => ({ keys: payload.ids.map((id) => `user:${id}`) }),
});
cache.emit('user:updated', { ids: [42] });

// подписка: автоматически перечитываем инвалидированные ключи
cache.on('invalidate', ({ keys }) => keys.forEach(refetch));

Возможности

  • Политикиttl / swr / staleIfError глобально и на запись; LRU через maxEntries.
  • SWR-режим с fetcher — мгновенно отдаёт стейл, ревалидирует в фоне, сворачивает одновременные вызовы в один in-flight промис.
  • Защита от гонок — результат fetcher'а отбрасывается, если ключ успели инвалидировать во время запроса (мертвецы не воскресают).
  • Инвалидация по тегам — одним вызовом убить всё с тегом users.
  • Каскады зависимостейdependsOn на ключи/теги, транзитивно, O(достижимых ключей).
  • Доменные событияbindEvent('order:cancelled', { tags: ['orders'] }), в том числе resolve-правила, вычисляющие цели из payload события.
  • Подписчикиon() на ключ, тег, событие, несколько целей сразу или глобальный поток инвалидаций; всегда возвращает функцию отписки.
  • Встроенная инструментацияcache.stats(): hit rate, средние латентности попаданий/промахов, сетевые вызовы, инвалидации, вытеснения.
  • Опциональная персистентность — глобальный localStorage, Storage-подобный объект или любой адаптер { get, set, del, keys }; полностью протухшие записи не воскрешаются.
  • Ноль зависимостей, один файл — ~23 КБ исходник, ~6.3 КБ gzip; ESM + UMD + CJS.

Установка

npm install freshl   # или просто скопируйте src/freshl.js
<!-- UMD через script-тег: глобальная переменная `Freshl` -->
<script src="dist/freshl.umd.js"></script>

TypeScript-типы входят в пакет (index.d.ts).

Документация

Разработка

npm test          # node --test, 27 тестов
npm run build     # dist/freshl.esm.js, dist/freshl.umd.js, dist/freshl.umd.cjs
npm run demo      # демо-сервер → http://localhost:8080

CI

GitHub Actions гоняет тесты на Node 20/22/24, пересобирает dist/ и падает, если закоммиченный бандл разошёлся с src/freshl.js (workflow).

Пропустить весь пайплайн можно маркером в сообщении коммита или заголовке PR (регистр не важен): [no-CI], [no ci], [skip-ci], [skip ci], [ci-skip].

git commit -m "docs: опечатка в ридми [no-CI]"   # CI будет пропущен

Лицензия

Apache License 2.0 © 2026 Micusion