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

safe-shape

v3.5.1

Published

Umbrella package for SafeShape runtime contracts and tooling.

Readme

Общий пакет SafeShape

English | Русский

Runtime-контракты для TypeScript: проверка неизвестных данных, вывод типов, экспорт схем и проверка совместимости API через одну зависимость.

Версия 3.5.0 добавляет AI-контракты и MCP через entry safe-shape/mcp, автоматически устанавливаемый с umbrella. Runtime umbrella сохраняет совместимость. Требуются Node >=20.10 и ESM.

npm install safe-shape
import { object, string, createContractSnapshotV2, toJsonSchema, toTypeScriptType,
  validateSchema, type InferInput, type InferOutput } from "safe-shape";
const user = object({ id: string() }).annotate({ title: "User" });
const report = validateSchema(user, { id: "user_1" });
const snapshot = createContractSnapshotV2(user, { id: "user" });
const jsonSchema = toJsonSchema(user);
const source = toTypeScriptType(user, { name: "User" });
type Input = InferInput<typeof user>;
type Output = InferOutput<typeof user>;

API workflow

Неизменяемый каталог endpoints, проверка запросов до fetch и ответов после decoding, экспорт OpenAPI 3.1 и сравнение API snapshots. Добавлено в 3.4.0 и сохранено в 3.5.0.

import {
  object, string, httpEndpoint, apiContract,
} from "safe-shape";

export const api = apiContract({
  getUser: httpEndpoint({
    method: "get",
    path: "/users/{id}",
    request: { params: object({ id: string({ minLength: 1 }) }) },
    responses: {
      200: object({ id: string() }),
      404: object({ message: string() }),
    },
  }),
});

Сохраните каталог в api.mjs. Вызовы клиента вынесите в отдельный модуль, чтобы CLI imports не отправляли HTTP-запросы:

import { createApiClient, toOpenApi, createApiSnapshot, compareApiSnapshots } from "safe-shape";
import { api } from "./api.mjs";

const client = createApiClient(api, { baseUrl: "https://api.example.com/v1" });
const result = await client.getUser({ params: { id: "user_1" } });
if (result.success && result.status === 200) console.log(result.data.id);

const openapi = toOpenApi(api, { title: "Users", version: "1.0.0" });
const baseline = createApiSnapshot(api);
const comparison = compareApiSnapshots(baseline, createApiSnapshot(api));
console.log(openapi.openapi, comparison.decision); // 3.1.0, compatible

Клиент обращается к вашему существующему серверу; SafeShape не устанавливает router. Типы path parameters и response data по status выводятся из каталога. Невалидный запрос останавливается до transport. Объявленный ответ 404 — типизированный результат; ошибки валидации, сети и decoding имеют success: false. Warnings сохраняются; второй аргумент вызова принимает { signal }.

Для браузера импортируйте apiContract, httpEndpoint, createApiClient из @safe-shape/api/client, а схемы — из @safe-shape/core. OpenAPI и snapshot tooling используют Node entry.

Transport поддерживает JSON, строковые path parameters, scalar query fields и непустые массивы с повторяющимися query keys. Transforms, stripping objects, cookies, multipart, автоматические retries и server routing не предоставляются. См. полный API reference и запускаемый пример.

CLI

Сохраните модуль с экспортом каталога как api.mjs, затем выполните:

npx safe-shape api export --module ./api.mjs --export api --title Users --version 1.0.0 --out ./openapi.json
npx safe-shape api snapshot --module ./api.mjs --export api --out ./api.contract.json
npx safe-shape --json api check --module ./api.mjs --export api --against ./api.contract.json

Exit codes проверки: 0 для совместимых изменений, 2 для миграции или ручного review, 1 для operational errors. Проверка читает baseline без его замены. См. CLI reference.

Переэкспортируются публичные API core, compat, http, json-schema, typescript, validation и api. Установка также приносит cli с бинарником safe-shape. Дополнительной runtime-семантики общий пакет не вводит.

Все ограничения, политики объектов, immutable-диагностика, warnings и явные async-методы совпадают с исходными пакетами. Доступны Standard Schema V1 и createStandardJsonSchema, safeToJsonSchema/JsonSchemaExportError, группировка ошибок, формы, recovery HTTP, композиция объектов, checked pipe, snapshots, checkContractConnection и рекурсивные TypeScript-объявления. Зарезервированные имена импортируйте с alias, например enum as enumSchema.

В версии 3.3.0 также переэкспортируются describeOutputBound и checkSchemaConnection; см. проверяемые выходы. Для browser runtime без инструментов Node выбирайте отдельный core-пакет; см. архитектуру.

AI-контракты и MCP

Одна команда npm install safe-shape устанавливает локальный stdio-сервер и адаптер AI-инструментов. Импортируйте MCP API из safe-shape/mcp; основной импорт не загружает MCP/SDK. Отдельный @safe-shape/mcp по-прежнему доступен. Установка umbrella включает SDK даже без использования этого entry. См. MCP.