@cedvict/http-guardian

中文文档
0.5.0发布于 2026/10/23MITTypeScriptESM + CJS零依赖近 30 天下载 3468

Configurable HTTP client for TypeScript: auth (bearer/cookie), guards, cache+dedupe, dynamic envelope parsing presets, notifications, redirect handling.

原始使用文档
文档目录18 节
  1. Install
  2. Quick example (REST classic envelope)
  3. Binary responses
  4. Presets
  5. Auth modes
  6. Guards
  7. bearerRefreshGuard({ refreshFn, onAuthFailed?, ... })
  8. csrfGuard({ tokenFromCookie?, tokenFromStorage?, tokenFromH…
  9. correlationIdGuard({ headerName?, generator?, readResponseH…
  10. idempotencyGuard({ headerName?, applyTo?, respectExisting? …
  11. Recipe : mapper le traceId backend ↔ Sentry / OTel frontend
  12. Redirects
  13. Testing
  14. Cookie session refresh guard (single-flight, cooldown, anti…
  15. Notifier redaction (optional)
  16. Preset builder & aliases (stable DX)
  17. Stable auth refresh policy
  18. Plugins (config-time)

@cedvict/http-guardian

Core HTTP client (Promises) built on fetch.

Install

Runtime requirement: Node >= 22 (or any modern browser/edge runtime with fetch).

If you run in an environment without a global fetch, pass one explicitly via createHttpClient({ fetch }).

Prereleases (0.0.1-next.*) are published on the next dist-tag. Until a stable version is out, latest points to an older prerelease: install from next, or pin the exact version.

npm i @cedvict/http-guardian@next

Quick example (REST classic envelope)

import { createHttpClient, bearerAuth, createApiParserRestClassic, memoryCache } from "@cedvict/http-guardian";

const api = createHttpClient({
  baseUrl: "https://api.example.com",
  auth: bearerAuth(() => localStorage.getItem("token")),
  parser: createApiParserRestClassic(),
  cache: memoryCache({ maxEntries: 500 })
});

const res = await api.get<{ id: string; name: string }>("/me", {
  cache: { ttlMs: 30_000, tags: ["me"] }
});

if (res.ok) console.log(res.data.name);
else console.error(res.errors);

Binary responses

Use an explicit response type for downloads. Successful responses bypass the JSON envelope parser so their bytes stay intact. Error responses still use the normal content-type decoder, which preserves structured API errors.

const report = await api.get<Blob>("/reports/monthly", {
  responseType: "blob",
  headers: { accept: "application/pdf" },
});

if (report.ok) {
  const url = URL.createObjectURL(report.data);
  // Open or download the URL, then call URL.revokeObjectURL(url).
} else {
  console.error(report.errors);
}

responseType: "arrayBuffer" is also available for byte-oriented processing. Binary requests do not receive the default Accept: application/json header, and cache/deduplication keys keep blob and arrayBuffer responses separate.

Presets

  • createApiParserRestClassic()
  • createApiParserLaravel()
  • createApiParserNest()
  • createApiParserGraphQL({ allowPartialData? })
  • createApiParserStructured({ exposeMeta?, honorRetryableHint? }) — parser pour une enveloppe structurée typée : { success, code, message, details, retryable, issues[], i18n, meta }. En cas d'erreur, chaque AppError porte code, message et le booléen typé retryable. Les détails backend et les champs structurés (category, severity, i18n, traceId, spanId, envelope) restent disponibles dans details. Une issue peut remplacer l'indication retryable de l'enveloppe.
  • createApiParserProblem({ codeMembers?, requestIdHeader? }) — Problem Details (RFC 9457, application/problem+json). Message from detail, else title; code from the first non-blank member of codeMembers (default ["code"], e.g. ["rule", "code"]); every extension kept in details.extensions (ProblemErrorDetails), with retryAfter (the Retry-After header) and requestId. A boolean retryable member becomes AppError.retryable. Validation problems give one AppError per input, from errors ({ detail, pointer }) or invalid-params ({ name, reason }).
  • createApiParserDetail({ requestIdHeader? }) — APIs without success envelope: the success body is the data, errors are { detail, code?, retryAfter?, requestId? }. A string detail gives one AppError (code kept); a 422 validation detail array gives one AppError per input, with field (loc without its body/query/... source) and code (the issue type). details (DetailErrorDetails) carries retryAfter (the Retry-After header, delay or HTTP date, else the body field, in whole seconds), requestId (body, else X-Request-ID), loc and the raw body.

A parser may read the headers of a failed response: getErrors(raw, status, response?) receives { headers } as an optional third argument.

Without a notifier, the client uses consoleNotifier, which writes every failure to the console. Pass silentNotifier when the application shows its own messages from result.errors.

Auth modes

  • bearerAuth(() => token)
  • cookieAuth({ credentials: "include", csrf: { headerName, getToken } })
  • noAuth()

Guards

Les guards composent un middleware autour de chaque requête.

bearerRefreshGuard({ refreshFn, onAuthFailed?, ... })

Refresh JWT Bearer single-flight : sur 401, un seul refreshFn() est invoqué ; toutes les autres requêtes 401 reçues pendant ce refresh attendent dans une queue partagée puis sont rejouées avec le nouveau token. Si le refresh échoue, onAuthFailed(error) est appelé une seule fois et toutes les requêtes en queue voient le 401 d'origine.

import { createHttpClient, bearerAuth, bearerRefreshGuard } from "@cedvict/http-guardian";

createHttpClient({
  auth: bearerAuth(() => tokenStore.access()),
  guards: [
    bearerRefreshGuard({
      refreshFn: async () => {
        const { accessToken, refreshToken } = await api.refresh();
        tokenStore.set(accessToken, refreshToken);
        return { accessToken, refreshToken };
      },
      onAuthFailed: () => router.navigate("/login"),
      skipRefreshFor: (ctx) => ctx.url.includes("/auth/"),
    }),
  ],
});

csrfGuard({ tokenFromCookie?, tokenFromStorage?, tokenFromHeader?, headerName?, applyTo? })

Injecte un header X-CSRF-Token (défaut) sur les méthodes mutantes (POST/PUT/PATCH/DELETE). SSR-safe : si tokenFromCookie est utilisé hors browser (typeof document === 'undefined'), le guard skippe silencieusement.

csrfGuard(
  isPlatformBrowser(platformId)
    ? { tokenFromCookie: "csrf_token" }
    : { tokenFromStorage: () => null },
);

correlationIdGuard({ headerName?, generator?, readResponseHeader? })

Injecte un header X-Correlation-Id (UUID v4 par défaut, fallback Math.random()+timestamp si crypto.randomUUID absent). L'ID est stable entre retries (mémorisé sur le ctx). Si la réponse contient le même header, il est copié dans ctx.meta.correlationId pour les plugins downstream (logger, sentry, otel).

💡 Pattern "X-Request-Id" : si ton backend (ops, ELK, Datadog…) utilise le header X-Request-Id plutôt que X-Correlation-Id pour stitcher les logs front/back, change juste headerName :

correlationIdGuard({ headerName: "X-Request-Id" })

Pas besoin d'OpenTelemetry côté front, ni d'un second guard : c'est le même mécanisme avec un nom différent. Combinable avec un OTel traceparent : les deux headers coexistent sans conflit.

idempotencyGuard({ headerName?, applyTo?, respectExisting? })

Injecte un header X-Idempotency-Key (UUID par défaut) sur POST/PUT/PATCH. La clé est stable entre retries — sinon l'idempotence côté serveur est cassée. Respecte une clé fournie via RequestOptions.idempotencyKey, ctx.idempotencyKey, ou directement via header.

Recipe : mapper le traceId backend ↔ Sentry / OTel frontend

Quand le backend renvoie une enveloppe avec un meta.traceId (et spanId) — typiquement via createApiParserStructured — il est utile de stitcher cette trace avec le span/event front-end pour qu'un incident Sentry pointe directement vers la trace backend correspondante (et inversement).

Le pattern repose sur deux briques :

  1. correlationIdGuard génère un X-Correlation-Id propagé sur la requête, et lit le header de réponse pour exposer l'ID dans ctx.meta.correlationId.
  2. createApiParserStructured stocke traceId / spanId dans errors[].details (en cas d'erreur). Pour les chemins succès, on lit le header de réponse via un petit guard dédié.
import {
  createHttpClient,
  bearerAuth,
  correlationIdGuard,
  createApiParserStructured,
  type Guard,
} from "@cedvict/http-guardian";
import { sentryPlugin } from "@cedvict/http-guardian-plugin-sentry";
import { otelPlugin } from "@cedvict/http-guardian-plugin-otel";
import * as Sentry from "@sentry/browser";

// Lit X-Trace-Id / X-Span-Id de la réponse et les pose sur ctx.meta pour
// les plugins downstream (sentry, otel, logger).
const traceMetaGuard: Guard = async (ctx, next) => {
  const res = await next(ctx);
  const traceId = res.headers.get("x-trace-id");
  const spanId = res.headers.get("x-span-id");
  if (traceId || spanId) {
    ctx.meta ??= {};
    if (traceId) ctx.meta.traceId = traceId;
    if (spanId) ctx.meta.spanId = spanId;
  }
  return res;
};

const api = createHttpClient({
  baseUrl: "https://api.example.com",
  auth: bearerAuth(() => token),
  parser: createApiParserStructured(),
  guards: [correlationIdGuard(), traceMetaGuard],
  plugins: [
    sentryPlugin({
      // shouldCapture reçoit le ctx → on lit ctx.meta pour tagger l'event Sentry.
      shouldCapture: ({ status, ctx }) => {
        if (status && status >= 500) {
          Sentry.getCurrentScope().setTags({
            "backend.trace_id": ctx.meta?.traceId ?? "",
            correlation_id: ctx.meta?.correlationId ?? "",
          });
          return true;
        }
        return false;
      },
    }),
    otelPlugin({
      setAttributes: (span, ctx) => {
        if (ctx.meta?.traceId) span.setAttribute("backend.trace_id", ctx.meta.traceId);
        if (ctx.meta?.spanId) span.setAttribute("backend.span_id", ctx.meta.spanId);
        if (ctx.meta?.correlationId) span.setAttribute("correlation_id", ctx.meta.correlationId);
      },
    }),
  ],
});

Côté erreur, l'enveloppe parsée par createApiParserStructured expose déjà traceId / spanId dans result.errors[0].details :

const r = await api.post("/orders", { json: payload });
if (!r.ok) {
  const d = r.errors[0]?.details as { traceId?: string; spanId?: string } | undefined;
  console.error("backend trace:", d?.traceId, d?.spanId);
}

Redirects

  • redirects: { mode: "follow" | "manual" | "error", maxHops, onRedirect }

Testing

See TESTING.md.

If you use cookie-based auth and your backend exposes a refresh endpoint, you can add the safe refresh guard:

import { createHttpClient, cookieAuth, cookieSafeRefreshGuard, createApiParserRestClassic } from "@cedvict/http-guardian";

const api = createHttpClient({
  baseUrl: "https://api.example.com",
  auth: cookieAuth({ credentials: "include" }),
  parser: createApiParserRestClassic(),
  guards: [
    cookieSafeRefreshGuard({
      refreshPath: "/auth/refresh", // or absolute: "https://auth.example.com/refresh"
      maxRetry: 1,                  // anti-loop (default)
      honorRetryAfter: true         // cooldown on 429 (default)
    })
  ],
});

You can disable any auth/refresh behavior per-request with noAuth: true:

await api.get("/public/health", { noAuth: true });

Notifier redaction (optional)

If you provide a custom notifier and it logs/sends events to telemetry, you can add a redact function to strip secrets from the event payload (e.g. query params in url):

import type { Notifier, NotifyEvent } from "@cedvict/http-guardian";

const notifier: Notifier = {
  redact: (e: NotifyEvent) => ({ ...e, url: e.url.replace(/\?.*$/, "") }),
  notify: (e) => console.error(e),
};

Preset builder & aliases (stable DX)

If you want a 1-liner setup without losing access to createHttpClient, use the preset builder:

import { createPresetBuilder } from "@cedvict/http-guardian";

const api = createPresetBuilder({ baseUrl: "https://api.example.com" })
  .cookie({ credentials: "include" })
  // opt-in only:
  // .cookieRefresh({ refreshPath: "/auth/refresh", mePath: "/auth/me" })
  .create();

Aliases (thin wrappers around the preset builder):

  • createCookieClient({ baseUrl, refresh?: CookieSafeRefreshGuardOptions | null, ... })
  • createBearerClient({ baseUrl, getToken, ... })

Stable auth refresh policy

  • Cookie auth: refresh is opt-in (add cookieRefresh(...) or pass refresh to createCookieClient).
  • Bearer auth: refresh is disabled by default.

Plugins (config-time)

plugins are applied synchronously during createHttpClient(...) to mutate a draft options object.

Contract:

  • Applied in order
  • De-duplicated by name (first wins)

版本与发布记录

@cedvict/http-guardian 共发布 22 个版本,首次发布于 2026/02/09;过去 12 个月发布了 22 个版本。

版本发布日期距今
0.5.0latest2026/10/2317 天前
0.4.02026/10/081 个月前
0.2.12026/10/081 个月前
0.2.02026/10/011 个月前
0.1.02026/10/011 个月前
0.0.1-next.17next2026/10/011 个月前

其他发布通道:legacy → 0.3.1,next → 0.0.1-next.17。

关于 @cedvict/http-guardian 的常见问题

@cedvict/http-guardian 是什么?

Configurable HTTP client for TypeScript: auth (bearer/cookie), guards, cache+dedupe, dynamic envelope parsing presets, notifications, redirect handling.

如何安装 @cedvict/http-guardian?

在项目目录运行 npm install @cedvict/http-guardian,或使用 pnpm add / yarn add / bun add。

@cedvict/http-guardian 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cedvict/http-guardian 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cedvict/http-guardian 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cedvict/http-guardian 可以商用吗?

@cedvict/http-guardian 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cedvict/http-guardian 的下载量有多少?

根据 npm 官方下载统计,@cedvict/http-guardian 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,468 次,日均约 116 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cedvict/http-guardian 还在维护吗?

最新版本 0.5.0 发布于 2026/10/23(17 天前);至今共发布 22 个版本,其中过去 12 个月发布了 22 个;首次发布于 2026/02/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。