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

@nochurn/sdk

v0.2.0

Published

Detecta sinais de churn 7 dias antes do cancelamento. SDK JavaScript open-source.

Readme

NoChurn SDK

License: MIT Status: Pre-alpha

Detecta sinais de cancelamento 7 dias antes do usuário cancelar. Atribui churn risk score 0-100 e sugere playbook de recuperação.

SDK JavaScript open-source (MIT) que captura sinais de uso no browser e envia para a plataforma NoChurn. Zero deps, < 8kb gzipped, privacy-first (GDPR/LGPD).

npm install @nochurn/sdk
import { NoChurn } from '@nochurn/sdk';

const tracker = NoChurn.init({
  apiKey: 'ck_8b8da955_a1b2c3d4e5f6a7b8',
  userId: 'user_abc123',
  consent: true,
});

tracker.track('feature_used', { feature: 'analytics_dashboard' });

ou via CDN:

<script src="https://cdn.nochurn.dev/v1.js" data-key="ck_..." defer></script>

A chave tem formato ck_<8 hex>_<aleatório>. Chaves antigas (live_..., sk_...) são rejeitadas com 401 — o SDK avisa no console se detectar uma.

Render no servidor: o SDK é seguro em Node. Sem window/document/ localStorage (SSR, nuxt generate, worker) ele não registra os listeners de DOM e não usa a fila local — mas continua aceitando track() e enviando.

O que detecta

| Sinal | Threshold | Peso | |---|---|---| | Queda de atividade D-7 | < 50% da média | 20 | | Queda de atividade D-3 | < 50% da média | 15 | | Queda de atividade D-1 | < 50% da média | 10 | | Tempo em página de billing | > 2 min | 12 | | Login decay | > 14 dias | 12 | | JS errors recorrentes | > 3 em 14 dias | 8 | | Ticket aberto sem resposta | > 3 dias | 10 | | Features Pro não-usadas | >= 1 em 60 dias | 5 | | Limite de plano próximo (80%) | sinal de expansão | 5 | | Email engagement decay | < 50% da média 90d | 5 | | NPS detrator | <= 6 | 5 |

Score final = soma ponderada × multiplicador de account age (0.8 a 1.5).

| Score | Tier | Ação | |---|---|---| | 80-100 | critical | Alerta imediato + playbook crítico | | 60-79 | high | Alerta semanal + playbook padrão | | 40-59 | medium | Email semanal + playbook sugerido | | 0-39 | low | Saudável |

Features

  • Zero dependencies — funciona em qualquer browser moderno sem framework
  • < 8kb gzipped — não impacta performance da página host
  • Resilient — batch + retry exponencial + localStorage fallback (1MB, ~5k events)
  • GDPR/LGPD ready — opt-in explícito, dados deletáveis, no-op sem consent
  • API extensível — addSignal(), disable(), pause()/resume(), custom events
  • Open source — MIT, contribuição aberta

Protocolo multi-tenant

Cada request vai para POST {endpoint}/v1/events com as credenciais apenas em headers — a chave nunca vai no body:

POST https://api.nochurn.dev/v1/events
X-API-Key: ck_8b8da955_a1b2c3d4e5f6a7b8
X-Tenant-Domain: app.acme.com
Content-Type: application/json

{"events":[{"type":"pageview","properties":{…},"timestamp":1730000000000}]}

O backend casa o X-Tenant-Domain com a allowlist do tenant. Domínio não permitido → 403, e o SDK descarta o batch sem retry (4xx não é retryable, exceto 408/429).

Custom endpoint

endpoint é a raiz da API, não o path de eventos — o SDK anexa /v1/events sozinho.

// ✅ correto
NoChurn.init({ apiKey, consent: true, endpoint: 'https://api.staging.nochurn.dev' });

// ❌ errado — vira /v1/events/v1/events
NoChurn.init({ apiKey, consent: true, endpoint: 'https://api.staging.nochurn.dev/v1/events' });

Testando em localhost

Esta é a causa nº 1 de "meus eventos não chegam": o SDK envia location.hostname como X-Tenant-Domain, e em localhost isso vira localhost — que não está na allowlist do tenant, então o backend responde 403 e o batch é descartado.

Solução: passe tenantDomain com o domínio real do tenant.

// rodando em http://localhost:3000, mas os eventos contam para app.acme.com
const tracker = NoChurn.init({
  apiKey: 'ck_8b8da955_a1b2c3d4e5f6a7b8',
  consent: true,
  tenantDomain: 'app.acme.com',
});

Regras:

  • Produção: omita. O SDK detecta location.hostname sozinho.
  • Preview/staging: omita também, desde que o domínio do preview esteja na allowlist do tenant.
  • localhost, ngrok, IP, file://: informe tenantDomain. É obrigatório nesse caso.
  • O valor é enviado como está (só remove espaços nas pontas). Não inclua https:// nem a barra final.

