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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@devix-tecnologia/utils-ts

v1.0.0

Published

Utilitários TypeScript para projetos Devix

Readme

@devix-tecnologia/utils-ts

npm version TypeScript Node License

Coleção de utilitários TypeScript para projetos Devix, incluindo clientes HTTP, validadores e helpers diversos.

📦 Instalação

npm install @devix-tecnologia/utils-ts
# ou
pnpm add @devix-tecnologia/utils-ts
# ou
yarn add @devix-tecnologia/utils-ts

🚀 Uso

WebhookClient

Cliente HTTP configurável com suporte a múltiplos tipos de autenticação, retry automático e gerenciamento de tokens.

import { WebhookClient } from '@devix-tecnologia/utils-ts';

// Autenticação Bearer Token
const client = new WebhookClient({
  baseUrl: 'https://api.exemplo.com',
  auth: {
    type: 'bearer',
    token: 'seu-token-aqui',
  },
  // Opcional: configuração de retry
  retry: {
    maxRetries: 3,
    retryDelay: 1000,
  },
});

// Realizar requisições
const response = await client.request({
  method: 'POST',
  path: '/endpoint',
  body: { foo: 'bar' },
});

// Autenticação com login (gerenciamento automático de token)
const clientWithLogin = new WebhookClient({
  baseUrl: 'https://api.exemplo.com',
  auth: {
    type: 'bearer-login',
    loginUrl: '/auth/login',
    loginPayload: {
      email: '[email protected]',
      password: 'senha',
    },
    tokenExpiresIn: 3600, // segundos
  },
});

Tipos de autenticação suportados:

  • bearer: Token fixo no header Authorization
  • bearer-login: Login automático com refresh de token
  • basic: Basic Authentication
  • apikey: API Key em header customizado

Features:

  • ✅ Retry automático com backoff exponencial
  • ✅ Gerenciamento de token com refresh automático
  • ✅ Compressão gzip/deflate
  • ✅ Logging configurável (compatível com Winston/Pino)
  • ✅ Timeout configurável
  • ✅ Headers customizáveis

EaseClient

Cliente especializado para integração com a API EASE (sistema de tickets).

import { EaseClient, WebhookClient } from '@devix-tecnologia/utils-ts';

// Configurar cliente base
const webhookClient = new WebhookClient({
  baseUrl: 'https://api.ease.com',
  auth: {
    type: 'bearer',
    token: 'seu-token',
  },
});

// Criar cliente EASE
const easeClient = new EaseClient({
  webhookClient,
  paths: {
    criarTicket: '/tickets',
    consultarTicket: '/tickets',
    atualizarTicket: '/tickets',
  },
});

// Criar ticket
const novoTicket = await easeClient.criarTicket({
  titulo: 'Problema no sistema',
  descricao: 'Descrição detalhada',
  prioridade: 'alta',
});

// Consultar ticket
const ticket = await easeClient.consultarTicket({
  id: '12345',
});

// Atualizar ticket
const atualizado = await easeClient.atualizarTicket({
  id: '12345',
  status: 'resolvido',
  comentario: 'Problema corrigido',
});

DirectusClient

Utilitário para buscar dados de instâncias Directus externas.

import { fetchDataFromAnotherDirectus } from '@devix-tecnologia/utils-ts';

// Autenticação com token
const dados = await fetchDataFromAnotherDirectus({
  url: 'https://directus.exemplo.com',
  credentials: {
    type: 'token',
    token: 'seu-token-directus',
  },
  collection: 'produtos',
  query: {
    fields: ['id', 'nome', 'preco'],
    filter: { status: { _eq: 'ativo' } },
    limit: 100,
  },
});

// Autenticação com email/senha
const usuarios = await fetchDataFromAnotherDirectus({
  url: 'https://directus.exemplo.com',
  credentials: {
    type: 'email',
    email: '[email protected]',
    password: 'senha',
  },
  collection: 'usuarios',
  query: {
    fields: ['*'],
    limit: 50,
  },
});

Validação de Cron

