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

@elephant.js/database

v0.1.0-beta

Published

Banco de dados embutido, tipado e persistente para Node.js. Validação com Zod + SQLite via sql.js.

Readme

🐘 @elephant.js/database

Banco de dados embutido, tipado e persistente para Node.js
Validação real com Zod • Armazenamento em SQLite (via sql.js)

“Elephants never forget”
Este pacote cuida da persistência, validação e integridade dos seus dados sem exigir servidor de banco externo.


✨ Características

  • 💾 Persistência local baseada em SQLite (arquivo único)
  • 🧠 Validação completa e em tempo real com Zod
  • 🧩 Tipagem automática perfeita no TypeScript
  • 🔒 Suporte nativo a campos unique e required
  • 🆔 _id automático (UUID) ou personalizado
  • 📦 Ideal para CLIs, ferramentas locais, bots, micro-serviços, apps desktop e embarcados
  • 🚫 Sem ORM pesado, sem configuração complexa, sem servidor externo
  • 🔄 Atualização de instância local com document.update()
  • 🔍 Busca inteligente em arrays (findOne({ tags: "dev" }) funciona!)

📦 Instalação

pnpm add @elephant.js/database

ou

npm install @elephant.js/database

📌 Uso Básico

Importação

const { ElephantDB, Schema, z } = require("@elephant.js/database");
// ou em TypeScript:
// import { ElephantDB, Schema, z } from "@elephant.js/database";

📐 Definindo um Schema

Schemas usam Zod para validação poderosa.

const userSchema = new Schema({
  _id: {
    type: z.string().default(() => crypto.randomUUID()), // opcional
  },
  username: {
    type: z.string().min(3),
    required: true,
    unique: true,
  },
  email: {
    type: z.string().email(),
    required: true,
    unique: true,
  },
  age: {
    type: z.number().min(0).default(18),
  },
  tags: {
    type: z.array(z.string()).default([]),
  },
  isActive: {
    type: z.boolean().default(true),
  },
});

Regras do Schema

  • type: obrigatório — deve ser um schema Zod
  • required: true: campo obrigatório
  • unique: true: valida unicidade em todo o collection
  • default: valor estático ou função (executada no create)
  • _id: gerado automaticamente se não fornecido

🗄️ Inicializando o Banco

const db = new ElephantDB("./data/app.db");
await db.connect();

O arquivo é criado automaticamente. Use ":memory:" para banco em memória.


🧠 Criando um Model

const User = db.model("User", userSchema);

➕ Criar Documento

const user = await User.create({
  username: "jatoba",
  email: "[email protected]",
  age: 25,
});

console.log(user.toJSON());
/*
{
  _id: "a1b2c3d4-...",
  username: "jatoba",
  email: "[email protected]",
  age: 25,
  tags: [],
  isActive: true
}
*/

Retorna uma instância de documento com métodos úteis.


🔄 Atualizar Documento

Via instância (atualiza objeto local!)

await user.update({ username: "jatobaa", age: 26 });
console.log(user.toJSON().username); // → "jatobaa"

Via método estático (busca por qualquer campo)

await User.updateOne({ _id: user._id }, { isActive: false });
await User.updateOne({ email: "[email protected]" }, { age: 30 });

➕ Push em Arrays

await User.push(user._id, "tags", "elephant-db");
await User.push(user._id, "tags", "developer");
await User.push(user._id, "tags", "zod");

Só funciona em campos definidos como array no schema.


🔍 Buscas

Buscar um documento (por qualquer campo)

const found = await User.findOne({ username: "jatobaa" });
const byEmail = await User.findOne({ email: "[email protected]" });
const byId = await User.findOne({ _id: "a1b2c3d4-..." });

// Busca em arrays (contém)
const hasTag = await User.findOne({ tags: "developer" }); // → true se existir

Buscar todos

const all = await User.find(); // array de documentos
all.forEach(u => console.log(u.toJSON()));

❌ Tratamento de Erros

Todos os erros são instâncias de ElephantError com padrão consistente:

try {
  await User.create({ username: "ab" }); // username muito curto
} catch (err) {
  console.log(err.code);     // ex: "INVALID_TYPE"
  console.log(err.message);  // mensagem clara
  console.log(err.details);  // detalhes do Zod ou campo
}

Códigos comuns:

  • REQUIRED_FIELD
  • INVALID_TYPE
  • UNIQUE_VIOLATION
  • NOT_FOUND
  • INVALID_SCHEMA
  • DB_NOT_CONNECTED

🧹 Fechando o Banco

Sempre feche para garantir gravação no disco:

db.close();
console.log("Banco salvo e fechado!");

🧩 Tipagem Avançada (TypeScript)

O tipo do documento é inferido automaticamente:

const User = db.model("User", userSchema);

const user = await User.create({
  username: "jatoba",
  email: "[email protected]",
  age: 25,
});

// Autocomplete perfeito:
user.toJSON().username; // string
user.update({ age: 30 }); // só aceita campos válidos
User.push(user._id, "tags", "ts"); // tipado!

Zero interfaces manuais. Tudo vem do schema Zod.


🧠 Quando usar ElephantDB?

Perfeito para:

  • Aplicações locais / CLIs
  • Bots (Discord, Telegram, etc.)
  • Ferramentas de desenvolvimento
  • Prototipagem rápida
  • Apps Electron / Tauri
  • Micro-serviços leves
  • Qualquer projeto que precise de dados persistentes sem complicação

Não é ideal para:

  • Alta concorrência massiva
  • Aplicações distribuídas em escala (use PostgreSQL/MongoDB)

📄 Licença

MIT © ARC Studio, Inc.


🔗 Links


ElephantDB — Simples. Forte. Inesquecível. 🐘

Pronto para usar em produção hoje.
Bem-vindo ao futuro dos bancos locais em JavaScript.