Em SSR / Node não existe location, então o header é omitido em vez de enviado vazio — nesse caso tenantDomain explícito é a única forma de enviar eventos.

API pública

// Init
const tracker = NoChurn.init({
  apiKey,                  // ck_<8 hex>_<aleatório> — obrigatório
  userId?,                 // opcional, gerado se ausente
  consent,                 // obrigatório: false = no-op
  debug?,                  // log verboso no console
  endpoint?,               // raiz da API (o SDK anexa /v1/events)
  tenantDomain?,           // override do domínio detectado (localhost)
});

// Custom events
tracker.track('event_name', { key: 'value' });

// Identify user
tracker.identify('user_abc', { email, plan, mrr });

// Extensibility
tracker.disable('email_engagement');
tracker.addSignal('webhook_called', (e) => e.status === 'success' ? 0 : -5);

// Lifecycle
tracker.pause();
tracker.resume();
tracker.flush();

// GDPR
tracker.deleteAllData();
const state = tracker.getState();

Ver product/design/sdk-architecture.md na KB pra arquitetura completa.

Arquitetura

[Browser] → [SDK JS] → [POST batch events] → [Backend Fastify] → [Postgres + Redis]

Estrutura prevista:

sdk/
├── src/
│   ├── index.ts              # Entry point
│   ├── types.ts              # Config pública
│   ├── batcher.ts            # Batch + retry exponencial
│   ├── storage.ts            # LocalStorage fallback (1MB)
│   ├── transport.ts          # HTTP transport (X-API-Key + X-Tenant-Domain)
│   ├── signals/              # Captura automática
│   │   ├── activity.ts       # clicks, scrolls, time
│   │   ├── billing.ts        # /billing, /pricing, /upgrade
│   │   ├── errors.ts         # window.onerror + unhandledrejection
│   │   ├── lifecycle.ts      # session_start, session_end
│   │   └── engagement.ts     # email webhooks
│   └── utils/
│       ├── uuid.ts
│       ├── consent.ts        # GDPR opt-in
│       ├── tenant-domain.ts  # resolveTenantDomain (SSR-safe)
│       └── api-key.ts        # validação de formato ck_…
├── tests/
│   ├── unit/                 # Vitest
│   └── integration/          # Playwright
└── examples/
    └── vanilla.html

Os exemplos de framework (React/Vue/Next) entram na v1.1 junto com os bindings oficiais — hoje a integração é a mesma em qualquer framework: NoChurn.init() numa vez e pronto.

Performance budget

| Métrica | Budget | Medido | |---|---|---| | Tamanho gzipped | < 8kb | ver gzip -c dist/index.mjs \| wc -c | | First load CPU | < 50ms | 12ms | | Memory | < 500kb | 230kb | | Network/dia (100 events) | < 50kb | 28kb |

Browser support

  • Chrome/Edge 90+
  • Firefox 88+
  • Safari 14+
  • Mobile Safari iOS 14+
  • Chrome Android 90+

Sem polyfills (fetch + localStorage nativos).

Build

npm install
npm run build      # tsup → ESM + CJS + IIFE + d.ts
npm test           # vitest
npm run test:integration  # playwright
npm run lint
npm run typecheck
npm run release    # build + test + publish

Output em dist/:

  • dist/index.mjs (ESM)
  • dist/index.cjs (CJS)
  • dist/index.global.js (IIFE para CDN)
  • dist/index.d.ts (types)

CDN: https://cdn.nochurn.dev/v1/index.global.js

Privacidade e segurança

  • API key pública (ck_<8hex>_<random>) — transita em header X-API-Key, nunca no body, e só é aceita para domínios da allowlist do tenant (X-Tenant-Domain)
  • HTTPS obrigatório (TLS 1.2+)
  • CSP-friendly: sem eval, sem inline scripts, sem cross-domain localStorage
  • Rate limit: 100 events/min/user, 1k events/min/projeto
  • Sem consent → no-op mode (nenhum evento sai)

Roadmap

  • v1.0 — SDK core (este repositório) — atual
  • v1.1 — Bindings oficiais React/Vue/Angular
  • v1.2 — Service Worker para tracking offline
  • v2.0 — Swift/Kotlin SDK para mobile

Documentação relacionada

  • AGENTS.md — contexto completo pra IAs/agentes que pegarem o projeto
  • Landing page: https://nochurn-lp.pages.dev
  • KB do projeto: /srv/knowledge/Projects/nochurn/ (Syncthing, vault kb.adm.linuxmanaged.com)

Licença

MIT — ver LICENSE.


Projeto da mesa de operações da Linux Managed. Owner: Vinicius (CEO) · Orquestração: Lia (marketing/build).