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

enerthya.dev-serializable

v1.0.0

Published

Serializable types shared between the Enerthya bot and dashboard — GuildConfig, UserProfile, GuildMember, MemberStats, Giveaway, ModAction, Suggestion

Downloads

97

Readme

enerthya.dev-serializable

Tipos serializáveis compartilhados entre o bot e a dashboard da Enerthya. Inspirado em loritta-serializable-commons (MrPowerGamerBR / LorittaBot).

Zero dependências externas. Funciona em qualquer ambiente Node.js ≥ 18.


O que este pacote resolve

O bot e a dashboard falam a mesma linguagem via API REST interna. Sem um contrato de tipos compartilhado, qualquer lado pode enviar campos inesperados, valores nulos não tratados ou enums inválidos — e o erro só aparece em produção.

Este pacote define a forma exata de cada tipo de dado, com defaults, validação e serialização. Ambos os lados importam o mesmo pacote, garantindo que o contrato nunca saia de sincronia.


Tipos suportados

| Tipo | Schema espelhado | Descrição | |------|-----------------|-----------| | GuildConfig | Guild.js | Configuração completa do servidor | | UserProfile | User.js | Perfil global do usuário (economy, reputação, etc.) | | GuildMember | Member.js | Dados do membro no servidor (invites, strikes) | | MemberStats | MemberStats.js | Estatísticas de atividade (XP, nível, mensagens) | | Giveaway | Giveaways.js | Sorteio (participantes, vencedores, timestamps) | | ModAction | ModLog.js | Ação de moderação (ban, kick, warn, etc.) | | Suggestion | Suggestions.js | Sugestão de membro com votos e status |


API

Cada tipo expõe:

| Função | O que faz | |--------|-----------| | create[Tipo](partial?) | Cria objeto com defaults preenchidos | | validate[Tipo](obj) | Retorna { valid, errors[] } | | is[Tipo](obj) | Type guard — retorna boolean | | serialize[Tipo](doc) | Mongoose doc → plain JSON-safe object | | deserialize[Tipo](json) | REST JSON → objeto tipado com defaults |


Uso

const {
  createGuildConfig,
  serializeGuildConfig,
  isGuildConfig,
  validateGuildConfig,
  MOD_ACTION_TYPES,
  serializeModAction,
} = require("enerthya.dev-serializable");

// Serializar um documento Mongoose antes de enviar pela API
const config = serializeGuildConfig(guildDoc); // remove __v, $__, etc.

// Validar body de uma rota PATCH
const { valid, errors } = validateGuildConfig(req.body);
if (!valid) return res.status(400).json({ errors });

// Type guard simples
if (!isGuildConfig(data)) throw new Error("Dados inválidos");

// Constantes de enum para validação manual
if (!MOD_ACTION_TYPES.includes(req.body.type)) {
  return res.status(400).json({ error: "Tipo de moderação inválido" });
}

Constantes exportadas

// GuildConfig
AUTOMOD_ACTIONS       // ["TIMEOUT", "KICK", "BAN"]
MAX_WARN_ACTIONS      // ["TIMEOUT", "KICK", "BAN"]
TICKET_BUTTON_STYLES  // ["SUCCESS", "PRIMARY", "SECONDARY", "DANGER"]
DEFAULT_GUILD_CONFIG  // objeto completo com todos os defaults

// UserProfile
GENDER_VALUES         // ["M", "F", "NB"]
USER_FLAGS            // ["OWNER", "BETA_TESTER"]

// ModAction
MOD_ACTION_TYPES      // ["PURGE", "WARN", "TIMEOUT", ...14 tipos]

// Suggestion
SUGGESTION_STATUSES   // ["PENDING", "APPROVED", "REJECTED", "DELETED"]

Namespaces

Para uso avançado:

const { validators, serializers } = require("enerthya.dev-serializable");

validators.isGuildConfig(obj);
serializers.serializeGuildConfig(doc);

Estrutura

src/
├── index.js              ← Exporta tudo
├── types/
│   ├── GuildConfig.js    ← create, validate, defaults, enums
│   ├── UserProfile.js
│   ├── GuildMember.js
│   ├── MemberStats.js
│   ├── Giveaway.js
│   ├── ModAction.js
│   └── Suggestion.js
├── validators/
│   └── index.js          ← isGuildConfig, isUserProfile, etc.
└── serializers/
    └── index.js          ← serialize* + deserialize*
test.js                   ← 60 testes — node test.js (0 falhas)

Testes

node test.js
# Results: 60 passed, 0 failed