Valida expressões cron e verifica intervalo mínimo entre execuções.

import { validarPeriodicidadeCron } from '@devix-tecnologia/utils-ts';

// Validar se cron executa com no mínimo 30 segundos de intervalo
const valido = validarPeriodicidadeCron('*/30 * * * * *', 30);
console.log(valido); // true

// Com limite customizado (5 minutos = 300 segundos)
const validoComLimite = validarPeriodicidadeCron('0 */5 * * *', 300);
console.log(validoComLimite); // true

// Com logger opcional
import pino from 'pino';
const logger = pino();

const resultado = validarPeriodicidadeCron('expressao-invalida', 30, logger);
// Logger receberá erro se expressão for inválida

Utilitários de URL

import { joinPathWithId } from '@devix-tecnologia/utils-ts';

// Concatena path com ID, normalizando barras
const url = joinPathWithId('/api/users', '12345');
console.log(url); // '/api/users/12345'

// Funciona com ou sem barra final
const url2 = joinPathWithId('/api/users/', '12345');
console.log(url2); // '/api/users/12345'

🔧 Logger Interface

Todos os clientes e funções que suportam logging seguem a interface Logger:

interface Logger {
  info(message: string, meta?: Record<string, unknown>): void;
  error(message: string, meta?: Record<string, unknown>): void;
  trace?(message: string, meta?: Record<string, unknown>): void;
  debug?(message: string, meta?: Record<string, unknown>): void;
  warn?(message: string, meta?: Record<string, unknown>): void;
  fatal?(message: string, meta?: Record<string, unknown>): void;
}

Compatível com:

import pino from 'pino';
import { WebhookClient } from '@devix-tecnologia/utils-ts';

const logger = pino();

const client = new WebhookClient({
  baseUrl: 'https://api.exemplo.com',
  auth: { type: 'bearer', token: 'token' },
  logger, // Logger será usado para todas as operações
});

📚 Documentação Completa

WebhookClient

Opções de Configuração:

interface WebhookClientOptions {
  baseUrl: string;
  auth: AuthConfig; // bearer | bearer-login | basic | apikey
  logger?: Logger;
  timeout?: number; // default: 30000ms
  retry?: {
    maxRetries: number;
    retryDelay: number;
  };
  headers?: Record<string, string>;
}

Métodos:

  • request<T>(config: RequestConfig): Promise<T> - Realiza requisição HTTP
  • isTokenExpired(): boolean - Verifica se token está expirado (para bearer-login)
  • refreshToken(): Promise<void> - Força refresh do token (para bearer-login)

EaseClient

Endpoints disponíveis:

  • criarTicket(request: CriarTicketRequest): Promise<CriarTicketResponse>
  • consultarTicket(request: ConsultarTicketRequest): Promise<ConsultarTicketResponse>
  • atualizarTicket(request: AtualizarTicketRequest): Promise<AtualizarTicketResponse>

DirectusClient

Função:

fetchDataFromAnotherDirectus<T>(config: DirectusConfig): Promise<T[]>

DirectusConfig:

interface DirectusConfig<Schema, Collection> {
  url: string;
  credentials:
    | { type: 'token'; token: string }
    | { type: 'email'; email: string; password: string };
  collection: string;
  query?: {
    fields?: string[];
    filter?: Record<string, unknown>;
    limit?: number;
    sort?: string[];
  };
}

🛠️ Desenvolvimento

# Instalar dependências
pnpm install

# Desenvolvimento com watch mode
pnpm dev

# Build
pnpm build

# Testes
pnpm test

# Testes com coverage
pnpm test:coverage

# Validar pacote
pnpm test:package

# Lint
pnpm lint
pnpm lint:fix

# Format
pnpm format
pnpm format:fix

# Type check
pnpm typecheck

📋 Requisitos

  • Node.js: >= 20.0.0
  • pnpm: >= 10.0.0
  • TypeScript: >= 5.0.0

🤝 Contribuindo

Veja CONTRIBUTING.md para instruções sobre como contribuir.

📄 Licença

ISC © Devix Tecnologia

🔗 Links