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

@rockcoredev/http

v0.1.0

Published

Isomorphic TypeScript HTTP client built on fetch.

Readme

@rockcoredev/http

Легковесный изоморфный HTTP-клиент на TypeScript поверх fetch.

Подходит для Node.js 18+, браузера и edge/runtime окружений.

Что умеет

  • Типизированные запросы и ответы
  • json-body с авто-content-type
  • Query-параметры
  • Таймаут на запрос
  • Retry с backoff
  • Ограничение запросов в секунду (RPS)
  • Proxy-конфиг для Node/undici-сценариев
  • HttpError с деталями ответа
  • Встроенный справочник HTTP-кодов

Установка

yarn add @rockcoredev/http

Быстрый старт

import { createHttpClient } from '@rockcoredev/http';

type User = {
  id: string;
  name: string;
};

const http = createHttpClient({
  baseUrl: 'https://api.example.com',
  timeoutMs: 5000,
  headers: {
    authorization: 'Bearer <token>'
  }
});

const user = await http.get<User>('/users/1');

await http.post('/users', {
  json: { name: 'Alice' }
});

Основное использование

GET с query

const users = await http.get<Array<{ id: string; name: string }>>('/users', {
  query: {
    page: 1,
    limit: 20,
    active: true
  }
});

POST с JSON

const created = await http.post<{ id: string }>('/users', {
  json: { name: 'Bob' }
});

Произвольный метод через request

const result = await http.request<{ ok: boolean }>('/resources/1', {
  method: 'PATCH',
  json: { enabled: false }
});

Обработка ошибок

Для не-2xx ответов бросается HttpError:

import { HttpError } from '@rockcoredev/http';

try {
  await http.get('/private');
} catch (error) {
  if (error instanceof HttpError) {
    console.error(error.status); // 401
    console.error(error.statusText); // Unauthorized
    console.error(error.url);
    console.error(error.body); // parsed JSON/text if possible
  }
}

Retry

По умолчанию retry применяется к идемпотентным методам и retryable HTTP-кодам.

const http = createHttpClient({
  baseUrl: 'https://api.example.com',
  retry: {
    attempts: 3,
    delayMs: 200,
    backoffFactor: 2,
    maxDelayMs: 2000
  }
});

Отключить retry для конкретного запроса:

await http.get('/health', { retry: false });

Лимит запросов (RPS)

const http = createHttpClient({
  baseUrl: 'https://api.example.com',
  requestsPerSecond: 10
});

Этот лимит общий для всех параллельных запросов данного экземпляра клиента.

Proxy (Node/undici-сценарии)

const http = createHttpClient({
  baseUrl: 'https://api.example.com',
  proxy: {
    headers: {
      'x-proxy-auth': 'proxy-token'
    },
    dispatcher: myUndiciDispatcher
  }
});

Отключить proxy для конкретного вызова:

await http.get('/public', { proxy: false });

Справочник HTTP-кодов

Пакет экспортирует справочник и хелперы:

  • HTTP_STATUS_TEXTS
  • getHttpStatusText(code)
  • RETRYABLE_HTTP_STATUS_CODES
  • isRetryableHttpStatusCode(code)

Пример:

import {
  getHttpStatusText,
  isRetryableHttpStatusCode
} from '@rockcoredev/http';

getHttpStatusText(404); // 'Not Found'
isRetryableHttpStatusCode(503); // true

API справка

createHttpClient(config?)

  • baseUrl?: string
  • headers?: HeadersInit
  • timeoutMs?: number
  • fetchFn?: typeof fetch (удобно для тестов)
  • requestsPerSecond?: number
  • retry?: RetryConfig
  • proxy?: ProxyConfig

Методы клиента

  • request<T>(path, options?)
  • get<T>(path, options?)
  • post<T>(path, options?)
  • put<T>(path, options?)
  • patch<T>(path, options?)
  • delete<T>(path, options?)

RequestOptions

Надстройка над RequestInit:

  • query?: Record<string, ...>
  • json?: unknown
  • timeoutMs?: number
  • retry?: RetryConfig | false
  • proxy?: ProxyConfig | false

RetryConfig

  • attempts?: number
  • delayMs?: number
  • maxDelayMs?: number
  • backoffFactor?: number
  • retryOnStatuses?: number[]
  • retryOnMethods?: string[]

ProxyConfig

  • headers?: HeadersInit
  • dispatcher?: unknown

Требования

  • Node.js >=18 (или современный runtime с fetch, AbortController, Headers)

Для разработки библиотеки

yarn install
yarn lint
yarn typecheck
yarn test:run
yarn build
yarn check:pkg

Публикация

  • После мержа PR в master запускается release workflow.
  • Workflow автоматически поднимает patch-версию в package.json и пушит коммит в master.
  • Workflow публикует пакет в npm только если версия из package.json еще не существует.
  • Публикация настроена через npm Trusted Publishing (GitHub OIDC), NPM_TOKEN не нужен.
  • В npm нужно один раз связать пакет @rockcoredev/http с этим GitHub-репозиторием как trusted publisher.