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

@budarin/psw-plugin-serve-root-from-asset

v1.2.1

Published

Service Worker plugin for @budarin/pluggable-serviceworker that serves a configured cached HTML asset for root (/) navigation requests.

Readme

@budarin/psw-plugin-serve-root-from-asset

Плагин для @budarin/pluggable-serviceworker: отдаёт заранее закэшированный HTML‑ассет в ответ на навигационные запросы к корню (/).

Описание

Во многих продакшен-сборках весь фронтенд попадает в отдельную папку (например assets/ или static/): оттуда раздаются скрипты, стили и главная HTML-страница. При этом запрос к корню сайта (/) ожидает index.html в корне, тогда как физически он лежит среди ассетов. Этот плагин даёт возможность отвечать на запросы к / заранее закэшированным HTML-ассетом, чтобы приложение корректно открывалось по корневому URL и при обновлении страницы.

Установка

npm install @budarin/psw-plugin-serve-root-from-asset
# или
yarn add @budarin/psw-plugin-serve-root-from-asset
# или
pnpm add @budarin/psw-plugin-serve-root-from-asset

Пример использования

import { serveRootFromAsset } from '@budarin/psw-plugin-serve-root-from-asset';
import { initServiceWorker } from '@budarin/pluggable-serviceworker';
import { precache } from '@budarin/pluggable-serviceworker/plugins';

const cacheName = 'app-shell';

initServiceWorker(
    [
        precache({
            cacheName,
            assets: [
                '/assets/index.html',
                '/assets/main.js',
                '/assets/styles.css',
                ...
            ],
        }),
        serveRootFromAsset({
            cacheName,
            rootContentAssetPath: '/assets/index.html',
        }),
    ],
    { version: '1.0.0' }
);

Плагин перехватывает fetch‑события для пути / и отвечает содержимым HTML‑файла, который уже лежит в Cache Storage под указанным ключом. Если ассет не найден в кеше, плагин возвращает undefined, и обработка запроса может быть продолжена другими плагинами или дефолтной логикой.

API

serveRootFromAsset(config)

Создает экземпляр плагина.

config: ServeRootFromAssetConfig

  • cacheName: string Обязательно. Имя кеша (Cache Storage), в котором хранится корневой HTML‑ассет.

  • rootContentAssetPath: string Обязательно. Ключ/путь, под которым ассет лежит в кеше (например, /index.html).

  • order: number Опционально. Порядковый номер плагина. По умолчанию — 0.

  • headers: HeadersInit | (params: { request: Request; cached: Response }) => HeadersInit Опционально. Дополнительные заголовки, которые будут добавлены или переопределены при отдаче ответа из кеша для /.
    Можно передать:

    • статический объект/массив/Headers,
    • или функцию, которая получит текущий request и найденный cached‑ответ и вернёт набор заголовков.
      Плагин всегда устанавливает дефолтные заголовки, отключающие кэширование в браузере (Cache-Control: no-cache, no-store, must-revalidate, Pragma: no-cache, Expires: 0), чтобы избежать коллизий между HTTP-кэшем браузера и Cache Storage Service Worker. Заголовки из этого поля накладываются поверх дефолтных и могут их переопределить.

    Примеры:

    Статический объект:

    serveRootFromAsset({
        cacheName,
        rootContentAssetPath: '/assets/index.html',
        headers: {
            'Cache-Control': 'no-cache',
            'X-Custom-Header': 'value',
        },
    });

    Функция с динамическими заголовками:

    serveRootFromAsset({
        cacheName,
        rootContentAssetPath: '/assets/index.html',
        headers: ({ request, cached }) => ({
            'Cache-Control': request.url.includes('preview') ? 'no-store' : 'public, max-age=3600',
            'X-Served-From': 'service-worker',
        }),
    });

Поведение

  • Обрабатываются только навигационные запросы, у которых URL.pathname === '/'.
  • Для всех остальных путей плагин сразу возвращает undefined.
  • Для /:
    • открывается кеш с именем cacheName;
    • выполняется поиск ответа по ключу rootContentAssetPath;
    • если ответ найден — он возвращается как результат;
    • если нет — логируется предупреждение и возвращается undefined.

Ограничения

  • Плагин не наполняет кеш сам по себе. Ожидается, что где‑то еще в сервис‑воркере (например, на этапе предзагрузки/прекаша) нужный ассет уже добавлен в Cache Storage.
  • Плагин влияет только на запросы к корню (/); все остальные запросы проходят дальше без изменений.

🤝 License

MIT © budarin