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

@baukit/api-runtime

v0.3.0

Published

Shared client-side behavior for product APIs: environment selection, auth and request-ID headers, trace propagation, normalized errors, and safe retries.

Readme

@baukit/api-runtime

Shared client-side behavior for Baukit product APIs: explicit environment selection, bearer-token and request-ID headers, optional W3C trace propagation, normalized errors, safe retries, and a test fetch transport. It works in browsers and React Native and never reads process.env.

Generated client usage

The package wraps openapi-fetch; each product continues to own its generated paths type.

import { createApiClient, resolveApiEnvironment } from '@baukit/api-runtime';
import type { paths } from './generated/api.js';

const environment = resolveApiEnvironment('production', {
  development: 'http://localhost:3000',
  production: 'https://api.example.com',
});

export const api = createApiClient<paths>({
  ...environment,
  tokenProvider: async () => session.accessToken ?? null,
  onUnauthorized: async ({ canRetry }) => {
    if (!canRetry) return 'handled';
    const token = await session.accessToken({ forceRefresh: true });
    return token === undefined ? 'handled' : 'retry-once';
  },
});

const { data } = await api.GET('/widgets');

If a generated wrapper already creates the client, pass it a configured runtime instead:

import createClient from 'openapi-fetch';
import { createApiRuntime } from '@baukit/api-runtime';

const runtime = createApiRuntime({
  baseUrl: 'https://api.example.com',
  environment: 'production',
  tokenProvider: getAccessToken,
});

const api = createClient<paths>({ baseUrl: runtime.baseUrl, fetch: runtime.fetch });

tokenProvider runs for every logical request; the runtime does not cache its result. Every request receives a new UUID in x-request-id. Configure traceparentProvider only when the product has a tracing implementation.

Unauthorized recovery

onUnauthorized remains a notification hook when it returns void or 'handled': the normalized 401 is thrown as before. Returning 'retry-once' explicitly asks the runtime to reacquire credentials through tokenProvider and replay a preflighted request clone. The hook receives canRetry: false when the body cannot be cloned; returning 'retry-once' then safely falls back to the original 401. Recovery runs at most once, a second 401 stops, and the original AbortSignal remains effective during refresh and replay.

Set onUnauthorizedExhausted when the product must stop schedulers or move to a signed-out state after that replay also returns 401. It receives the final normalized error with canRetry: false; observer failures never replace the API failure.

This handshake does not make arbitrary mutations safe. Replaying POST, PATCH, or any write whose outcome may already have committed still requires a product/server idempotency contract. Follow the repository's integration reliability recipe, offline replay contract, and add-endpoint replay/idempotency guidance.

Unverified display identity hints

unverifiedDisplayIdentityHintsFromJwt decodes local JWT claims for display only. It prefers name, then joined given_name and family_name, preferred_username, and email. It derives at most two initials. Invalid tokens and missing claims use product-supplied fallback text.

import { unverifiedDisplayIdentityHintsFromJwt } from '@baukit/api-runtime';

const hints = unverifiedDisplayIdentityHintsFromJwt(session.accessToken, {
  displayName: 'Local account',
  initials: 'LA',
});

The claims have not been verified. Never use these hints for authorization, a storage partition, analytics identity, cache ownership, or synchronization ownership. Those decisions need the server-validated subject. Existing web and native helpers can be replaced directly, but products must keep their fallback copy at the call site.

Error handling

Non-success responses throw one of three typed errors. Raw fetch/CORS errors are always wrapped.

import { isApiError, isHttpError, isNetworkError } from '@baukit/api-runtime';

try {
  await api.POST('/widgets', { body: widget });
} catch (error) {
  if (isApiError(error, 'validation_failed')) {
    showValidation(error.details, error.requestId);
  } else if (isNetworkError(error)) {
    showOfflineMessage();
  } else if (isHttpError(error)) {
    reportUnexpectedResponse(error.status, error.requestId);
  } else {
    throw error;
  }
}
  • ApiError: a valid Baukit { error: { code, message, request_id, details } } envelope.
  • HttpError: an HTTP failure with a missing or malformed envelope, including non-JSON bodies.
  • NetworkError: no HTTP response, such as an offline, DNS, fetch, or CORS failure. Aborts set aborted to true.

The backend message is public, safe fallback text. Localized clients should resolve ApiError.code plus structured ApiError.details through their product catalog and use ApiError.message only when that resolution is unavailable. Do not parse the message or use it as a stable localization key.

Retry semantics

Retries use exponential backoff with full jitter, capped by maxDelayMs. The same request ID is retained across attempts.

| Request/result | Default | Configurable | | ----------------------------- | ---------------- | -------------------------------------------- | | GET, HEAD + network error | Retry | maxRetries, delays, or disable | | GET, HEAD + 502/503/504 | Retry | maxRetries, delays, or disable | | OPTIONS, PUT, DELETE | No retry | May be explicitly opted in through methods | | Any 4xx | Never | No | | POST, PATCH | Never | No | | Abort | Stop immediately | No |

Defaults are two retries, a 100 ms initial ceiling, and a 2,000 ms maximum ceiling. Use retry: false to disable retries.

Tests

MockFetch queues responses, errors, or handlers and records cloned requests:

const mock = new MockFetch().enqueueJson({ widgets: [] });
const runtime = createApiRuntime({
  baseUrl: 'https://api.example.test',
  environment: 'test',
  fetch: mock.fetch,
});

await runtime.fetch('/widgets');
mock.assertRequest(0, { method: 'GET', url: 'https://api.example.test/widgets' });
mock.assertQueueEmpty();